diff --git a/.gitattributes b/.gitattributes
index 5ce50252724afe0cf88fe8743a19eb3647888707..af93fe8174a5e0ca1106871e189e57ec5bdf4aaa 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -345,3 +345,43 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.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
+.venv/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.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
+.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
+.venv/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.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
+.venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.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
+.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
+.venv/lib/python3.12/site-packages/scipy/sparse/linalg/_propack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.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
+.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
+.venv/lib/python3.12/site-packages/scipy/special/__pycache__/_basic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+.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
+.venv/lib/python3.12/site-packages/scipy/special/_gufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/special/_specfun.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/special/_special_ufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/special/_ufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/special/_ufuncs_cxx.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+.venv/lib/python3.12/site-packages/scipy/special/cython_special.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz
new file mode 100644
index 0000000000000000000000000000000000000000..35d1681786c95602c4f0d5260fc5ad0ff4236189
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1b2a0736b541ebf5c4b9b4c00d6dab281e73c9fb9913c6e2581a781b37b602f9
+size 15878
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz
new file mode 100644
index 0000000000000000000000000000000000000000..ff967f2ca0d0868aacf7d7e67402599e64bab817
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a3dfab451d9d5c20243e0ed85cd8b6c9657669fb9a0f83b5be165585783d55b5
+size 2164
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_basic.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..747a028681d32654ae1fb09364acf52d0c7b8f10
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_basic.py
@@ -0,0 +1,3033 @@
+import os
+import platform
+import math
+import itertools
+import warnings
+
+import numpy as np
+from numpy import (arange, array, dot, zeros, identity, conjugate, transpose,
+ float32)
+
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+ assert_array_almost_equal, assert_allclose,
+ assert_array_equal)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import (solve, inv, det, lstsq, pinv, pinvh, norm,
+ solve_banded, solveh_banded, solve_triangular,
+ solve_circulant, circulant, LinAlgError, block_diag,
+ matrix_balance, qr, LinAlgWarning)
+
+from scipy.linalg._testutils import assert_no_overwrite
+from scipy._lib._testutils import check_free_memory, IS_MUSL
+from scipy.linalg.blas import HAS_ILP64
+from scipy.conftest import skip_xp_invalid_arg
+
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+parametrize_overwrite_arg = pytest.mark.parametrize(
+ "overwrite_kw", [{"overwrite_a": True}, {"overwrite_a": False}, {}],
+ ids=["True", "False", "None"]
+)
+
+
+parametrize_overwrite_b_arg = pytest.mark.parametrize(
+ "overwrite_b_kw", [{"overwrite_b": True}, {"overwrite_b": False}, {}],
+ ids=["True", "False", "None"]
+)
+
+
+def _eps_cast(dtyp):
+ """Get the epsilon for dtype, possibly downcast to BLAS types."""
+ dt = dtyp
+ if dt == np.longdouble:
+ dt = np.float64
+ elif dt == np.clongdouble:
+ dt = np.complex128
+ return np.finfo(dt).eps
+
+
+class TestSolveBanded:
+
+ def test_real(self):
+ a = array([[1.0, 20, 0, 0],
+ [-30, 4, 6, 0],
+ [2, 1, 20, 2],
+ [0, -1, 7, 14]])
+ ab = array([[0.0, 20, 6, 2],
+ [1, 4, 20, 14],
+ [-30, 1, 7, 0],
+ [2, -1, 0, 0]])
+ l, u = 2, 1
+ b4 = array([10.0, 0.0, 2.0, 14.0])
+ b4by1 = b4.reshape(-1, 1)
+ b4by2 = array([[2, 1],
+ [-30, 4],
+ [2, 3],
+ [1, 3]])
+ b4by4 = array([[1, 0, 0, 0],
+ [0, 0, 0, 1],
+ [0, 1, 0, 0],
+ [0, 1, 0, 0]])
+ for b in [b4, b4by1, b4by2, b4by4]:
+ x = solve_banded((l, u), ab, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_complex(self):
+ a = array([[1.0, 20, 0, 0],
+ [-30, 4, 6, 0],
+ [2j, 1, 20, 2j],
+ [0, -1, 7, 14]])
+ ab = array([[0.0, 20, 6, 2j],
+ [1, 4, 20, 14],
+ [-30, 1, 7, 0],
+ [2j, -1, 0, 0]])
+ l, u = 2, 1
+ b4 = array([10.0, 0.0, 2.0, 14.0j])
+ b4by1 = b4.reshape(-1, 1)
+ b4by2 = array([[2, 1],
+ [-30, 4],
+ [2, 3],
+ [1, 3]])
+ b4by4 = array([[1, 0, 0, 0],
+ [0, 0, 0, 1j],
+ [0, 1, 0, 0],
+ [0, 1, 0, 0]])
+ for b in [b4, b4by1, b4by2, b4by4]:
+ x = solve_banded((l, u), ab, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_tridiag_real(self):
+ ab = array([[0.0, 20, 6, 2],
+ [1, 4, 20, 14],
+ [-30, 1, 7, 0]])
+ a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
+ ab[2, :-1], -1)
+ b4 = array([10.0, 0.0, 2.0, 14.0])
+ b4by1 = b4.reshape(-1, 1)
+ b4by2 = array([[2, 1],
+ [-30, 4],
+ [2, 3],
+ [1, 3]])
+ b4by4 = array([[1, 0, 0, 0],
+ [0, 0, 0, 1],
+ [0, 1, 0, 0],
+ [0, 1, 0, 0]])
+ for b in [b4, b4by1, b4by2, b4by4]:
+ x = solve_banded((1, 1), ab, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_tridiag_complex(self):
+ ab = array([[0.0, 20, 6, 2j],
+ [1, 4, 20, 14],
+ [-30, 1, 7, 0]])
+ a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
+ ab[2, :-1], -1)
+ b4 = array([10.0, 0.0, 2.0, 14.0j])
+ b4by1 = b4.reshape(-1, 1)
+ b4by2 = array([[2, 1],
+ [-30, 4],
+ [2, 3],
+ [1, 3]])
+ b4by4 = array([[1, 0, 0, 0],
+ [0, 0, 0, 1],
+ [0, 1, 0, 0],
+ [0, 1, 0, 0]])
+ for b in [b4, b4by1, b4by2, b4by4]:
+ x = solve_banded((1, 1), ab, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_check_finite(self):
+ a = array([[1.0, 20, 0, 0],
+ [-30, 4, 6, 0],
+ [2, 1, 20, 2],
+ [0, -1, 7, 14]])
+ ab = array([[0.0, 20, 6, 2],
+ [1, 4, 20, 14],
+ [-30, 1, 7, 0],
+ [2, -1, 0, 0]])
+ l, u = 2, 1
+ b4 = array([10.0, 0.0, 2.0, 14.0])
+ x = solve_banded((l, u), ab, b4, check_finite=False)
+ assert_array_almost_equal(dot(a, x), b4)
+
+ def test_bad_shape(self):
+ ab = array([[0.0, 20, 6, 2],
+ [1, 4, 20, 14],
+ [-30, 1, 7, 0],
+ [2, -1, 0, 0]])
+ l, u = 2, 1
+ bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1, 4)
+ assert_raises(ValueError, solve_banded, (l, u), ab, bad)
+ assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0])
+
+ # Values of (l,u) are not compatible with ab.
+ assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0])
+
+ def test_1x1(self):
+ # gh-8906 noted that the case of A@x = b with 1x1 A was handled
+ # incorrectly; check that this is resolved. Typical case:
+ # nupper == nlower == 0
+ # A = [[2]]
+ b = array([[1., 2., 3.]])
+ ref = array([[0.5, 1.0, 1.5]])
+ x = solve_banded((0, 0), [[2]], b)
+ assert_allclose(x, ref, rtol=1e-15)
+
+ # However, the user *can* represent the same system with garbage rows
+ # in `ab`. Test the case with `nupper == 1, nlower == 1`.
+ x = solve_banded((1, 1), [[0], [2], [0]], b)
+ assert_allclose(x, ref, rtol=1e-15)
+ assert_equal(x.dtype, np.dtype('f8'))
+ assert_array_equal(b, [[1.0, 2.0, 3.0]])
+
+ def test_native_list_arguments(self):
+ a = [[1.0, 20, 0, 0],
+ [-30, 4, 6, 0],
+ [2, 1, 20, 2],
+ [0, -1, 7, 14]]
+ ab = [[0.0, 20, 6, 2],
+ [1, 4, 20, 14],
+ [-30, 1, 7, 0],
+ [2, -1, 0, 0]]
+ l, u = 2, 1
+ b = [10.0, 0.0, 2.0, 14.0]
+ x = solve_banded((l, u), ab, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt_ab, dt_b):
+ # ab contains one empty row corresponding to the diagonal
+ ab = np.array([[]], dtype=dt_ab)
+ b = np.array([], dtype=dt_b)
+ x = solve_banded((0, 0), ab, b)
+
+ assert x.shape == (0,)
+ assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+ b = np.empty((0, 0), dtype=dt_b)
+ x = solve_banded((0, 0), ab, b)
+
+ assert x.shape == (0, 0)
+ assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+
+class TestSolveHBanded:
+
+ def test_01_upper(self):
+ # Solve
+ # [ 4 1 2 0] [1]
+ # [ 1 4 1 2] X = [4]
+ # [ 2 1 4 1] [1]
+ # [ 0 2 1 4] [2]
+ # with the RHS as a 1D array.
+ ab = array([[0.0, 0.0, 2.0, 2.0],
+ [-99, 1.0, 1.0, 1.0],
+ [4.0, 4.0, 4.0, 4.0]])
+ b = array([1.0, 4.0, 1.0, 2.0])
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+ def test_02_upper(self):
+ # Solve
+ # [ 4 1 2 0] [1 6]
+ # [ 1 4 1 2] X = [4 2]
+ # [ 2 1 4 1] [1 6]
+ # [ 0 2 1 4] [2 1]
+ #
+ ab = array([[0.0, 0.0, 2.0, 2.0],
+ [-99, 1.0, 1.0, 1.0],
+ [4.0, 4.0, 4.0, 4.0]])
+ b = array([[1.0, 6.0],
+ [4.0, 2.0],
+ [1.0, 6.0],
+ [2.0, 1.0]])
+ x = solveh_banded(ab, b)
+ expected = array([[0.0, 1.0],
+ [1.0, 0.0],
+ [0.0, 1.0],
+ [0.0, 0.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_03_upper(self):
+ # Solve
+ # [ 4 1 2 0] [1]
+ # [ 1 4 1 2] X = [4]
+ # [ 2 1 4 1] [1]
+ # [ 0 2 1 4] [2]
+ # with the RHS as a 2D array with shape (3,1).
+ ab = array([[0.0, 0.0, 2.0, 2.0],
+ [-99, 1.0, 1.0, 1.0],
+ [4.0, 4.0, 4.0, 4.0]])
+ b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1, 1)
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, array([0., 1., 0., 0.]).reshape(-1, 1))
+
+ def test_01_lower(self):
+ # Solve
+ # [ 4 1 2 0] [1]
+ # [ 1 4 1 2] X = [4]
+ # [ 2 1 4 1] [1]
+ # [ 0 2 1 4] [2]
+ #
+ ab = array([[4.0, 4.0, 4.0, 4.0],
+ [1.0, 1.0, 1.0, -99],
+ [2.0, 2.0, 0.0, 0.0]])
+ b = array([1.0, 4.0, 1.0, 2.0])
+ x = solveh_banded(ab, b, lower=True)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+ def test_02_lower(self):
+ # Solve
+ # [ 4 1 2 0] [1 6]
+ # [ 1 4 1 2] X = [4 2]
+ # [ 2 1 4 1] [1 6]
+ # [ 0 2 1 4] [2 1]
+ #
+ ab = array([[4.0, 4.0, 4.0, 4.0],
+ [1.0, 1.0, 1.0, -99],
+ [2.0, 2.0, 0.0, 0.0]])
+ b = array([[1.0, 6.0],
+ [4.0, 2.0],
+ [1.0, 6.0],
+ [2.0, 1.0]])
+ x = solveh_banded(ab, b, lower=True)
+ expected = array([[0.0, 1.0],
+ [1.0, 0.0],
+ [0.0, 1.0],
+ [0.0, 0.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_01_float32(self):
+ # Solve
+ # [ 4 1 2 0] [1]
+ # [ 1 4 1 2] X = [4]
+ # [ 2 1 4 1] [1]
+ # [ 0 2 1 4] [2]
+ #
+ ab = array([[0.0, 0.0, 2.0, 2.0],
+ [-99, 1.0, 1.0, 1.0],
+ [4.0, 4.0, 4.0, 4.0]], dtype=float32)
+ b = array([1.0, 4.0, 1.0, 2.0], dtype=float32)
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+ def test_02_float32(self):
+ # Solve
+ # [ 4 1 2 0] [1 6]
+ # [ 1 4 1 2] X = [4 2]
+ # [ 2 1 4 1] [1 6]
+ # [ 0 2 1 4] [2 1]
+ #
+ ab = array([[0.0, 0.0, 2.0, 2.0],
+ [-99, 1.0, 1.0, 1.0],
+ [4.0, 4.0, 4.0, 4.0]], dtype=float32)
+ b = array([[1.0, 6.0],
+ [4.0, 2.0],
+ [1.0, 6.0],
+ [2.0, 1.0]], dtype=float32)
+ x = solveh_banded(ab, b)
+ expected = array([[0.0, 1.0],
+ [1.0, 0.0],
+ [0.0, 1.0],
+ [0.0, 0.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_01_complex(self):
+ # Solve
+ # [ 4 -j 2 0] [2-j]
+ # [ j 4 -j 2] X = [4-j]
+ # [ 2 j 4 -j] [4+j]
+ # [ 0 2 j 4] [2+j]
+ #
+ ab = array([[0.0, 0.0, 2.0, 2.0],
+ [-99, -1.0j, -1.0j, -1.0j],
+ [4.0, 4.0, 4.0, 4.0]])
+ b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j])
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
+
+ def test_02_complex(self):
+ # Solve
+ # [ 4 -j 2 0] [2-j 2+4j]
+ # [ j 4 -j 2] X = [4-j -1-j]
+ # [ 2 j 4 -j] [4+j 4+2j]
+ # [ 0 2 j 4] [2+j j]
+ #
+ ab = array([[0.0, 0.0, 2.0, 2.0],
+ [-99, -1.0j, -1.0j, -1.0j],
+ [4.0, 4.0, 4.0, 4.0]])
+ b = array([[2-1j, 2+4j],
+ [4.0-1j, -1-1j],
+ [4.0+1j, 4+2j],
+ [2+1j, 1j]])
+ x = solveh_banded(ab, b)
+ expected = array([[0.0, 1.0j],
+ [1.0, 0.0],
+ [1.0, 1.0],
+ [0.0, 0.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_tridiag_01_upper(self):
+ # Solve
+ # [ 4 1 0] [1]
+ # [ 1 4 1] X = [4]
+ # [ 0 1 4] [1]
+ # with the RHS as a 1D array.
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+ b = array([1.0, 4.0, 1.0])
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+ def test_tridiag_02_upper(self):
+ # Solve
+ # [ 4 1 0] [1 4]
+ # [ 1 4 1] X = [4 2]
+ # [ 0 1 4] [1 4]
+ #
+ ab = array([[-99, 1.0, 1.0],
+ [4.0, 4.0, 4.0]])
+ b = array([[1.0, 4.0],
+ [4.0, 2.0],
+ [1.0, 4.0]])
+ x = solveh_banded(ab, b)
+ expected = array([[0.0, 1.0],
+ [1.0, 0.0],
+ [0.0, 1.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_tridiag_03_upper(self):
+ # Solve
+ # [ 4 1 0] [1]
+ # [ 1 4 1] X = [4]
+ # [ 0 1 4] [1]
+ # with the RHS as a 2D array with shape (3,1).
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+ b = array([1.0, 4.0, 1.0]).reshape(-1, 1)
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
+
+ def test_tridiag_01_lower(self):
+ # Solve
+ # [ 4 1 0] [1]
+ # [ 1 4 1] X = [4]
+ # [ 0 1 4] [1]
+ #
+ ab = array([[4.0, 4.0, 4.0],
+ [1.0, 1.0, -99]])
+ b = array([1.0, 4.0, 1.0])
+ x = solveh_banded(ab, b, lower=True)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+ def test_tridiag_02_lower(self):
+ # Solve
+ # [ 4 1 0] [1 4]
+ # [ 1 4 1] X = [4 2]
+ # [ 0 1 4] [1 4]
+ #
+ ab = array([[4.0, 4.0, 4.0],
+ [1.0, 1.0, -99]])
+ b = array([[1.0, 4.0],
+ [4.0, 2.0],
+ [1.0, 4.0]])
+ x = solveh_banded(ab, b, lower=True)
+ expected = array([[0.0, 1.0],
+ [1.0, 0.0],
+ [0.0, 1.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_tridiag_01_float32(self):
+ # Solve
+ # [ 4 1 0] [1]
+ # [ 1 4 1] X = [4]
+ # [ 0 1 4] [1]
+ #
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
+ b = array([1.0, 4.0, 1.0], dtype=float32)
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+ def test_tridiag_02_float32(self):
+ # Solve
+ # [ 4 1 0] [1 4]
+ # [ 1 4 1] X = [4 2]
+ # [ 0 1 4] [1 4]
+ #
+ ab = array([[-99, 1.0, 1.0],
+ [4.0, 4.0, 4.0]], dtype=float32)
+ b = array([[1.0, 4.0],
+ [4.0, 2.0],
+ [1.0, 4.0]], dtype=float32)
+ x = solveh_banded(ab, b)
+ expected = array([[0.0, 1.0],
+ [1.0, 0.0],
+ [0.0, 1.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_tridiag_01_complex(self):
+ # Solve
+ # [ 4 -j 0] [ -j]
+ # [ j 4 -j] X = [4-j]
+ # [ 0 j 4] [4+j]
+ #
+ ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
+ b = array([-1.0j, 4.0-1j, 4+1j])
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, [0.0, 1.0, 1.0])
+
+ def test_tridiag_02_complex(self):
+ # Solve
+ # [ 4 -j 0] [ -j 4j]
+ # [ j 4 -j] X = [4-j -1-j]
+ # [ 0 j 4] [4+j 4 ]
+ #
+ ab = array([[-99, -1.0j, -1.0j],
+ [4.0, 4.0, 4.0]])
+ b = array([[-1j, 4.0j],
+ [4.0-1j, -1.0-1j],
+ [4.0+1j, 4.0]])
+ x = solveh_banded(ab, b)
+ expected = array([[0.0, 1.0j],
+ [1.0, 0.0],
+ [1.0, 1.0]])
+ assert_array_almost_equal(x, expected)
+
+ def test_check_finite(self):
+ # Solve
+ # [ 4 1 0] [1]
+ # [ 1 4 1] X = [4]
+ # [ 0 1 4] [1]
+ # with the RHS as a 1D array.
+ ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+ b = array([1.0, 4.0, 1.0])
+ x = solveh_banded(ab, b, check_finite=False)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+ def test_bad_shapes(self):
+ ab = array([[-99, 1.0, 1.0],
+ [4.0, 4.0, 4.0]])
+ b = array([[1.0, 4.0],
+ [4.0, 2.0]])
+ assert_raises(ValueError, solveh_banded, ab, b)
+ assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0])
+ assert_raises(ValueError, solveh_banded, ab, [1.0])
+
+ def test_1x1(self):
+ x = solveh_banded([[1]], [[1, 2, 3]])
+ assert_array_equal(x, [[1.0, 2.0, 3.0]])
+ assert_equal(x.dtype, np.dtype('f8'))
+
+ def test_native_list_arguments(self):
+ # Same as test_01_upper, using python's native list.
+ ab = [[0.0, 0.0, 2.0, 2.0],
+ [-99, 1.0, 1.0, 1.0],
+ [4.0, 4.0, 4.0, 4.0]]
+ b = [1.0, 4.0, 1.0, 2.0]
+ x = solveh_banded(ab, b)
+ assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+ @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt_ab, dt_b):
+ # ab contains one empty row corresponding to the diagonal
+ ab = np.array([[]], dtype=dt_ab)
+ b = np.array([], dtype=dt_b)
+ x = solveh_banded(ab, b)
+
+ assert x.shape == (0,)
+ assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+ b = np.empty((0, 0), dtype=dt_b)
+ x = solveh_banded(ab, b)
+
+ assert x.shape == (0, 0)
+ assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+
+class TestSolve:
+ def test_20Feb04_bug(self):
+ a = [[1, 1], [1.0, 0]] # ok
+ x0 = solve(a, [1, 0j])
+ assert_array_almost_equal(dot(a, x0), [1, 0])
+
+ # gives failure with clapack.zgesv(..,rowmajor=0)
+ a = [[1, 1], [1.2, 0]]
+ b = [1, 0j]
+ x0 = solve(a, b)
+ assert_array_almost_equal(dot(a, x0), [1, 0])
+
+ def test_simple(self):
+ a = [[1, 20], [-30, 4]]
+ for b in ([[1, 0], [0, 1]],
+ [1, 0],
+ [[2, 1], [-30, 4]]
+ ):
+ x = solve(a, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_complex(self):
+ a = array([[5, 2], [2j, 4]], 'D')
+ for b in ([1j, 0],
+ [[1j, 1j], [0, 2]],
+ [1, 0j],
+ array([1, 0], 'D'),
+ ):
+ x = solve(a, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_pos(self):
+ a = [[2, 3], [3, 5]]
+ for lower in [0, 1]:
+ for b in ([[1, 0], [0, 1]],
+ [1, 0]
+ ):
+ x = solve(a, b, assume_a='pos', lower=lower)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_pos_complexb(self):
+ a = [[5, 2], [2, 4]]
+ for b in ([1j, 0],
+ [[1j, 1j], [0, 2]],
+ ):
+ x = solve(a, b, assume_a='pos')
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_sym(self):
+ a = [[2, 3], [3, -5]]
+ for lower in [0, 1]:
+ for b in ([[1, 0], [0, 1]],
+ [1, 0]
+ ):
+ x = solve(a, b, assume_a='sym', lower=lower)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_sym_complexb(self):
+ a = [[5, 2], [2, -4]]
+ for b in ([1j, 0],
+ [[1j, 1j], [0, 2]]
+ ):
+ x = solve(a, b, assume_a='sym')
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_sym_complex(self):
+ a = [[5, 2+1j], [2+1j, -4]]
+ for b in ([1j, 0],
+ [1, 0],
+ [[1j, 1j], [0, 2]]
+ ):
+ x = solve(a, b, assume_a='sym')
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_her_actuallysym(self):
+ a = [[2, 3], [3, -5]]
+ for lower in [0, 1]:
+ for b in ([[1, 0], [0, 1]],
+ [1, 0],
+ [1j, 0],
+ ):
+ x = solve(a, b, assume_a='her', lower=lower)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_simple_her(self):
+ a = [[5, 2+1j], [2-1j, -4]]
+ for b in ([1j, 0],
+ [1, 0],
+ [[1j, 1j], [0, 2]]
+ ):
+ x = solve(a, b, assume_a='her')
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_nils_20Feb04(self):
+ rng = np.random.default_rng(1234)
+ n = 2
+ A = rng.random([n, n])+rng.random([n, n])*1j
+ X = zeros((n, n), 'D')
+ Ainv = inv(A)
+ R = identity(n)+identity(n)*0j
+ for i in arange(0, n):
+ r = R[:, i]
+ X[:, i] = solve(A, r)
+ assert_array_almost_equal(X, Ainv)
+
+ def test_random(self):
+ rng = np.random.default_rng(1234)
+ n = 20
+ a = rng.random([n, n])
+ for i in range(n):
+ a[i, i] = 20*(.1+a[i, i])
+ for i in range(4):
+ b = rng.random([n, 3])
+ x = solve(a, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_random_complex(self):
+ rng = np.random.default_rng(1234)
+ n = 20
+ a = rng.random([n, n]) + 1j * rng.random([n, n])
+ for i in range(n):
+ a[i, i] = 20*(.1+a[i, i])
+ for i in range(2):
+ b = rng.random([n, 3])
+ x = solve(a, b)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_random_sym(self):
+ rng = np.random.default_rng(1234)
+ n = 20
+ a = rng.random([n, n])
+ for i in range(n):
+ a[i, i] = abs(20*(.1+a[i, i]))
+ for j in range(i):
+ a[i, j] = a[j, i]
+ for i in range(4):
+ b = rng.random([n])
+ x = solve(a, b, assume_a="pos")
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_random_sym_complex(self):
+ rng = np.random.default_rng(1234)
+ n = 20
+ a = rng.random([n, n])
+ a = a + 1j*rng.random([n, n])
+ for i in range(n):
+ a[i, i] = abs(20*(.1+a[i, i]))
+ for j in range(i):
+ a[i, j] = conjugate(a[j, i])
+ b = rng.random([n])+2j*rng.random([n])
+ for i in range(2):
+ x = solve(a, b, assume_a="pos")
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_check_finite(self):
+ a = [[1, 20], [-30, 4]]
+ for b in ([[1, 0], [0, 1]], [1, 0],
+ [[2, 1], [-30, 4]]):
+ x = solve(a, b, check_finite=False)
+ assert_array_almost_equal(dot(a, x), b)
+
+ def test_scalar_a_and_1D_b(self):
+ a = 1
+ b = [1, 2, 3]
+ x = solve(a, b)
+ assert_array_almost_equal(x.ravel(), b)
+ assert_(x.shape == (3,), 'Scalar_a_1D_b test returned wrong shape')
+
+ def test_simple2(self):
+ a = np.array([[1.80, 2.88, 2.05, -0.89],
+ [525.00, -295.00, -95.00, -380.00],
+ [1.58, -2.69, -2.90, -1.04],
+ [-1.11, -0.66, -0.59, 0.80]])
+
+ b = np.array([[9.52, 18.47],
+ [2435.00, 225.00],
+ [0.77, -13.28],
+ [-6.22, -6.21]])
+
+ x = solve(a, b)
+ assert_array_almost_equal(x, np.array([[1., -1, 3, -5],
+ [3, 2, 4, 1]]).T)
+
+ def test_simple_complex2(self):
+ a = np.array([[-1.34+2.55j, 0.28+3.17j, -6.39-2.20j, 0.72-0.92j],
+ [-1.70-14.10j, 33.10-1.50j, -1.50+13.40j, 12.90+13.80j],
+ [-3.29-2.39j, -1.91+4.42j, -0.14-1.35j, 1.72+1.35j],
+ [2.41+0.39j, -0.56+1.47j, -0.83-0.69j, -1.96+0.67j]])
+
+ b = np.array([[26.26+51.78j, 31.32-6.70j],
+ [64.30-86.80j, 158.60-14.20j],
+ [-5.75+25.31j, -2.15+30.19j],
+ [1.16+2.57j, -2.56+7.55j]])
+
+ x = solve(a, b)
+ assert_array_almost_equal(x, np. array([[1+1.j, -1-2.j],
+ [2-3.j, 5+1.j],
+ [-4-5.j, -3+4.j],
+ [6.j, 2-3.j]]))
+
+ @pytest.mark.parametrize("assume_a", ['her', 'sym'])
+ def test_symmetric_hermitian(self, assume_a):
+ # An upper triangular matrix will be used for symmetric/hermitian matrix a
+ a = np.array([[-1.84, 0.11-0.11j, -1.78-1.18j, 3.91-1.50j],
+ [0, -4.63, -1.84+0.03j, 2.21+0.21j],
+ [0, 0, -8.87, 1.58-0.90j],
+ [0, 0, 0, -1.36]])
+ b = np.array([[2.98-10.18j, 28.68-39.89j],
+ [-9.58+3.88j, -24.79-8.40j],
+ [-0.77-16.05j, 4.23-70.02j],
+ [7.79+5.48j, -35.39+18.01j]])
+
+ a2 = a.T if assume_a == 'sym' else a.conj().T # for testing `lower`
+ a3 = a + a2 # for reference solution
+ a3[np.arange(4), np.arange(4)] = np.diag(a)
+ ref = solve(a3, b, assume_a='general')
+
+ x = solve(a, b, assume_a=assume_a)
+ assert_array_almost_equal(x, ref)
+ # Also transpose(/conjugate) `a` and test for lower triangular data
+ # This also tests gh-22265 resolution; otherwise, a warning would be emitted
+ x = solve(a2, b, assume_a=assume_a, lower=True)
+ assert_array_almost_equal(x, ref)
+
+ def test_pos_and_sym(self):
+ A = np.arange(1, 10).reshape(3, 3)
+ x = solve(np.tril(A)/9, np.ones(3), assume_a='pos')
+ assert_array_almost_equal(x, [9., 1.8, 1.])
+ x = solve(np.tril(A)/9, np.ones(3), assume_a='sym')
+ assert_array_almost_equal(x, [9., 1.8, 1.])
+
+ def test_singularity(self):
+ a = np.array([[1, 0, 0, 0, 0, 0, 1, 0, 1],
+ [1, 1, 1, 0, 0, 0, 1, 0, 1],
+ [0, 1, 1, 0, 0, 0, 1, 0, 1],
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
+ [1, 0, 1, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1]])
+ b = np.arange(9)[:, None]
+ assert_raises(LinAlgError, solve, a, b)
+
+ @pytest.mark.parametrize('structure',
+ ('diagonal', 'tridiagonal', 'lower triangular',
+ 'upper triangular', 'symmetric', 'hermitian',
+ 'positive definite', 'general', 'banded', None))
+ def test_ill_condition_warning(self, structure):
+ rng = np.random.default_rng(234859349452)
+ n = 10
+ d = np.logspace(0, 50, n)
+ A = np.diag(d)
+ b = rng.random(size=n)
+ message = "(Ill-conditioned matrix|An ill-conditioned matrix)"
+ with pytest.warns(LinAlgWarning, match=message):
+ solve(A, b, assume_a=structure)
+
+ @pytest.mark.parametrize('structure',
+ ('diagonal', 'tridiagonal', 'lower triangular',
+ 'upper triangular', 'symmetric', 'hermitian',
+ 'positive definite', 'general', None))
+ def test_exactly_singular_gh22263(self, structure):
+ n = 10
+ A = np.zeros((n, n))
+ b = np.ones(n)
+ with (pytest.raises(LinAlgError, match="singular"), np.errstate(all='ignore')):
+ solve(A, b, assume_a=structure)
+
+ @pytest.mark.parametrize('b', [0, 1, [0, 1]])
+ def test_singular_scalar(self, b):
+ # regression test for gh-24355: scalar a=0 is singular
+ # thus should raise the same error
+
+ with pytest.raises(LinAlgError):
+ a = np.zeros((1, 1))
+ solve(a, b)
+
+ with pytest.raises(LinAlgError):
+ solve(0, b)
+
+ with pytest.raises(LinAlgError):
+ solve([[0]], b)
+
+ def test_multiple_rhs(self):
+ a = np.eye(2)
+ rng = np.random.default_rng(1234)
+ b = rng.random((2, 12))
+ x = solve(a, b)
+ assert_array_almost_equal(x, b)
+
+ def test_transposed_keyword(self):
+ A = np.arange(9).reshape(3, 3) + 1
+ x = solve(np.tril(A)/9, np.ones(3), transposed=True)
+ assert_array_almost_equal(x, [1.2, 0.2, 1])
+ x = solve(np.tril(A)/9, np.ones(3), transposed=False)
+ assert_array_almost_equal(x, [9, -5.4, -1.2])
+
+ @pytest.mark.skip(reason="1. why? 2. deprecate the kwarg altogether?")
+ def test_transposed_notimplemented(self):
+ a = np.eye(3).astype(complex)
+ with assert_raises(NotImplementedError):
+ solve(a, a, transposed=True)
+
+ def test_nonsquare_a(self):
+ assert_raises(ValueError, solve, [1, 2], 1)
+
+ def test_size_mismatch_with_1D_b(self):
+ assert_array_almost_equal(solve(np.eye(3), np.ones(3)), np.ones(3))
+ assert_raises(ValueError, solve, np.eye(3), np.ones(4))
+
+ def test_assume_a_keyword(self):
+ assert_raises(ValueError, solve, 1, 1, assume_a='zxcv')
+
+ @pytest.mark.parametrize("size", [10, 100])
+ @pytest.mark.parametrize("assume_a", ['gen', 'sym', 'pos', 'her', 'tridiagonal'])
+ @pytest.mark.parametrize(
+ "dtype", [np.float32, np.float64, np.complex64, np.complex128]
+ )
+ def test_all_type_size_routine_combinations(self, size, dtype, assume_a):
+ rng = np.random.default_rng(1234)
+ is_complex = dtype in (np.complex64, np.complex128)
+
+ a = rng.standard_normal((size, size)).astype(dtype)
+ b = rng.standard_normal(size).astype(dtype)
+ if is_complex:
+ a += (1j*rng.standard_normal((size, size))).astype(dtype)
+
+ if assume_a == 'sym': # Can still be complex but only symmetric
+ a = a + a.T
+ elif assume_a == 'her': # Handle hermitian matrices here instead
+ a = a + a.T.conj()
+ elif assume_a == 'pos':
+ a = a.T.conj() @ a + 0.1*np.eye(size)
+ elif assume_a == 'tridiagonal':
+ a = (np.diag(np.diag(a)) +
+ np.diag(np.diag(a, 1), 1) +
+ np.diag(np.diag(a, -1), -1)
+ )
+
+ tol = 1e-12 if dtype in (np.float64, np.complex128) else 1e-6
+
+ if assume_a in ['gen', 'sym', 'her']:
+ # We revert the tolerance from before
+ # 4b4a6e7c34fa4060533db38f9a819b98fa81476c
+ if dtype in (np.float32, np.complex64):
+ tol *= 10
+
+ x = solve(a, b, assume_a=assume_a)
+ assert_allclose(a @ x, b, atol=tol * size, rtol=tol * size)
+
+ if assume_a == 'sym' and not is_complex:
+ x = solve(a, b, assume_a=assume_a, transposed=True)
+ assert_allclose(a @ x, b, atol=tol * size, rtol=tol * size)
+
+ @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt_a, dt_b):
+ a = np.empty((0, 0), dtype=dt_a)
+ b = np.empty(0, dtype=dt_b)
+ x = solve(a, b)
+
+ assert x.size == 0
+ dt_nonempty = solve(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)).dtype
+ assert x.dtype == dt_nonempty
+ assert x.shape == np.linalg.solve(a, b).shape
+
+ a = np.ones((3, 0, 2, 2), dtype=dt_a)
+ b = np.ones((2, 4), dtype=dt_b)
+ x = solve(a, b)
+ assert x.shape == (3, 0, 2, 4)
+ assert x.dtype == dt_nonempty
+
+ def test_empty_rhs(self):
+ a = np.eye(2)
+ b = [[], []]
+ x = solve(a, b)
+ assert_(x.size == 0, 'Returned array is not empty')
+ assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
+
+ @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+ @pytest.mark.parametrize('assume_a', ['diagonal', 'tridiagonal', 'banded',
+ 'lower triangular', 'upper triangular',
+ 'pos', 'positive definite',
+ 'symmetric', 'hermitian', 'general',
+ 'sym', 'her', 'gen'])
+ @pytest.mark.parametrize('nrhs', [(), (5,)])
+ @pytest.mark.parametrize('transposed', [True, False])
+ @pytest.mark.parametrize('overwrite', [True, False])
+ @pytest.mark.parametrize('fortran', [True, False])
+ def test_structure_detection(self, dtype, assume_a, nrhs, transposed,
+ overwrite, fortran):
+ rng = np.random.default_rng(982345982439826)
+ n = 5 if not assume_a == 'banded' else 20
+ b = rng.random(size=(n,) + nrhs)
+ A = rng.random(size=(n, n))
+
+ if np.issubdtype(dtype, np.complexfloating):
+ b = b + rng.random(size=(n,) + nrhs) * 1j
+ A = A + rng.random(size=(n, n)) * 1j
+
+ if assume_a == 'diagonal':
+ A = np.diag(np.diag(A))
+ elif assume_a == 'lower triangular':
+ A = np.tril(A)
+ elif assume_a == 'upper triangular':
+ A = np.triu(A)
+ elif assume_a == 'tridiagonal':
+ A = (np.diag(np.diag(A))
+ + np.diag(np.diag(A, -1), -1)
+ + np.diag(np.diag(A, 1), 1))
+ elif assume_a == 'banded':
+ A = np.triu(np.tril(A, 2), -1)
+ elif assume_a in {'symmetric', 'sym'}:
+ A = A + A.T
+ elif assume_a in {'hermitian', 'her'}:
+ A = A + A.conj().T
+ elif assume_a in {'positive definite', 'pos'}:
+ A = A @ A.T.conj()
+
+ if fortran:
+ A = np.asfortranarray(A)
+
+ A_copy = A.copy(order='A')
+ b_copy = b.copy()
+
+ if np.issubdtype(dtype, np.complexfloating) and transposed:
+ message = "scipy.linalg.solve can currently..."
+ with pytest.raises(NotImplementedError, match=message):
+ solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite,
+ transposed=transposed)
+ return
+
+ res = solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite,
+ transposed=transposed, assume_a=assume_a)
+
+ # Check that solution this solution is *correct*
+ ref = np.linalg.solve(A_copy.T if transposed else A_copy, b_copy)
+ assert_allclose(res, ref)
+
+ # Check that `solve` correctly identifies the structure and returns
+ # *exactly* the same solution whether `assume_a` is specified or not
+ if assume_a != 'banded': # structure detection removed for banded
+ assert_allclose(
+ solve(A_copy, b_copy, transposed=transposed), res, atol=1e-15
+ )
+
+ # Check that overwrite was respected
+ if not overwrite:
+ assert_equal(A, A_copy)
+ assert_equal(b, b_copy)
+
+ @pytest.mark.parametrize(
+ "assume_a",
+ [
+ None, "diagonal", "general", "upper triangular", "lower triangular", "pos",
+ ]
+ )
+ def test_vs_np_solve(self, assume_a):
+ e = np.eye(2)
+ a = np.arange(1, 4*3*2 + 1).reshape((4, 3, 2, 1, 1)) * e
+
+ b = np.ones(2)
+ assert_allclose(solve(a, b, assume_a=assume_a), np.linalg.solve(a, b))
+
+ b = np.ones((2, 1))
+ assert_allclose(solve(a, b, assume_a=assume_a), np.linalg.solve(a, b))
+
+ b = np.ones((2, 2)) * [1, 2]
+ assert_allclose(solve(a, b, assume_a=assume_a), np.linalg.solve(a, b))
+
+ def test_pos_lower(self):
+ # regression test for
+ # https://github.com/scipy/scipy/pull/23071#issuecomment-3085826112
+ rng = np.random.default_rng(0)
+ a = rng.normal(size=(4, 4))
+ a = np.tril(np.matmul(a, np.conj(a.T))) # lower triangle of hermitian array
+ b = rng.normal(size=(4, 2))
+ out = solve(a, b, assume_a='pos', lower=True)
+
+ aa = a + a.T - np.diag(np.diag(a)) # the full hermitian array
+ result_np = np.linalg.solve(aa, b)
+ assert_allclose(out, result_np, atol=1e-15)
+
+ # repeat with uplo='U'
+ out = solve(a.T, b, assume_a='pos', lower=False)
+ assert_allclose(out, result_np, atol=1e-15)
+
+ def test_pos_fails_sym_complex(self):
+ # regression test for the `solve` analog of gh-24359
+ # the matrix is 1) symmetric not hermitian, and 2) not positive definite:
+ a = np.asarray([[ 182.56985285-64.28859483j, -177.24879835+11.0780499j ],
+ [-177.24879835+11.0780499j , 177.24879835-11.0780499j ]])
+ b = np.eye(2)
+
+ ainv = solve(a, b)
+ assert_allclose(ainv @ a, np.eye(2), atol=1e-14)
+
+ ainv_sym = solve(a, b, assume_a="sym")
+ assert_allclose(ainv_sym, ainv, atol=1e-14)
+
+ # Specifying assume_a="pos" disables the structure detection, and directly
+ # calls LAPACK routines zportf and zpotri.
+ # Since zportf(a) does not error out, neither does solve.
+ ainv_chol = solve(a, b, assume_a="pos")
+ assert not np.allclose(ainv, ainv_chol, atol=1e-14)
+
+ # Setting assume_a="pos" with a non-pos def matrix returned nonsense.
+ # This is at least consistent with inv.
+ ainv_inv = inv(a, assume_a="pos")
+ assert_allclose(ainv_chol, ainv_inv, atol=1e-14)
+
+ def test_readonly(self):
+ a = np.eye(3)
+ a.flags.writeable = False
+ b = np.ones(3)
+ x = solve(a, b)
+ assert_allclose(x, b, atol=1e-14)
+
+ @parametrize_overwrite_arg
+ def test_batch_negative_stride(self, overwrite_kw):
+ a = np.arange(3*8).reshape(2, 3, 2, 2)
+ a = a[:, ::-1, :, :]
+ b = np.ones(2)
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1]
+ assert_allclose(a @ x[..., None] - b, 0, atol=1e-14)
+
+ # use b with a negative stride now
+ b = np.ones((2, 4))[:, ::-1]
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1] + (b.shape[-1],)
+ assert_allclose(a @ x - b, 0, atol=1e-14)
+
+ @parametrize_overwrite_arg
+ def test_core_negative_stride(self, overwrite_kw):
+ a = np.arange(3*8).reshape(2, 3, 2, 2)
+ a = a[:, :, ::-1, :]
+ b = np.ones(2)
+ x = solve(a, b, **overwrite_kw)
+
+ assert x.shape == a.shape[:-1]
+ assert_allclose(a @ x[..., None] - b, 0, atol=1e-14)
+
+ # use b with a negative stride now
+ b = np.ones((2, 4))[::-1, :]
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1] + (b.shape[-1],)
+ assert_allclose(a @ x - b, 0, atol=1e-14)
+
+ @parametrize_overwrite_arg
+ def test_core_non_contiguous(self, overwrite_kw):
+ a = np.arange(3*8*2).reshape(2, 3, 2, 4)
+ a = a[..., ::2]
+ b = np.ones(2)
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1]
+ assert_allclose(a @ x[..., None] - b, 0, atol=1e-14)
+
+ # use strided b now
+ b = np.ones(4)[::2]
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1]
+ assert_allclose(a @ x[..., None] - b, 0, atol=1e-14)
+
+ @parametrize_overwrite_arg
+ def test_batch_non_contiguous(self, overwrite_kw):
+ a = np.arange(3*8*2).reshape(2, 6, 2, 2)
+ a = a[:, ::2, ...]
+ b = np.ones(2)
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1]
+ assert_allclose(a @ x[..., None] - b, 0, atol=1e-14)
+
+ # use strided b now
+ b = np.ones((2, 6))[:, ::2]
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1] + (b.shape[-1],)
+ assert_allclose(a @ x - b, 0, atol=1e-14)
+
+ @parametrize_overwrite_arg
+ def test_batch_weird_strides(self, overwrite_kw):
+ a = np.arange(3*8*2).reshape(2, 3, 2, 2, 2)
+ a = a.transpose(1, 3, 4, 0, 2)
+
+ b = np.ones(2)
+ x = solve(a, b, **overwrite_kw)
+ assert x.shape == a.shape[:-1]
+ assert_allclose(a @ x[..., None] - b, 0, atol=1e-14)
+
+ @parametrize_overwrite_arg
+ @parametrize_overwrite_b_arg
+ @pytest.mark.parametrize('a_dtype', [int, float])
+ @pytest.mark.parametrize('a_order', ['C', 'F'])
+ @pytest.mark.parametrize('b_dtype', [int, float])
+ @pytest.mark.parametrize('b_order', ['C', 'F'])
+ @pytest.mark.parametrize('b_ndim', [1, 2]) # XXX ndim > 2
+ @pytest.mark.parametrize('transposed', [True, False])
+ @pytest.mark.parametrize('assume_a', [None, "banded"]) # separate branches in C code
+ def test_overwrite_args(
+ self, overwrite_kw, overwrite_b_kw, a_dtype, a_order,
+ b_dtype, b_order, b_ndim, transposed, assume_a
+ ):
+ n = 3
+ a = np.arange(1, n**2 + 1).reshape(n, n) + np.eye(n)
+ a = a.astype(a_dtype, order=a_order)
+
+ b = np.arange(n)
+ if b_ndim > 1:
+ b = np.stack([b*j for j in range(b_ndim)]).T
+ b = b.astype(b_dtype, order=b_order)
+
+ a_ref = a.copy()
+ b_ref = b.copy()
+
+ # solve and check that the solution is correct for all parameters
+ x = solve(a, b, **overwrite_kw, **overwrite_b_kw,
+ transposed=transposed, assume_a=assume_a)
+ a_or_aT = a_ref.T if transposed else a_ref
+ assert_allclose(a_or_aT @ x, b_ref, atol=1e-14)
+
+ # now check that it worked in-place where expected
+ overwrite_a = overwrite_kw.get('overwrite_a', False)
+ a_inplace = overwrite_a and (a.dtype != int) and a.flags['F_CONTIGUOUS']
+
+ overwrite_b = overwrite_b_kw.get('overwrite_b', False)
+ b_inplace = overwrite_b and (b.dtype != int) and b.flags['F_CONTIGUOUS']
+
+ assert np.shares_memory(x, b) == b_inplace
+
+ # for `assume_a="banded"`, the `overwrite_a` argument is ignored for now
+ assert (b == b_ref).all() != b_inplace
+ assert (a == a_ref).all() != a_inplace or assume_a == "banded"
+
+ def test_posdef_not_posdef(self):
+ # the `b` matrix is invertible but not positive definite
+ a = np.arange(9).reshape(3, 3)
+ A = a + a.T + np.eye(3)
+ b = np.ones(3)
+
+ # cholesky solver fails, and the routine falls back to the general inverse
+ x0 = solve(A, b)
+ assert_allclose(A @ x0, b, atol=1e-14)
+
+ # but it does not fall back if `assume_a` is given
+ with assert_raises(LinAlgError):
+ solve(A, b, assume_a='pos')
+
+ def test_diagonal(self):
+ a = np.stack([np.triu(np.ones((3, 3))), np.diag(np.arange(1, 4))])
+ b = np.ones(3)
+ x = solve(a, b)
+
+ # basic diagonal solve
+ assert_allclose(x[1, ...], 1 / np.arange(1, 4), atol=1e-14)
+
+ # ill-conditioned inputs warn
+ a = np.asarray([[1e30, 0], [0, 1]])
+ b = np.ones(2)
+ with pytest.warns(LinAlgWarning):
+ solve(a, b, assume_a="diagonal")
+
+ # singular input raises
+ a = np.asarray([[0, 0], [0, 1]])
+ b = np.ones(2)
+ with pytest.raises(LinAlgError):
+ solve(a, b, assume_a="diagonal")
+
+ def test_tridiagonal(self):
+ n = 4
+ a = -2*np.diag(np.ones(n)) + np.diag(np.ones(3), 1) + np.diag(np.ones(3), -1)
+ a = np.stack([np.triu(np.ones((n, n))), a])
+ b = np.ones(4)
+ x = solve(a, b)
+
+ # basic tridiag solve
+ assert_allclose(x[1, ...], np.asarray([-2., -3., -3., -2.]), atol=1e-15)
+
+ # ill-conditioned inputs warn
+ a[1, 0, 0] = 1e20
+ with pytest.warns(LinAlgWarning):
+ solve(a, b, assume_a="tridiagonal")
+
+ # singular inputss raise
+ a[1, 0, 0] = a[1, 0, 1] = 0
+ with pytest.raises(LinAlgError):
+ solve(a, b, assume_a="tridiagonal")
+
+ def test_banded(self):
+ rng = np.random.default_rng(982345982439826)
+
+ n = 20
+ A = rng.random((n, n))
+ b = rng.random(n)
+
+ # test if even for full matrix solver gives correct results
+ ref = np.linalg.solve(A, b)
+ res = solve(A, b, assume_a="banded")
+ assert_allclose(ref, res, atol=1e-14)
+
+ # restrict to banded
+ A = np.triu(np.tril(A, k=5), k=-7)
+ ref = np.linalg.solve(A, b)
+ res = solve(A, b, assume_a="banded")
+ assert_allclose(ref, res, atol=1e-14)
+
+ # ill-conditioned inputs warn
+ A[0, 0] = 1e40
+ with pytest.warns(LinAlgWarning):
+ solve(A, b, assume_a="banded")
+
+ # singular inputs raise
+ A[-1, :] = 0
+ with pytest.raises(LinAlgError):
+ solve(A, b, assume_a="banded")
+
+
+class TestSolveTriangular:
+
+ def test_simple(self):
+ """
+ solve_triangular on a simple 2x2 matrix.
+ """
+ A = array([[1, 0], [1, 2]])
+ b = [1, 1]
+ sol = solve_triangular(A, b, lower=True)
+ assert_array_almost_equal(sol, [1, 0])
+
+ # check that it works also for non-contiguous matrices
+ sol = solve_triangular(A.T, b, lower=False)
+ assert_array_almost_equal(sol, [.5, .5])
+
+ # and that it gives the same result as trans=1
+ sol = solve_triangular(A, b, lower=True, trans=1)
+ assert_array_almost_equal(sol, [.5, .5])
+
+ b = identity(2)
+ sol = solve_triangular(A, b, lower=True, trans=1)
+ assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]])
+
+ def test_simple_complex(self):
+ """
+ solve_triangular on a simple 2x2 complex matrix
+ """
+ A = array([[1+1j, 0], [1j, 2]])
+ b = identity(2)
+ sol = solve_triangular(A, b, lower=True, trans=1)
+ assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]])
+
+ # check other option combinations with complex rhs
+ b = np.diag([1+1j, 1+2j])
+ sol = solve_triangular(A, b, lower=True, trans=0)
+ assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
+
+ sol = solve_triangular(A, b, lower=True, trans=1)
+ assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
+
+ sol = solve_triangular(A, b, lower=True, trans=2)
+ assert_array_almost_equal(sol, [[1j, -0.75-0.25j], [0, 0.5+1j]])
+
+ sol = solve_triangular(A.T, b, lower=False, trans=0)
+ assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
+
+ sol = solve_triangular(A.T, b, lower=False, trans=1)
+ assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
+
+ sol = solve_triangular(A.T, b, lower=False, trans=2)
+ assert_array_almost_equal(sol, [[1j, 0], [-0.5, 0.5+1j]])
+
+ def test_check_finite(self):
+ """
+ solve_triangular on a simple 2x2 matrix.
+ """
+ A = array([[1, 0], [1, 2]])
+ b = [1, 1]
+ sol = solve_triangular(A, b, lower=True, check_finite=False)
+ assert_array_almost_equal(sol, [1, 0])
+
+ @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt_a, dt_b):
+ a = np.empty((0, 0), dtype=dt_a)
+ b = np.empty(0, dtype=dt_b)
+ x = solve_triangular(a, b)
+
+ assert x.size == 0
+ dt_nonempty = solve_triangular(
+ np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)
+ ).dtype
+ assert x.dtype == dt_nonempty
+
+ def test_empty_rhs(self):
+ a = np.eye(2)
+ b = [[], []]
+ x = solve_triangular(a, b)
+ assert_(x.size == 0, 'Returned array is not empty')
+ assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
+
+
+class TestInv:
+ def test_simple(self):
+ a = [[1, 2], [3, 4]]
+ a_inv = inv(a)
+ assert_array_almost_equal(dot(a, a_inv), np.eye(2))
+ a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]]
+ a_inv = inv(a)
+ assert_array_almost_equal(dot(a, a_inv), np.eye(3))
+
+ def test_random(self):
+ rng = np.random.default_rng(1234)
+ n = 20
+ for i in range(4):
+ a = rng.random([n, n])
+ for i in range(n):
+ a[i, i] = 20*(.1+a[i, i])
+ a_inv = inv(a)
+ assert_array_almost_equal(dot(a, a_inv),
+ identity(n))
+
+ def test_simple_complex(self):
+ a = [[1, 2], [3, 4j]]
+ a_inv = inv(a)
+ assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
+
+ def test_random_complex(self):
+ rng = np.random.default_rng(1234)
+ n = 20
+ for i in range(4):
+ a = rng.random([n, n])+2j*rng.random([n, n])
+ for i in range(n):
+ a[i, i] = 20*(.1+a[i, i])
+ a_inv = inv(a)
+ assert_array_almost_equal(dot(a, a_inv),
+ identity(n))
+
+ def test_check_finite(self):
+ a = [[1, 2], [3, 4]]
+ a_inv = inv(a, check_finite=False)
+ assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ a_inv = inv(a)
+ assert a_inv.size == 0
+ assert a_inv.dtype == inv(np.eye(2, dtype=dt)).dtype
+
+ a = np.ones((3, 0, 2, 2), dtype=dt)
+ a_inv = inv(a)
+ assert a_inv.shape == (3, 0, 2, 2)
+
+ a = np.ones((3, 1, 0, 0), dtype=dt)
+ a_inv = inv(a)
+ assert a_inv.shape == (3, 1, 0, 0)
+
+ @parametrize_overwrite_arg
+ def test_overwrite_a(self, overwrite_kw):
+ n = 3
+ a0 = np.arange(1, n**2 + 1).reshape(n, n) + np.eye(n)
+
+ # int arrays are copied internally
+ a = a0.copy()
+ a_inv = inv(a, **overwrite_kw)
+ assert_allclose(a_inv @ a, np.eye(n), atol=1e-14)
+ assert_equal(a, a0)
+ assert not np.shares_memory(a, a_inv)
+
+ # float C ordered arrays are copied, too
+ a = a0.copy().astype(float)
+ a_inv = inv(a, **overwrite_kw)
+ assert_allclose(a_inv @ a0, np.eye(n), atol=1e-14)
+ assert_equal(a, a0)
+ assert not np.shares_memory(a, a_inv)
+
+ # 2D F-ordered arrays of LAPACK-compatible dtypes: inv works inplace.
+ # IOW, the output is always the inverse, and the original input may be
+ # destroyed, depending on the `overwrite_a` kwarg value
+ a = a0.astype(float).copy(order='F')
+ a_inv = inv(a, **overwrite_kw)
+ assert_allclose(a_inv @ a0, np.eye(n), atol=1e-14)
+
+ overwrite_a = overwrite_kw.get("overwrite_a", False)
+ assert (a == a0).all() != overwrite_a
+ assert np.shares_memory(a, a_inv) == overwrite_a
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ @pytest.mark.parametrize(
+ "dtyp", [np.float16, np.float32, np.longdouble, np.clongdouble]
+ )
+ def test_dtypes(self, dtyp):
+ # backwards compat: inv(float16)->float32 ; inv(clongdouble)->complex128 etc
+ a = np.arange(4).reshape(2, 2).astype(dtyp)
+
+ a_inv = inv(a)
+ assert_allclose(a @ a_inv, np.eye(a.shape[0]), atol=100*np.finfo(a.dtype).eps)
+
+ dt_map = {
+ 'e': 'f', # float16 -> float32
+ 'f': 'f',
+ 'g': 'd', # longdouble -> float64
+ 'G': 'D' # clongdouble -> complex128
+ }
+ assert a_inv.dtype.char == dt_map[a.dtype.char]
+
+ def test_readonly(self):
+ a = np.eye(3)
+ a.flags.writeable = False
+
+ a_inv = inv(a)
+ assert_allclose(a_inv, a, atol=1e-14)
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_batch_core_1x1(self, dt):
+ a = np.arange(3*2, dtype=dt).reshape(3, 2, 1, 1) + 1
+ a_inv = inv(a)
+ assert a_inv.shape == a.shape
+ assert_allclose(a @ a_inv, 1.)
+
+ @parametrize_overwrite_arg
+ def test_batch_zero_stride(self, overwrite_kw):
+ a = np.arange(3*2*2, dtype=float).reshape(3, 2, 2)
+ aa = a[None, ...]
+ a_inv = inv(aa, **overwrite_kw)
+ assert a_inv.shape == aa.shape
+ assert_allclose(aa @ a_inv, np.broadcast_to(np.eye(2), aa.shape), atol=2e-14)
+
+ aa = a[:, None, ...]
+ a_inv = inv(aa, **overwrite_kw)
+ assert a_inv.shape == aa.shape
+ assert_allclose(aa @ a_inv, np.broadcast_to(np.eye(2), aa.shape), atol=2e-14)
+
+ @parametrize_overwrite_arg
+ def test_batch_negative_stride(self, overwrite_kw):
+ a = np.arange(3*8).reshape(2, 3, 2, 2)
+ a = a[:, ::-1, :, :]
+ a_inv = inv(a, **overwrite_kw)
+ assert a_inv.shape == a.shape
+ assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=5e-14)
+
+ @parametrize_overwrite_arg
+ def test_core_negative_stride(self, overwrite_kw):
+ a = np.arange(3*8).reshape(2, 3, 2, 2)
+ a = a[:, :, ::-1, :]
+ a_inv = inv(a, **overwrite_kw)
+ assert a_inv.shape == a.shape
+ assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=5e-14)
+
+ @parametrize_overwrite_arg
+ def test_core_non_contiguous(self, overwrite_kw):
+ a = np.arange(3*8*2).reshape(2, 3, 2, 4)
+ a = a[..., ::2]
+ a_inv = inv(a, **overwrite_kw)
+ assert a_inv.shape == (2, 3, 2, 2)
+ assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=5e-14)
+
+ @parametrize_overwrite_arg
+ def test_batch_non_contiguous(self, overwrite_kw):
+ a = np.arange(3*8*2).reshape(2, 6, 2, 2)
+ a = a[:, ::2, ...]
+ a_inv = inv(a, **overwrite_kw)
+ assert a_inv.shape == (2, 3, 2, 2)
+ assert_allclose(a @ a_inv, np.broadcast_to(np.eye(2), a.shape), atol=2e-13)
+
+ @parametrize_overwrite_arg
+ def test_singular(self, overwrite_kw):
+ # 2D case: A singular matrix: raise
+
+ with assert_raises(LinAlgError):
+ inv(np.ones((2, 2)))
+
+ # batched case: If all slices are singlar, raise
+ with assert_raises(LinAlgError):
+ inv(np.ones((3, 2, 2)))
+
+ # XXX: shall we make this behavior configurable somehow?
+ # A "keep-going" option would be this:
+ # if some of the slices are singular and some are not,
+ # - singular slices are filled with nans
+ # - non-singular slices are inverted
+ # - there is no error
+ a = np.stack((np.ones((2, 2), dtype=complex), np.arange(4).reshape(2, 2)))
+ with assert_raises(LinAlgError):
+ inv(a)
+
+ # this would be true for a "keep-going" option
+ # assert np.isnan(a_inv[0, ...]).all()
+ # assert_allclose(a_inv[1, ...] @ a[1, ...], np.eye(2), atol=1e-14)
+
+ def test_ill_cond(self):
+ a = np.diag([1., 1e-20])
+ with pytest.warns(LinAlgWarning):
+ inv(a)
+
+ a2 = np.stack([np.diag([1., 1e-20]), np.diag([1, 1]), np.diag([1, 1e-20])])
+ with pytest.warns(LinAlgWarning):
+ inv(a2)
+
+ def test_wrong_assume_a(self):
+ with assert_raises(KeyError):
+ inv(np.eye(2), assume_a="kaboom")
+
+ def test_posdef(self):
+ x = np.arange(25, dtype=float).reshape(5, 5)
+ y = x + x.T
+ y += 21*np.eye(5)
+
+ y_inv0 = inv(y)
+ y_inv1 = inv(y, assume_a="pos")
+
+ assert_allclose(y_inv1, y_inv0, atol=1e-15)
+
+ # check that the lower triangle is not referenced for `lower=False`
+ mask = np.where(1 - np.tri(*y.shape, -1) == 0, np.nan, 1)
+ y_inv2 = inv(y*mask, check_finite=False, assume_a="pos", lower=False)
+ assert_allclose(y_inv2, y_inv0, atol=1e-15)
+
+ # repeat with the upper triangle
+ y_inv3 = inv(y*mask.T, check_finite=False, assume_a="pos", lower=True)
+ assert_allclose(y_inv3, y_inv0, atol=1e-15)
+
+ @pytest.mark.parametrize('complex_', [False, True])
+ def test_posdef_not_posdef(self, complex_):
+ # the `b` matrix is invertible but not pos definite: test the "sym" fallback
+ a = np.arange(9).reshape(3, 3)
+ b = a + a.T + np.eye(3)
+ if complex_:
+ b = b + 1j*b
+
+ # cholesky solver fails, and the routine falls back to the symmetric inverse
+ b_inv0 = inv(b)
+ assert_allclose(b_inv0 @ b, np.eye(3), atol=3e-15)
+
+ # but it does not fall back if `assume_a` is given
+ with assert_raises(LinAlgError):
+ inv(b, assume_a='pos')
+
+ # test posdef fallback to the hermitian solver, too
+ if complex_:
+ a = np.arange(9).reshape(3, 3)
+ a = a + 1j*a
+ b = a + a.T.conj() + np.eye(3)
+ assert_allclose(inv(b) @ b, np.eye(3), atol=3e-15)
+
+ def test_pos_fails_sym_complex(self):
+ # regression test for gh-24359
+ # the matrix is 1) symmetric not hermitian, and 2) not positive definite:
+ a = np.asarray([[ 182.56985285-64.28859483j, -177.24879835+11.0780499j ],
+ [-177.24879835+11.0780499j , 177.24879835-11.0780499j ]])
+
+ ainv = inv(a)
+ assert_allclose(ainv @ a, np.eye(2), atol=1e-14)
+
+ ainv_sym = inv(a, assume_a="sym")
+ assert_allclose(ainv_sym, ainv, atol=1e-14)
+
+ # Specifying assume_a="pos" disables the structure detection, and directly
+ # calls LAPACK routines zportf and zpotri.
+ # Since zportf(a) does not error out, neither does inv
+ ainv_chol = inv(a, assume_a="pos")
+ assert not np.allclose(ainv, ainv_chol, atol=1e-14)
+
+ # Setting assume_a="pos" with a non-pos def matrix returned nonsense.
+ # This is at least consistent with solve.
+ ainv_slv = solve(a, np.eye(2), assume_a="pos")
+ assert_allclose(ainv_chol, ainv_slv, atol=1e-14)
+
+ # Repeat it for bunch of simple cases to cover more branches
+ # Real symmetric, positive definite
+ a = np.eye(4) + np.ones(4)
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(4), atol=1e-14)
+
+ # Real symmetric, NOT positive definite
+ a = -np.eye(4) + np.ones(4)
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(4), atol=1e-14)
+
+ # Real, not symmetric
+ a = -np.eye(4) + np.ones(4)
+ a[0, -1] = 2.
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(4), atol=1e-14)
+
+ # | Test | is_symm | is_herm | pos def |
+ # |---------------------------------------|---------|---------|---------|
+ # | Complex, both sym+herm, pos def | 1 | 1 | yes |
+ # | Complex, symmetric only | 1 | 0 | - |
+ # | Complex, both sym+herm, NOT pos def | 1 | 1 | no |
+ # | Complex, neither | 0 | 0 | - |
+ # | Complex, hermitian only, pos def | 0 | 1 | yes |
+ # | Complex, hermitian only, NOT pos def | 0 | 1 | no |
+
+ # Complex, both symmetric and hermitian, positive definite
+ a = (np.eye(4) + np.ones(4)).astype(np.complex128)
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(4), atol=1e-14)
+
+ # Complex, symmetric only (not hermitian)
+ a = (np.eye(4)*1.0j + np.ones(4)).astype(np.complex128)
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(4), atol=1e-14)
+
+ # Complex, both symmetric and hermitian, NOT positive definite
+ a = (-np.eye(4) + np.ones(4)).astype(np.complex128)
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(4), atol=1e-14)
+
+ # Complex, neither symmetric nor hermitian
+ a = (-np.eye(4) + np.ones(4)).astype(np.complex128)
+ a[0, -1] = 2.
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(4), atol=1e-14)
+
+ # Complex, hermitian only, positive definite
+ a = np.array([[2, 1+1j], [1-1j, 2]], dtype=np.complex128)
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(2), atol=1e-14)
+
+ # Complex, hermitian only, NOT positive definite
+ a = np.array([[-1, 1+1j], [1-1j, -1]], dtype=np.complex128)
+ res = inv(a)
+ assert_allclose(res @ a, np.eye(2), atol=1e-14)
+
+ @pytest.mark.parametrize('complex_', [False, True])
+ @pytest.mark.parametrize('sym_herm', ['sym', 'her'])
+ def test_sym_her(self, complex_, sym_herm):
+ # test "sym" and "her" modes
+ a = np.arange(9).reshape(3, 3)
+ if complex_:
+ a = a + 1j*a
+
+ if sym_herm == "sym":
+ b = a + a.T
+ else: # sym_herm == "herm":
+ b = a + a.T.conj()
+
+ b = b + np.eye(3)
+
+ b_inv0 = np.linalg.inv(b)
+ assert_allclose(b_inv0 @ b, np.eye(3), atol=1e-14)
+
+ b_inv1 = inv(b, assume_a=sym_herm)
+ assert_allclose(b_inv0, b_inv1, atol=1e-15)
+
+ # check that the "other" triangle is not referenced
+ mask = np.where(1 - np.tri(*a.shape, -1) == 0, np.nan, 1)
+ b_inv2 = inv(b*mask, check_finite=False, assume_a=sym_herm, lower=False)
+ assert_allclose(b_inv2, b_inv0, atol=1e-15)
+
+ # repeat with the upper triangle
+ b_inv3 = inv(b*mask.T, check_finite=False, assume_a=sym_herm, lower=True)
+ assert_allclose(b_inv3, b_inv0, atol=1e-15)
+
+ def test_triangular_1(self):
+ x = np.arange(25, dtype=float).reshape(5, 5)
+ y = x + x.T
+ y += 21*np.eye(5)
+ y_inv0 = inv(y, assume_a='upper triangular')
+
+ # check that upper triangular differs from posdef
+ y_inv_posdef = inv(y, assume_a='pos')
+ assert not np.allclose(y_inv0, y_inv_posdef)
+
+ def test_triangular_2(self):
+ y = np.ones(25, dtype=float).reshape(5, 5)
+
+ y_inv_0_u = inv(np.triu(y))
+ assert_allclose(y_inv_0_u @ np.triu(y), np.eye(5), atol=1e-15)
+
+ y_inv_1_u = inv(y, assume_a='upper triangular')
+ assert_allclose(y_inv_1_u @ np.triu(y), np.eye(5), atol=1e-15)
+
+ # check that the lower triangle is not referenced for "upper triangular"
+ mask = np.where(1 - np.tri(*y.shape, -1) == 0, np.nan, 1)
+ y_inv_2_u = inv(y*mask, check_finite=False, assume_a='upper triangular')
+ assert_allclose(y_inv_2_u @ np.triu(y), np.eye(5), atol=1e-15)
+
+ # repeat for the lower traingular matrix
+ y_inv_0_l = inv(np.tril(y))
+ assert_allclose(y_inv_0_l @ np.tril(y), np.eye(5), atol=1e-15)
+
+ y_inv_1_l = inv(y, assume_a='lower triangular')
+ assert_allclose(y_inv_1_l @ np.tril(y), np.eye(5), atol=1e-15)
+
+ # check that the lower triangle is not referenced for "lower triangular"
+ mask = np.where(1 - np.tri(*y.shape, -1) == 0, np.nan, 1)
+ y_inv_2_l = inv(y*mask.T, check_finite=False, assume_a='lower triangular')
+ assert_allclose(y_inv_2_l @ np.tril(y), np.eye(5), atol=1e-15)
+
+ def test_diagonal(self):
+ a = np.stack([np.triu(np.ones((3, 3))), np.diag(np.arange(1, 4))])
+ inv_a = inv(a)
+
+ # basic diagonal invert
+ assert_allclose(inv_a[1], np.diag(1 / np.arange(1, 4)), atol=1e-14)
+
+ # ill-conditioned inputs warn
+ a = np.asarray([[1e30, 0], [0, 1]])
+ with pytest.warns(LinAlgWarning):
+ inv(a, assume_a="diagonal")
+
+ # singular input raises
+ a = np.asarray([[0, 0], [0, 1]])
+ with pytest.raises(LinAlgError):
+ inv(a, assume_a="diagonal")
+
+
+class TestDet:
+ def test_1x1_all_singleton_dims(self):
+ a = np.array([[1]])
+ deta = det(a)
+ assert deta.dtype.char == 'd'
+ assert np.isscalar(deta)
+ assert deta == 1.
+ a = np.array([[[[1]]]], dtype='f')
+ deta = det(a)
+ assert deta.dtype.char == 'd'
+ assert deta.shape == (1, 1)
+ assert_equal(deta, [[1.0]])
+ a = np.array([[[1 + 3.j]]], dtype=np.complex64)
+ deta = det(a)
+ assert deta.dtype.char == 'D'
+ assert deta.shape == (1,)
+ assert_equal(deta, [1.+3.j])
+
+ def test_1by1_stacked_input_output(self):
+ rng = np.random.default_rng(1680305949878959)
+ a = rng.random([4, 5, 1, 1], dtype=np.float32)
+ deta = det(a)
+ assert deta.dtype.char == 'd'
+ assert deta.shape == (4, 5)
+ assert_allclose(deta, np.squeeze(a))
+
+ a = rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
+ deta = det(a)
+ assert deta.dtype.char == 'D'
+ assert deta.shape == (4, 5)
+ assert_allclose(deta, np.squeeze(a))
+
+ @pytest.mark.parametrize('shape', [[2, 2], [20, 20], [3, 2, 20, 20]])
+ def test_simple_det_shapes_real_complex(self, shape):
+ rng = np.random.default_rng(1680305949878959)
+ a = rng.uniform(-1., 1., size=shape)
+ d1, d2 = det(a), np.linalg.det(a)
+ assert_allclose(d1, d2)
+
+ b = rng.uniform(-1., 1., size=shape)*1j
+ b += rng.uniform(-0.5, 0.5, size=shape)
+ d3, d4 = det(b), np.linalg.det(b)
+ assert_allclose(d3, d4)
+
+ def test_for_known_det_values(self):
+ # Hadamard8
+ a = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
+ [1, -1, 1, -1, 1, -1, 1, -1],
+ [1, 1, -1, -1, 1, 1, -1, -1],
+ [1, -1, -1, 1, 1, -1, -1, 1],
+ [1, 1, 1, 1, -1, -1, -1, -1],
+ [1, -1, 1, -1, -1, 1, -1, 1],
+ [1, 1, -1, -1, -1, -1, 1, 1],
+ [1, -1, -1, 1, -1, 1, 1, -1]])
+ assert_allclose(det(a), 4096.)
+
+ # consecutive number array always singular
+ assert_allclose(det(np.arange(25).reshape(5, 5)), 0.)
+
+ # simple anti-diagonal block array
+ # Upper right has det (-2+1j) and lower right has (-2-1j)
+ # det(a) = - (-2+1j) (-2-1j) = 5.
+ a = np.array([[0.+0.j, 0.+0.j, 0.-1.j, 1.-1.j],
+ [0.+0.j, 0.+0.j, 1.+0.j, 0.-1.j],
+ [0.+1.j, 1.+1.j, 0.+0.j, 0.+0.j],
+ [1.+0.j, 0.+1.j, 0.+0.j, 0.+0.j]], dtype=np.complex64)
+ assert_allclose(det(a), 5.+0.j)
+
+ # Fiedler companion complexified
+ # >>> a = scipy.linalg.fiedler_companion(np.arange(1, 10))
+ a = np.array([[-2., -3., 1., 0., 0., 0., 0., 0.],
+ [1., 0., 0., 0., 0., 0., 0., 0.],
+ [0., -4., 0., -5., 1., 0., 0., 0.],
+ [0., 1., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., -6., 0., -7., 1., 0.],
+ [0., 0., 0., 1., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., -8., 0., -9.],
+ [0., 0., 0., 0., 0., 1., 0., 0.]])*1.j
+ assert_allclose(det(a), 9.)
+
+ # g and G dtypes are handled differently in windows and other platforms
+ @pytest.mark.parametrize('typ', [x for x in np.typecodes['All'][:20]
+ if x not in 'gG'])
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_sample_compatible_dtype_input(self, typ):
+ rng = np.random.default_rng(1680305949878959)
+ n = 4
+ a = rng.random([n, n]).astype(typ) # value is not important
+ assert isinstance(det(a), (np.float64 | np.complex128))
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_incompatible_dtype_input(self):
+ # Double backslashes needed for escaping pytest regex.
+ msg = 'cannot be cast to float\\(32, 64\\)'
+
+ for c, t in zip('SUO', ['bytes8', 'str32', 'object']):
+ with assert_raises(TypeError, match=msg):
+ det(np.array([['a', 'b']]*2, dtype=c))
+ with assert_raises(TypeError, match=msg):
+ det(np.array([[b'a', b'b']]*2, dtype='V'))
+ with assert_raises(TypeError, match=msg):
+ det(np.array([[100, 200]]*2, dtype='datetime64[s]'))
+ with assert_raises(TypeError, match=msg):
+ det(np.array([[100, 200]]*2, dtype='timedelta64[s]'))
+
+ def test_empty_edge_cases(self):
+ assert_allclose(det(np.empty([0, 0])), 1.)
+ assert_allclose(det(np.empty([0, 0, 0])), np.array([]))
+ assert_allclose(det(np.empty([3, 0, 0])), np.array([1., 1., 1.]))
+ with assert_raises(ValueError, match='Last 2 dimensions'):
+ det(np.empty([0, 0, 3]))
+ with assert_raises(ValueError, match='at least two-dimensional'):
+ det(np.array([]))
+ with assert_raises(ValueError, match='Last 2 dimensions'):
+ det(np.array([[]]))
+ with assert_raises(ValueError, match='Last 2 dimensions'):
+ det(np.array([[[]]]))
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty_dtype(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ d = det(a)
+ assert d.shape == ()
+ assert d.dtype == det(np.eye(2, dtype=dt)).dtype
+
+ a = np.empty((3, 0, 0), dtype=dt)
+ d = det(a)
+ assert d.shape == (3,)
+ assert d.dtype == det(np.zeros((3, 1, 1), dtype=dt)).dtype
+
+ def test_overwrite_a(self):
+ # If all conditions are met then input should be overwritten;
+ # - dtype is one of 'fdFD'
+ # - C-contiguous
+ # - writeable
+ a = np.arange(9).reshape(3, 3).astype(np.float32)
+ ac = a.copy()
+ deta = det(ac, overwrite_a=True)
+ assert_allclose(deta, 0.)
+ assert not (a == ac).all()
+
+ def test_readonly_array(self):
+ a = np.array([[2., 0., 1.], [5., 3., -1.], [1., 1., 1.]])
+ a.setflags(write=False)
+ # overwrite_a will be overridden
+ assert_allclose(det(a, overwrite_a=True), 10.)
+
+ def test_simple_check_finite(self):
+ a = [[1, 2], [3, np.inf]]
+ with assert_raises(ValueError, match='array must not contain'):
+ det(a)
+
+
+def direct_lstsq(a, b, cmplx=0):
+ at = transpose(a)
+ if cmplx:
+ at = conjugate(at)
+ a1 = dot(at, a)
+ b1 = dot(at, b)
+ return solve(a1, b1)
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class TestLstsq:
+ lapack_drivers = ('gelsd', 'gelss', 'gelsy', None)
+
+ def test_simple_exact(self):
+ for dtype in REAL_DTYPES:
+ a = np.array([[1, 20], [-30, 4]], dtype=dtype)
+ for lapack_driver in TestLstsq.lapack_drivers:
+ for overwrite in (True, False):
+ for bt in (((1, 0), (0, 1)), (1, 0),
+ ((2, 1), (-30, 4))):
+ # Store values in case they are overwritten
+ # later
+ a1 = a.copy()
+ b = np.array(bt, dtype=dtype)
+ b1 = b.copy()
+ out = lstsq(a1, b1,
+ lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+ x = out[0]
+ r = out[2]
+ assert_(r == 2,
+ f'expected efficient rank 2, got {r}')
+ assert_allclose(dot(a, x), b,
+ atol=25 * _eps_cast(a1.dtype),
+ rtol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ def test_simple_overdet(self):
+ for dtype in REAL_DTYPES:
+ a = np.array([[1, 2], [4, 5], [3, 4]], dtype=dtype)
+ b = np.array([1, 2, 3], dtype=dtype)
+ for lapack_driver in TestLstsq.lapack_drivers:
+ for overwrite in (True, False):
+ # Store values in case they are overwritten later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+ x = out[0]
+ if lapack_driver == 'gelsy':
+ residuals = np.sum((b - a.dot(x))**2)
+ else:
+ residuals = out[1]
+ r = out[2]
+ assert_(r == 2, f'expected efficient rank 2, got {r}')
+ assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
+ residuals,
+ rtol=25 * _eps_cast(a1.dtype),
+ atol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+ assert_allclose(x, (-0.428571428571429, 0.85714285714285),
+ rtol=25 * _eps_cast(a1.dtype),
+ atol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ def test_simple_overdet_complex(self):
+ for dtype in COMPLEX_DTYPES:
+ a = np.array([[1+2j, 2], [4, 5], [3, 4]], dtype=dtype)
+ b = np.array([1, 2+4j, 3], dtype=dtype)
+ for lapack_driver in TestLstsq.lapack_drivers:
+ for overwrite in (True, False):
+ # Store values in case they are overwritten later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+
+ x = out[0]
+ if lapack_driver == 'gelsy':
+ res = b - a.dot(x)
+ residuals = np.sum(res * res.conj())
+ else:
+ residuals = out[1]
+ r = out[2]
+ assert_(r == 2, f'expected efficient rank 2, got {r}')
+ assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
+ residuals,
+ rtol=25 * _eps_cast(a1.dtype),
+ atol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+ assert_allclose(
+ x, (-0.4831460674157303 + 0.258426966292135j,
+ 0.921348314606741 + 0.292134831460674j),
+ rtol=25 * _eps_cast(a1.dtype),
+ atol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ def test_simple_underdet(self):
+ for dtype in REAL_DTYPES:
+ a = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype)
+ b = np.array([1, 2], dtype=dtype)
+ for lapack_driver in TestLstsq.lapack_drivers:
+ for overwrite in (True, False):
+ # Store values in case they are overwritten later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+
+ x = out[0]
+ r = out[2]
+ assert_(r == 2, f'expected efficient rank 2, got {r}')
+ assert_allclose(x, (-0.055555555555555, 0.111111111111111,
+ 0.277777777777777),
+ rtol=25 * _eps_cast(a1.dtype),
+ atol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ # as documented, residuals is empty for an underdetermined problem
+ residuals = out[1]
+ assert residuals.size == 0
+
+ @pytest.mark.parametrize("dtype", REAL_DTYPES)
+ @pytest.mark.parametrize("n", (20, 200))
+ @pytest.mark.parametrize("lapack_driver", lapack_drivers)
+ @pytest.mark.parametrize("overwrite", (True, False))
+ def test_random_exact(self, dtype, n, lapack_driver, overwrite):
+ rng = np.random.RandomState(1234)
+
+ a = np.asarray(rng.random([n, n]), dtype=dtype)
+ for i in range(n):
+ a[i, i] = 20 * (0.1 + a[i, i])
+ for i in range(4):
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
+ # Store values in case they are overwritten later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1,
+ lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+ x = out[0]
+ r = out[2]
+ assert_(r == n, f'expected efficient rank {n}, '
+ f'got {r}')
+ if dtype is np.float32:
+ assert_allclose(
+ dot(a, x), b,
+ rtol=500 * _eps_cast(a1.dtype),
+ atol=500 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+ else:
+ assert_allclose(
+ dot(a, x), b,
+ rtol=1000 * _eps_cast(a1.dtype),
+ atol=1000 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ @pytest.mark.skipif(IS_MUSL, reason="may segfault on Alpine, see gh-17630")
+ @pytest.mark.parametrize("dtype", COMPLEX_DTYPES)
+ @pytest.mark.parametrize("n", (20, 200))
+ @pytest.mark.parametrize("lapack_driver", lapack_drivers)
+ @pytest.mark.parametrize("overwrite", (True, False))
+ def test_random_complex_exact(self, dtype, n, lapack_driver, overwrite):
+ rng = np.random.RandomState(1234)
+
+ a = np.asarray(rng.random([n, n]) + 1j*rng.random([n, n]),
+ dtype=dtype)
+ for i in range(n):
+ a[i, i] = 20 * (0.1 + a[i, i])
+ for i in range(2):
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
+ # Store values in case they are overwritten later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+ x = out[0]
+ r = out[2]
+ assert_(r == n, f'expected efficient rank {n}, '
+ f'got {r}')
+ if dtype is np.complex64:
+ assert_allclose(
+ dot(a, x), b,
+ rtol=400 * _eps_cast(a1.dtype),
+ atol=400 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+ else:
+ assert_allclose(
+ dot(a, x), b,
+ rtol=1000 * _eps_cast(a1.dtype),
+ atol=1000 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ def test_random_overdet(self):
+ rng = np.random.RandomState(1234)
+ for dtype in REAL_DTYPES:
+ for (n, m) in ((20, 15), (200, 2)):
+ for lapack_driver in TestLstsq.lapack_drivers:
+ for overwrite in (True, False):
+ a = np.asarray(rng.random([n, m]), dtype=dtype)
+ for i in range(m):
+ a[i, i] = 20 * (0.1 + a[i, i])
+ for i in range(4):
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
+ # Store values in case they are overwritten later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1,
+ lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+ x = out[0]
+ r = out[2]
+ assert_(r == m, f'expected efficient rank {m}, '
+ f'got {r}')
+ assert_allclose(
+ x, direct_lstsq(a, b, cmplx=0),
+ rtol=25 * _eps_cast(a1.dtype),
+ atol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ def test_random_complex_overdet(self):
+ rng = np.random.RandomState(1234)
+ for dtype in COMPLEX_DTYPES:
+ for (n, m) in ((20, 15), (200, 2)):
+ for lapack_driver in TestLstsq.lapack_drivers:
+ for overwrite in (True, False):
+ a = np.asarray(rng.random([n, m]) + 1j*rng.random([n, m]),
+ dtype=dtype)
+ for i in range(m):
+ a[i, i] = 20 * (0.1 + a[i, i])
+ for i in range(2):
+ b = np.asarray(rng.random([n, 3]), dtype=dtype)
+ # Store values in case they are overwritten
+ # later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1,
+ lapack_driver=lapack_driver,
+ overwrite_a=overwrite,
+ overwrite_b=overwrite)
+ x = out[0]
+ r = out[2]
+ assert_(r == m, f'expected efficient rank {m}, '
+ f'got {r}')
+ assert_allclose(
+ x, direct_lstsq(a, b, cmplx=1),
+ rtol=25 * _eps_cast(a1.dtype),
+ atol=25 * _eps_cast(a1.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ def test_check_finite(self):
+ with warnings.catch_warnings():
+ # On (some) OSX this tests triggers a warning (gh-7538)
+ warnings.filterwarnings("ignore",
+ "internal gelsd driver lwork query error,.*"
+ "Falling back to 'gelss' driver.", RuntimeWarning)
+
+ at = np.array(((1, 20), (-30, 4)))
+ for dtype, bt, lapack_driver, overwrite, check_finite in \
+ itertools.product(REAL_DTYPES,
+ (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))),
+ TestLstsq.lapack_drivers,
+ (True, False),
+ (True, False)):
+
+ a = at.astype(dtype)
+ b = np.array(bt, dtype=dtype)
+ # Store values in case they are overwritten
+ # later
+ a1 = a.copy()
+ b1 = b.copy()
+ out = lstsq(a1, b1, lapack_driver=lapack_driver,
+ check_finite=check_finite, overwrite_a=overwrite,
+ overwrite_b=overwrite)
+ x = out[0]
+ r = out[2]
+ assert_(r == 2, f'expected efficient rank 2, got {r}')
+ assert_allclose(dot(a, x), b,
+ rtol=25 * _eps_cast(a.dtype),
+ atol=25 * _eps_cast(a.dtype),
+ err_msg=f"driver: {lapack_driver}")
+
+ def test_empty(self):
+ for a_shape, b_shape in (((0, 2), (0,)),
+ ((0, 4), (0, 2)),
+ ((4, 0), (4,)),
+ ((4, 0), (4, 2))):
+ b = np.ones(b_shape)
+ x, residues, rank, s = lstsq(np.zeros(a_shape), b)
+ assert_equal(x, np.zeros((a_shape[1],) + b_shape[1:]))
+ residues_should_be = (np.empty((0,)) if a_shape[1]
+ else np.linalg.norm(b, axis=0)**2)
+ assert_equal(residues, residues_should_be)
+ assert_(rank == 0, 'expected rank 0')
+ assert_equal(s, np.empty((0,)))
+
+ @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty_dtype(self, dt_a, dt_b):
+ a = np.empty((0, 0), dtype=dt_a)
+ b = np.empty(0, dtype=dt_b)
+ x, residues, rank, s = lstsq(a, b)
+
+ assert x.size == 0
+ dt_nonempty = lstsq(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b))[0].dtype
+ assert x.dtype == dt_nonempty
+
+
+ @pytest.mark.parametrize('driver', ['gelss', 'gelsy', 'gelsd'])
+ def test_m_less_than_n(self, driver):
+ # if m < n, LAPACK needs a copy of b:
+ # B is (LDB, NRHS)-shaped, with LDB = max(1, M, N)
+ # https://www.netlib.org/lapack/explore-html/d6/d4b/dgelsy_8f.html
+ a = np.arange(3*4).reshape(3, 4) + 1
+ aa = np.stack((a, 2*a))
+ bb = np.stack((np.arange(3) + 1, 1 + 4*np.arange(3))).T
+
+ x, residues, rank, s = lstsq(aa, bb, lapack_driver=driver)
+ assert_allclose(x,
+ np.asarray([[[-0.05 , 0.7 ],
+ [ 0.025 , 0.4 ],
+ [ 0.1 , 0.1 ],
+ [ 0.175 , -0.2 ]],
+
+ [[-0.025 , 0.35 ],
+ [ 0.0125, 0.2 ],
+ [ 0.05 , 0.05 ],
+ [ 0.0875, -0.1 ]]]), atol=1e-15
+ )
+
+ @pytest.mark.parametrize('driver', ['gelss', 'gelsy', 'gelsd'])
+ def test_m_larger_than_n(self, driver):
+ # similar to test_m_less_than_n: test copying with LDB=max(1, M, N)
+ a = np.arange(3*4).reshape(4, 3) + 1
+ aa = np.stack((a, 2*a))
+ bb = np.stack((np.arange(4) + 1, 1 + 4*np.arange(4))).T
+
+ x, residues, rank, s = lstsq(aa, bb, lapack_driver=driver)
+ assert_allclose(x,
+ np.asarray([[[-0.05555556, 1.27777778],
+ [ 0.11111111, 0.44444444],
+ [ 0.27777778, -0.38888889]],
+
+ [[-0.02777778, 0.63888889],
+ [ 0.05555556, 0.22222222],
+ [ 0.13888889, -0.19444444]]]), atol=1e-15
+ )
+
+ @pytest.mark.parametrize('driver', ['gelss', 'gelsy', 'gelsd'])
+ def test_residuals(self, driver):
+ # assert the (quirky) behavior of the `residuals` return
+ a = np.array([[1, 2], [4, 5], [3, 4]], dtype=float)
+ b = np.array([1, 2, 3], dtype=float)
+
+ m, n = a.shape
+ assert m > n # backcompat: residuals are non-empty iff m > n and rank == n
+
+ # 1. b.shape == (n,)
+ x, resid, rank, s = lstsq(a, b, lapack_driver=driver)
+
+ assert rank == n
+
+ if driver != "gelsy":
+ assert resid.ndim == 0 # it's numpy scalar, in fact
+
+ delta = b - a @ x
+ manual_residuals = np.sum(delta * delta.conj(), axis=0)
+ assert math.isclose(resid, manual_residuals, abs_tol=1e-14)
+ else:
+ assert resid.ndim == 1 and resid.size == 0
+
+ # 2. b.shape == (n, nrhs)
+ b2 = np.stack((b, 2*b, 3*b, 4*b), axis=1) # b1.shape=(3, 4), nrhs=4
+ nrhs = b2.shape[-1]
+ x2, resid2, rank2, s2 = lstsq(a, b2, lapack_driver=driver)
+
+ assert rank2 == n
+
+ if driver != "gelsy":
+ assert resid2.shape == (nrhs,)
+ delta2 = b2 - a @ x2
+ manual_residuals2 = np.sum( delta2 * delta2.conj(), axis=0 )
+ assert_allclose(resid2, manual_residuals2, atol=1e-14)
+ else:
+ assert resid.ndim == 1 and resid.size == 0
+
+ # 3. b.shape == (n,), and a has batch shape (2,)
+ a3 = np.stack((a, 2*a))
+ b3 = b.copy()
+ batch_shape = a3.shape[:-2]
+
+ x3, resid3, ranks3, s3 = lstsq(a3, b3, lapack_driver=driver)
+ assert_equal(ranks3, np.asarray([n, n]))
+
+ if driver != "gelsy":
+ assert resid3.shape == (n,)
+ assert_allclose(resid3, [resid]*n, atol=1e-14)
+ else:
+ assert resid3.shape == (2, 0)
+
+ # 4. b.shape == (n, nhrs) and a has batch shape = (2,)
+ a4 = np.stack((a, 2*a))
+ batch_shape = a4.shape[:-2]
+ b4 = b2.copy()
+ x4, resid4, rank4, s4 = lstsq(a4, b4, lapack_driver=driver)
+
+ assert_equal(rank4, np.asarray([n, n]))
+
+ if driver != "gelsy":
+ assert resid4.shape == (2, nrhs) # batch_shape + (nrhs,)
+ delta4 = b4 - a4 @ x4
+ manual_residual4 = np.sum( delta4 * delta4.conj(), axis=len(batch_shape) )
+ assert_allclose(resid4, manual_residual4, atol=1e-14)
+ else:
+ assert resid4.shape == (2, 0)
+
+ @pytest.mark.parametrize("driver", ["gelsd", "gelss", "gelsy"])
+ @pytest.mark.parametrize("shape_a", [(3, 2), (4, 3, 2)])
+ @pytest.mark.parametrize("shape_b", [(3,), (3, 1), (3, 5)])
+ def test_rank_deficient_residuals(self, driver, shape_a, shape_b):
+ rng = np.random.default_rng(seed=42)
+
+ # Insert one rank-deficient slice to check if `NaN` is returned
+ if len(shape_a) == 2:
+ a = np.zeros(shape_a)
+ else:
+ a = np.zeros(shape_a)
+ a[1:, :, 0] = 1
+ a[1:, :, 1:] = rng.normal(size=(shape_a[0]-1, shape_a[1], shape_a[-1]-1))
+
+ b = rng.normal(size=shape_b)
+
+ x, res, rank, _ = lstsq(a, b, lapack_driver=driver)
+
+ # Validate that the residuals are correct for full-rank slices and that `NaN` is
+ # inserted otherwise.
+ if driver != "gelsy":
+ if b.ndim == 1:
+ b = b[:, None]
+ x = x[..., None]
+ res = res[..., None]
+ res_ref = a @ x - b
+ res_ref = np.sum(res_ref * res_ref.conj(), axis=-2)
+
+ mask = rank == shape_a[-1]
+ assert_allclose(res[mask], res_ref[mask])
+ assert np.all(np.isnan(res[~mask]))
+ else:
+ assert res.shape == (a.shape[:-2] + (0,))
+
+
+ def test_errors(self):
+ a = np.ones((3, 4))
+ b = np.ones(4)
+
+ with pytest.raises(ValueError, match="LAPACK driver"):
+ lstsq(a, b, lapack_driver='krampus')
+
+ with pytest.raises(ValueError, match="Shape mismatch"):
+ lstsq(a, b)
+
+ with pytest.raises(ValueError, match="Input array"):
+ lstsq(np.ones(3), np.ones(3))
+
+ @parametrize_overwrite_arg
+ @parametrize_overwrite_b_arg
+ @pytest.mark.parametrize("driver", ["gelss", "gelsd", "gelsy"])
+ @pytest.mark.parametrize("dtype", [int, float])
+ @pytest.mark.parametrize("shape", [(2, 4, 3), (4, 3), (3, 4)])
+ @pytest.mark.parametrize("nrhs", [1, 5])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ def test_overwrite(
+ self, overwrite_kw, overwrite_b_kw, driver, dtype, shape, nrhs, order
+ ):
+ rng = np.random.default_rng(seed=123456)
+ if dtype is not int:
+ a = np.asarray(rng.normal(size=shape), order=order)
+ b = np.asarray(rng.normal(size=(*shape[:-1], nrhs)), order=order)
+ else: # avoid issues with singularity
+ a = np.asarray(rng.integers(1000, size=shape), order=order)
+ b = np.asarray(rng.integers(1000, size=(*shape[:-1], nrhs)), order=order)
+
+ a_ref = np.copy(a)
+ b_ref = np.copy(b)
+
+ x, res, rank, S = lstsq(
+ a, b, **overwrite_kw, **overwrite_b_kw, lapack_driver=driver
+ )
+
+ # validate solution and residuals
+ a_T = a_ref.swapaxes(-2, -1)
+ if shape[-2] >= shape[-1]:
+ x_ref = solve(a_T @ a_ref, a_T @ b_ref)
+ else:
+ x_ref = a_T @ solve(a_ref @ a_T, b_ref)
+
+ assert_allclose(x_ref, x, atol=1e-12)
+
+ if driver != "gelsy" and shape[-2] >= shape[-1]:
+ res_ref = a_ref @ x - b_ref
+ res_ref = np.sum(res_ref * res_ref.conj(), axis=-2)
+ assert_allclose(res_ref, res, atol=1e-12)
+ else:
+ assert_allclose(np.zeros(shape[:-2] + (0,), x.dtype), res)
+
+ overwrite_a = overwrite_kw.get("overwrite_a", False)
+ overwrite_a = (
+ overwrite_a and
+ (dtype is not int) and
+ a.flags["F_CONTIGUOUS"] and
+ a.ndim <= 2
+ )
+
+ # Classical conditions: F_contiguity + should not be overwritten internally.
+ # Complemented by the fact that LAPACK requires a `b` of at least `max(m, n)`,
+ # hence if this is not the case `b` can not be used directly.
+ overwrite_b = overwrite_b_kw.get("overwrite_b", False)
+ overwrite_b = (
+ overwrite_b and
+ (dtype is not int) and
+ b.flags["F_CONTIGUOUS"] and
+ shape[0] >= shape[1]
+ )
+
+ assert np.all(a_ref == a) != overwrite_a
+ assert np.all(b_ref == b) != overwrite_b
+ assert np.shares_memory(x, b) == overwrite_b
+
+
+class TestPinv:
+ def test_simple_real(self):
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+ a_pinv = pinv(a)
+ assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+ def test_simple_complex(self):
+ a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
+ dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
+ dtype=float))
+ a_pinv = pinv(a)
+ assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+ def test_simple_singular(self):
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
+ a_pinv = pinv(a)
+ expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
+ [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
+ [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
+ assert_array_almost_equal(a_pinv, expected)
+
+ def test_simple_cols(self):
+ a = array([[1, 2, 3], [4, 5, 6]], dtype=float)
+ a_pinv = pinv(a)
+ expected = array([[-0.94444444, 0.44444444],
+ [-0.11111111, 0.11111111],
+ [0.72222222, -0.22222222]])
+ assert_array_almost_equal(a_pinv, expected)
+
+ def test_simple_rows(self):
+ a = array([[1, 2], [3, 4], [5, 6]], dtype=float)
+ a_pinv = pinv(a)
+ expected = array([[-1.33333333, -0.33333333, 0.66666667],
+ [1.08333333, 0.33333333, -0.41666667]])
+ assert_array_almost_equal(a_pinv, expected)
+
+ def test_check_finite(self):
+ a = array([[1, 2, 3], [4, 5, 6.], [7, 8, 10]])
+ a_pinv = pinv(a, check_finite=False)
+ assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+ def test_native_list_argument(self):
+ a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+ a_pinv = pinv(a)
+ expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
+ [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
+ [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
+ assert_array_almost_equal(a_pinv, expected)
+
+ def test_atol_rtol(self):
+ rng = np.random.default_rng(1234)
+ n = 12
+ # get a random ortho matrix for shuffling
+ q, _ = qr(rng.random((n, n)))
+ a_m = np.arange(35.0).reshape(7, 5)
+ a = a_m.copy()
+ a[0, 0] = 0.001
+ atol = 1e-5
+ rtol = 0.05
+ # svds of a_m is ~ [116.906, 4.234, tiny, tiny, tiny]
+ # svds of a is ~ [116.906, 4.234, 4.62959e-04, tiny, tiny]
+ # Just abs cutoff such that we arrive at a_modified
+ a_p = pinv(a_m, atol=atol, rtol=0.)
+ adiff1 = a @ a_p @ a - a
+ adiff2 = a_m @ a_p @ a_m - a_m
+ # Now adiff1 should be around atol value while adiff2 should be
+ # relatively tiny
+ assert_allclose(np.linalg.norm(adiff1), 5e-4, atol=5.e-4)
+ assert_allclose(np.linalg.norm(adiff2), 5e-14, atol=7.e-14)
+
+ # Now do the same but remove another sv ~4.234 via rtol
+ a_p = pinv(a_m, atol=atol, rtol=rtol)
+ adiff1 = a @ a_p @ a - a
+ adiff2 = a_m @ a_p @ a_m - a_m
+ assert_allclose(np.linalg.norm(adiff1), 4.233, rtol=0.01)
+ assert_allclose(np.linalg.norm(adiff2), 4.233, rtol=0.01)
+
+ @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ a_pinv = pinv(a)
+ assert a_pinv.size == 0
+ assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
+
+
+class TestPinvSymmetric:
+ def test_simple_real(self):
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+ a = np.dot(a, a.T)
+ a_pinv = pinvh(a)
+ assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+ def test_nonpositive(self):
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
+ a = np.dot(a, a.T)
+ u, s, vt = np.linalg.svd(a)
+ s[0] *= -1
+ a = np.dot(u * s, vt) # a is now symmetric non-positive and singular
+ a_pinv = pinv(a)
+ a_pinvh = pinvh(a)
+ assert_array_almost_equal(a_pinv, a_pinvh)
+
+ def test_simple_complex(self):
+ a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
+ dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
+ dtype=float))
+ a = np.dot(a, a.conj().T)
+ a_pinv = pinvh(a)
+ assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+ def test_native_list_argument(self):
+ a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+ a = np.dot(a, a.T)
+ a_pinv = pinvh(a.tolist())
+ assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+ def test_zero_eigenvalue(self):
+ # https://github.com/scipy/scipy/issues/12515
+ # the SYEVR eigh driver may give the zero eigenvalue > eps
+ a = np.array([[1, -1, 0], [-1, 2, -1], [0, -1, 1]])
+ p = pinvh(a)
+ assert_allclose(p @ a @ p, p, atol=1e-15)
+ assert_allclose(a @ p @ a, a, atol=1e-15)
+
+ def test_atol_rtol(self):
+ rng = np.random.default_rng(1234)
+ n = 12
+ # get a random ortho matrix for shuffling
+ q, _ = qr(rng.random((n, n)))
+ a = np.diag([4, 3, 2, 1, 0.99e-4, 0.99e-5] + [0.99e-6]*(n-6))
+ a = q.T @ a @ q
+ a_m = np.diag([4, 3, 2, 1, 0.99e-4, 0.] + [0.]*(n-6))
+ a_m = q.T @ a_m @ q
+ atol = 1e-5
+ rtol = (4.01e-4 - 4e-5)/4
+ # Just abs cutoff such that we arrive at a_modified
+ a_p = pinvh(a, atol=atol, rtol=0.)
+ adiff1 = a @ a_p @ a - a
+ adiff2 = a_m @ a_p @ a_m - a_m
+ # Now adiff1 should dance around atol value since truncation
+ # while adiff2 should be relatively tiny
+ assert_allclose(norm(adiff1), atol, rtol=0.1)
+ assert_allclose(norm(adiff2), 1e-12, atol=1e-11)
+
+ # Now do the same but through rtol cancelling atol value
+ a_p = pinvh(a, atol=atol, rtol=rtol)
+ adiff1 = a @ a_p @ a - a
+ adiff2 = a_m @ a_p @ a_m - a_m
+ # adiff1 and adiff2 should be elevated to ~1e-4 due to mismatch
+ assert_allclose(norm(adiff1), 1e-4, rtol=0.1)
+ assert_allclose(norm(adiff2), 1e-4, rtol=0.1)
+
+ @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ a_pinv = pinvh(a)
+ assert a_pinv.size == 0
+ assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
+
+
+@pytest.mark.parametrize('scale', (1e-20, 1., 1e20))
+@pytest.mark.parametrize('pinv_', (pinv, pinvh))
+def test_auto_rcond(scale, pinv_):
+ x = np.array([[1, 0], [0, 1e-10]]) * scale
+ expected = np.diag(1. / np.diag(x))
+ x_inv = pinv_(x)
+ assert_allclose(x_inv, expected)
+
+
+class TestVectorNorms:
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_types(self):
+ for dtype in np.typecodes['AllFloat']:
+ x = np.array([1, 2, 3], dtype=dtype)
+ tol = max(1e-15, np.finfo(dtype).eps.real * 20)
+ assert_allclose(norm(x), np.sqrt(14), rtol=tol)
+ assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
+
+ for dtype in np.typecodes['Complex']:
+ x = np.array([1j, 2j, 3j], dtype=dtype)
+ tol = max(1e-15, np.finfo(dtype).eps.real * 20)
+ assert_allclose(norm(x), np.sqrt(14), rtol=tol)
+ assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
+
+ def test_overflow(self):
+ # unlike numpy's norm, this one is
+ # safer on overflow
+ a = array([1e20], dtype=float32)
+ assert_almost_equal(norm(a), a)
+
+ def test_stable(self):
+ # more stable than numpy's norm
+ a = array([1e4] + [1]*10000, dtype=float32)
+ try:
+ # snrm in double precision; we obtain the same as for float64
+ # -- large atol needed due to varying blas implementations
+ assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2)
+ except AssertionError:
+ # snrm implemented in single precision, == np.linalg.norm result
+ msg = ": Result should equal either 0.0 or 0.5 (depending on " \
+ "implementation of snrm2)."
+ assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg)
+
+ def test_zero_norm(self):
+ assert_equal(norm([1, 0, 3], 0), 2)
+ assert_equal(norm([1, 2, 3], 0), 3)
+
+ def test_axis_kwd(self):
+ a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+ assert_allclose(norm(a, axis=1), [[3.60555128, 4.12310563]] * 2)
+ assert_allclose(norm(a, 1, axis=1), [[5.] * 2] * 2)
+
+ def test_keepdims_kwd(self):
+ a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+ b = norm(a, axis=1, keepdims=True)
+ assert_allclose(b, [[[3.60555128, 4.12310563]]] * 2)
+ assert_(b.shape == (2, 1, 2))
+ assert_allclose(norm(a, 1, axis=2, keepdims=True), [[[3.], [7.]]] * 2)
+
+ @pytest.mark.skipif(not HAS_ILP64, reason="64-bit BLAS required")
+ def test_large_vector(self):
+ check_free_memory(free_mb=17000)
+ x = np.zeros([2**31], dtype=np.float64)
+ x[-1] = 1
+ res = norm(x)
+ del x
+ assert_allclose(res, 1.0)
+
+
+class TestMatrixNorms:
+
+ def test_matrix_norms(self):
+ # Not all of these are matrix norms in the most technical sense.
+ rng = np.random.default_rng(1234)
+ for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4):
+ for t in np.float32, np.float64, np.complex64, np.complex128, np.int64:
+ A = 10 * rng.standard_normal((n, m)).astype(t)
+ if np.issubdtype(A.dtype, np.complexfloating):
+ A += 10j * rng.standard_normal((n, m))
+ t_high = np.complex128
+ else:
+ t_high = np.float64
+ for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf):
+ actual = norm(A, ord=order)
+ desired = np.linalg.norm(A, ord=order)
+ # SciPy may return higher precision matrix norms.
+ # This is a consequence of using LAPACK.
+ if not np.allclose(actual, desired):
+ desired = np.linalg.norm(A.astype(t_high), ord=order)
+ assert_allclose(actual, desired)
+
+ def test_axis_kwd(self):
+ a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+ b = norm(a, ord=np.inf, axis=(1, 0))
+ c = norm(np.swapaxes(a, 0, 1), ord=np.inf, axis=(0, 1))
+ d = norm(a, ord=1, axis=(0, 1))
+ assert_allclose(b, c)
+ assert_allclose(c, d)
+ assert_allclose(b, d)
+ assert_(b.shape == c.shape == d.shape)
+ b = norm(a, ord=1, axis=(1, 0))
+ c = norm(np.swapaxes(a, 0, 1), ord=1, axis=(0, 1))
+ d = norm(a, ord=np.inf, axis=(0, 1))
+ assert_allclose(b, c)
+ assert_allclose(c, d)
+ assert_allclose(b, d)
+ assert_(b.shape == c.shape == d.shape)
+
+ def test_keepdims_kwd(self):
+ a = np.arange(120, dtype='d').reshape(2, 3, 4, 5)
+ b = norm(a, ord=np.inf, axis=(1, 0), keepdims=True)
+ c = norm(a, ord=1, axis=(0, 1), keepdims=True)
+ assert_allclose(b, c)
+ assert_(b.shape == c.shape)
+
+ def test_empty(self):
+ a = np.empty((0, 0))
+ assert_allclose(norm(a), 0.)
+ assert_allclose(norm(a, axis=0), np.zeros((0,)))
+ assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
+
+ a = np.empty((0, 3))
+ assert_allclose(norm(a), 0.)
+ assert_allclose(norm(a, axis=0), np.zeros((3,)))
+ assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
+
+
+class TestOverwrite:
+ def test_solve(self):
+ assert_no_overwrite(solve, [(3, 3), (3,)])
+
+ def test_solve_triangular(self):
+ assert_no_overwrite(solve_triangular, [(3, 3), (3,)])
+
+ def test_solve_banded(self):
+ assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b),
+ [(4, 6), (6,)])
+
+ def test_solveh_banded(self):
+ assert_no_overwrite(solveh_banded, [(2, 6), (6,)])
+
+ def test_inv(self):
+ assert_no_overwrite(inv, [(3, 3)])
+
+ def test_det(self):
+ assert_no_overwrite(det, [(3, 3)])
+
+ def test_lstsq(self):
+ assert_no_overwrite(lstsq, [(3, 2), (3,)])
+
+ def test_pinv(self):
+ assert_no_overwrite(pinv, [(3, 3)])
+
+ def test_pinvh(self):
+ assert_no_overwrite(pinvh, [(3, 3)])
+
+
+class TestSolveCirculant:
+
+ def test_basic1(self):
+ c = np.array([1, 2, 3, 5])
+ b = np.array([1, -1, 1, 0])
+ x = solve_circulant(c, b)
+ y = solve(circulant(c), b)
+ assert_allclose(x, y)
+
+ def test_basic2(self):
+ # b is a 2-d matrix.
+ c = np.array([1, 2, -3, -5])
+ b = np.arange(12).reshape(4, 3)
+ x = solve_circulant(c, b)
+ y = solve(circulant(c), b)
+ assert_allclose(x, y)
+
+ def test_basic3(self):
+ # b is a 3-d matrix.
+ c = np.array([1, 2, -3, -5])
+ b = np.arange(24).reshape(4, 3, 2)
+ x = solve_circulant(c, b)
+ y = solve(circulant(c), b.reshape(4, -1)).reshape(b.shape)
+ assert_allclose(x, y)
+
+ def test_complex(self):
+ # Complex b and c
+ c = np.array([1+2j, -3, 4j, 5])
+ b = np.arange(8).reshape(4, 2) + 0.5j
+ x = solve_circulant(c, b)
+ y = solve(circulant(c), b)
+ assert_allclose(x, y)
+
+ def test_random_b_and_c(self):
+ # Random b and c
+ rng = np.random.RandomState(54321)
+ c = rng.standard_normal(50)
+ b = rng.standard_normal(50)
+ x = solve_circulant(c, b)
+ y = solve(circulant(c), b)
+ assert_allclose(x, y)
+
+ def test_singular(self):
+ # c gives a singular circulant matrix.
+ c = np.array([1, 1, 0, 0])
+ b = np.array([1, 2, 3, 4])
+ x = solve_circulant(c, b, singular='lstsq')
+ y, res, rnk, s = lstsq(circulant(c), b)
+ assert_allclose(x, y)
+ assert_raises(LinAlgError, solve_circulant, x, y)
+
+ def test_axis_args(self):
+ # Test use of caxis, baxis and outaxis.
+
+ # c has shape (2, 1, 4)
+ c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]])
+
+ # b has shape (3, 4)
+ b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]])
+
+ x = solve_circulant(c, b, baxis=1)
+ assert_equal(x.shape, (4, 2, 3))
+ expected = np.empty_like(x)
+ expected[:, 0, :] = solve(circulant(c[0].ravel()), b.T)
+ expected[:, 1, :] = solve(circulant(c[1].ravel()), b.T)
+ assert_allclose(x, expected)
+
+ x = solve_circulant(c, b, baxis=1, outaxis=-1)
+ assert_equal(x.shape, (2, 3, 4))
+ assert_allclose(np.moveaxis(x, -1, 0), expected)
+
+ # np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3).
+ x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1)
+ assert_equal(x.shape, (4, 2, 3))
+ assert_allclose(x, expected)
+
+ def test_native_list_arguments(self):
+ # Same as test_basic1 using python's native list.
+ c = [1, 2, 3, 5]
+ b = [1, -1, 1, 0]
+ x = solve_circulant(c, b)
+ y = solve(circulant(c), b)
+ assert_allclose(x, y)
+
+ @pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt_c, dt_b):
+ c = np.array([], dtype=dt_c)
+ b = np.array([], dtype=dt_b)
+ x = solve_circulant(c, b)
+ assert x.shape == (0,)
+ assert x.dtype == solve_circulant(np.arange(3, dtype=dt_c),
+ np.ones(3, dtype=dt_b)).dtype
+
+ b = np.empty((0, 0), dtype=dt_b)
+ x1 = solve_circulant(c, b)
+ assert x1.shape == (0, 0)
+ assert x1.dtype == x.dtype
+
+
+class TestMatrix_Balance:
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ @skip_xp_invalid_arg
+ def test_string_arg(self):
+ assert_raises(ValueError, matrix_balance, 'Some string for fail')
+
+ def test_infnan_arg(self):
+ assert_raises(ValueError, matrix_balance,
+ np.array([[1, 2], [3, np.inf]]))
+ assert_raises(ValueError, matrix_balance,
+ np.array([[1, 2], [3, np.nan]]))
+
+ def test_scaling(self):
+ _, y = matrix_balance(np.array([[1000, 1], [1000, 0]]))
+ # Pre/post LAPACK 3.5.0 gives the same result up to an offset
+ # since in each case col norm is x1000 greater and
+ # 1000 / 32 ~= 1 * 32 hence balanced with 2 ** 5.
+ assert_allclose(np.diff(np.log2(np.diag(y))), [5])
+
+ def test_scaling_order(self):
+ A = np.array([[1, 0, 1e-4], [1, 1, 1e-2], [1e4, 1e2, 1]])
+ x, y = matrix_balance(A)
+ assert_allclose(solve(y, A).dot(y), x)
+
+ def test_separate(self):
+ _, (y, z) = matrix_balance(np.array([[1000, 1], [1000, 0]]),
+ separate=1)
+ assert_equal(np.diff(np.log2(y)), [5])
+ assert_allclose(z, np.arange(2))
+
+ def test_permutation(self):
+ A = block_diag(np.ones((2, 2)), np.tril(np.ones((2, 2))),
+ np.ones((3, 3)))
+ x, (y, z) = matrix_balance(A, separate=1)
+ assert_allclose(y, np.ones_like(y))
+ assert_allclose(z, np.array([0, 1, 6, 5, 4, 3, 2]))
+
+ def test_perm_and_scaling(self):
+ # Matrix with its diagonal removed
+ cases = ( # Case 0
+ np.array([[0., 0., 0., 0., 0.000002],
+ [0., 0., 0., 0., 0.],
+ [2., 2., 0., 0., 0.],
+ [2., 2., 0., 0., 0.],
+ [0., 0., 0.000002, 0., 0.]]),
+ # Case 1 user reported GH-7258
+ np.array([[-0.5, 0., 0., 0.],
+ [0., -1., 0., 0.],
+ [1., 0., -0.5, 0.],
+ [0., 1., 0., -1.]]),
+ # Case 2 user reported GH-7258
+ np.array([[-3., 0., 1., 0.],
+ [-1., -1., -0., 1.],
+ [-3., -0., -0., 0.],
+ [-1., -0., 1., -1.]])
+ )
+
+ for A in cases:
+ x, y = matrix_balance(A)
+ x, (s, p) = matrix_balance(A, separate=1)
+ ip = np.empty_like(p)
+ ip[p] = np.arange(A.shape[0])
+ assert_allclose(y, np.diag(s)[ip, :])
+ assert_allclose(solve(y, A).dot(y), x)
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ b, t = matrix_balance(a)
+
+ assert b.size == 0
+ assert t.size == 0
+
+ b_n, t_n = matrix_balance(np.eye(2, dtype=dt))
+ assert b.dtype == b_n.dtype
+ assert t.dtype == t_n.dtype
+
+ b, (scale, perm) = matrix_balance(a, separate=True)
+ assert b.size == 0
+ assert scale.size == 0
+ assert perm.size == 0
+
+ b_n, (scale_n, perm_n) = matrix_balance(a, separate=True)
+ assert b.dtype == b_n.dtype
+ assert scale.dtype == scale_n.dtype
+ assert perm.dtype == perm_n.dtype
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class TestDTypes:
+ """Check backwards compatibility for dtypes vs scipy 1.16."""
+
+ def get_arr2D(self, tcode):
+ # return a valid 2D array for the typecode
+ if tcode == 'M':
+ return np.eye(2, dtype='datetime64[ms]')
+ elif tcode == 'm':
+ return np.eye(2, dtype='timedelta64[ms]')
+ elif tcode == 'V':
+ return np.asarray([[b'a', b'b'], [b'c', b'd']], dtype='V')
+ else:
+ return np.eye(2, dtype=tcode)
+
+ def get_arr1D(self, tcode):
+ # return a valid 1D array for the typecode
+ if tcode == 'M':
+ return np.ones(2, dtype='datetime64[ms]')
+ elif tcode =='m':
+ return np.ones(2, dtype='timedelta64[ms]')
+ elif tcode == 'V':
+ return np.asarray([b'a', b'b'], dtype='V')
+ else:
+ return np.ones(2, dtype=tcode)
+
+ @pytest.mark.parametrize("tcode", np.typecodes['All'])
+ def test_inv(self, tcode):
+ # check backwards compat vs scipy 1.16
+ a = self.get_arr2D(tcode)
+ if tcode in 'SUVO':
+ # raises
+ with pytest.raises(ValueError):
+ inv(a)
+ else:
+ # passes
+ inv(a)
+
+ @pytest.mark.parametrize("tcode", np.typecodes['All'])
+ def test_det(self, tcode):
+ a = self.get_arr2D(tcode)
+
+ is_arm = platform.machine() == 'arm64'
+ is_armhf = platform.machine() == 'armv8l' # gh-24831
+ is_windows = os.name == 'nt'
+
+ failing_tcodes = 'SUVOmM'
+ if not (is_arm or is_armhf or is_windows):
+ failing_tcodes += 'gG'
+
+ if tcode in failing_tcodes:
+ # raises
+ with pytest.raises(TypeError):
+ det(a)
+ else:
+ # passes
+ det(a)
+
+ @pytest.mark.filterwarnings("ignore:Casting complex values")
+ @pytest.mark.parametrize("tcode_a", np.typecodes['All'])
+ @pytest.mark.parametrize("tcode_b", np.typecodes['All'])
+ def test_solve(self, tcode_a, tcode_b):
+ a = self.get_arr2D(tcode_a)
+ b = self.get_arr1D(tcode_b)
+
+ can_combine = True
+ try:
+ np.result_type(tcode_a, tcode_b)
+ except TypeError:
+ can_combine = False
+
+ if not can_combine:
+ # np.exceptions.DTypePromotionError subclasses TypeError
+ with pytest.raises(TypeError):
+ solve(a, b)
+ elif tcode_a in 'SUVO' or tcode_b in 'VO':
+ with pytest.raises(ValueError):
+ solve(a, b)
+ else:
+ solve(a, b)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_batch.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_batch.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cbf25369196a05f955e3812859918c54867b0ce
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_batch.py
@@ -0,0 +1,742 @@
+import inspect
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+from scipy import linalg, sparse
+
+
+real_floating = [np.float32, np.float64]
+complex_floating = [np.complex64, np.complex128]
+floating = real_floating + complex_floating
+
+
+def get_random(shape, *, dtype, rng):
+ A = rng.random(shape)
+ if np.issubdtype(dtype, np.complexfloating):
+ A = A + rng.random(shape) * 1j
+ return A.astype(dtype)
+
+def get_nearly_hermitian(shape, dtype, atol, rng):
+ # Generate a batch of nearly Hermitian matrices with specified
+ # `shape` and `dtype`. `atol` controls the level of noise in
+ # Hermitian-ness to by generated by `rng`.
+ A = rng.random(shape).astype(dtype)
+ At = np.conj(A.swapaxes(-1, -2))
+ noise = rng.standard_normal(size=A.shape).astype(dtype) * atol
+ return A + At + noise
+
+
+class TestBatch:
+ # Test batch support for most linalg functions
+
+ def batch_test(self, fun, arrays, *, core_dim=2, n_out=1, kwargs=None, dtype=None,
+ broadcast=True, check_kwargs=True):
+ # Check that all outputs of batched call `fun(A, **kwargs)` are the same
+ # as if we loop over the separate vectors/matrices in `A`. Also check
+ # that `fun` accepts `A` by position or keyword and that results are
+ # identical. This is important because the name of the array argument
+ # is manually specified to the decorator, and it's easy to mess up.
+ # However, this makes it hard to test positional arguments passed
+ # after the array, so we test that separately for a few functions to
+ # make sure the decorator is working as it should.
+
+ kwargs = {} if kwargs is None else kwargs
+ parameters = list(inspect.signature(fun).parameters.keys())
+ arrays = (arrays,) if not isinstance(arrays, tuple) else arrays
+
+ # Identical results when passing argument by keyword or position
+ res2 = fun(*arrays, **kwargs)
+ if check_kwargs:
+ res1 = fun(**dict(zip(parameters, arrays)), **kwargs)
+ for out1, out2 in zip(res1, res2): # even a single array is iterable...
+ np.testing.assert_equal(out1, out2)
+
+ # Check results vs looping over
+ res = (res2,) if n_out == 1 else res2
+ # This is not the general behavior (only batch dimensions get
+ # broadcasted by the decorator) but it's easier for testing.
+ if broadcast:
+ arrays = np.broadcast_arrays(*arrays)
+ batch_shape = arrays[0].shape[:-core_dim]
+ for i in range(batch_shape[0]):
+ for j in range(batch_shape[1]):
+ arrays_ij = (array[i, j] for array in arrays)
+ ref = fun(*arrays_ij, **kwargs)
+ # see gh-25508:
+ if (np.dtype(np.int_).itemsize == 4 and
+ n_out > 1 and isinstance(ref[0], int)):
+ ref = tuple(np.asarray(refk, dtype=np.int64) for refk in ref)
+ else:
+ ref = ((np.asarray(ref),) if n_out == 1 else
+ tuple(np.asarray(refk) for refk in ref))
+ for k in range(n_out):
+ assert_allclose(res[k][i, j], ref[k])
+ assert np.shape(res[k][i, j]) == ref[k].shape
+
+ for k in range(len(ref)):
+ out_dtype = ref[k].dtype if dtype is None else dtype
+ assert res[k].dtype == out_dtype
+
+ return res2 # return original, non-tuplized result
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_expm_cond(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = rng.random((5, 3, 4, 4)).astype(dtype)
+ self.batch_test(linalg.expm_cond, A)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_issymmetric(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_nearly_hermitian((5, 3, 4, 4), dtype, 3e-4, rng)
+ res = self.batch_test(linalg.issymmetric, A, kwargs=dict(atol=1e-3))
+ assert not np.all(res) # ensure test is not trivial: not all True or False;
+ assert np.any(res) # also confirms that `atol` is passed to issymmetric
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_ishermitian(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_nearly_hermitian((5, 3, 4, 4), dtype, 3e-4, rng)
+ res = self.batch_test(linalg.ishermitian, A, kwargs=dict(atol=1e-3))
+ assert not np.all(res) # ensure test is not trivial: not all True or False;
+ assert np.any(res) # also confirms that `atol` is passed to ishermitian
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_diagsvd(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = rng.random((5, 3, 4)).astype(dtype)
+ res1 = self.batch_test(linalg.diagsvd, A, kwargs=dict(M=6, N=4), core_dim=1)
+ # test that `M, N` can be passed by position
+ res2 = linalg.diagsvd(A, 6, 4)
+ np.testing.assert_equal(res1, res2)
+
+ @pytest.mark.parametrize('fun', [linalg.inv, linalg.sqrtm, linalg.signm,
+ linalg.sinm, linalg.cosm, linalg.tanhm,
+ linalg.sinhm, linalg.coshm, linalg.tanhm,
+ linalg.pinv, linalg.pinvh, linalg.orth])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_matmat(self, fun, dtype): # matrix in, matrix out
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+
+ # sqrtm can return complex output for real input resulting in i/o type
+ # mismatch. Nudge the eigenvalues to positive side to avoid this.
+ if fun == linalg.sqrtm:
+ A = A + 3*np.eye(4, dtype=dtype)
+
+ self.batch_test(fun, A)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_null_space(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 6), dtype=dtype, rng=rng)
+ self.batch_test(linalg.null_space, A)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_funm(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 4, 3, 3), dtype=dtype, rng=rng)
+ self.batch_test(linalg.funm, A, kwargs=dict(func=np.sin))
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_fractional_matrix_power(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 4, 3, 3), dtype=dtype, rng=rng)
+ res1 = self.batch_test(linalg.fractional_matrix_power, A, kwargs={'t':1.5})
+ # test that `t` can be passed by position
+ res2 = linalg.fractional_matrix_power(A, 1.5)
+ np.testing.assert_equal(res1, res2)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_logm(self, dtype):
+ # One test failed absolute tolerance with default random seed
+ rng = np.random.default_rng(89940026998903887141749720079406074936)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+ A = A + 3*np.eye(4) # avoid complex output for real input
+ res1 = self.batch_test(linalg.logm, A)
+ # test that `disp` can be passed by position
+ res2 = linalg.logm(A)
+ for res1i, res2i in zip(res1, res2):
+ np.testing.assert_equal(res1i, res2i)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_pinv(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+ self.batch_test(linalg.pinv, A, n_out=2, kwargs=dict(return_rank=True))
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_matrix_balance(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+ self.batch_test(linalg.matrix_balance, A, n_out=2)
+ self.batch_test(linalg.matrix_balance, A, n_out=2, kwargs={'separate':True})
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_bandwidth(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((4, 4), dtype=dtype, rng=rng)
+ A = np.asarray([np.triu(A, k) for k in range(-3, 3)]).reshape((2, 3, 4, 4))
+ self.batch_test(linalg.bandwidth, A, n_out=2)
+
+ @pytest.mark.parametrize('fun_n_out', [(linalg.cholesky, 1), (linalg.ldl, 3),
+ (linalg.cho_factor, 2)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_ldl_cholesky(self, fun_n_out, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ fun, n_out = fun_n_out
+ A = get_nearly_hermitian((5, 3, 4, 4), dtype, 0, rng) # exactly Hermitian
+ A = A + 4*np.eye(4, dtype=dtype) # ensure positive definite for Cholesky
+ self.batch_test(fun, A, n_out=n_out)
+
+ @pytest.mark.parametrize('compute_uv', [False, True])
+ @pytest.mark.parametrize('full_matrices', [False, True])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_svd(self, compute_uv, full_matrices, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
+ n_out = 3 if compute_uv else 1
+ self.batch_test(
+ linalg.svd, A, n_out=n_out,
+ kwargs=dict(compute_uv=compute_uv, full_matrices=full_matrices)
+ )
+
+ A = get_random((5, 3, 2, 0), dtype=dtype, rng=rng)
+ self.batch_test(
+ linalg.svd, A, n_out=n_out,
+ kwargs=dict(compute_uv=compute_uv, full_matrices=full_matrices)
+ )
+
+ @pytest.mark.parametrize('fun', [linalg.polar, linalg.rq])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_polar_qr_rq(self, fun, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
+ self.batch_test(fun, A, n_out=2)
+
+ @pytest.mark.parametrize('pivoting', [True, False])
+ @pytest.mark.parametrize('dtype', floating)
+ @pytest.mark.parametrize('mode', ['full', 'economic', 'r'])
+ def test_qr(self, mode, dtype, pivoting):
+ rng = np.random.default_rng(12345)
+ a = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
+ self.batch_test(lambda x: linalg.qr(x, mode=mode, pivoting=pivoting), a,
+ n_out=(1 if mode == 'r' else 2) + 1 if pivoting else 0)
+
+ @pytest.mark.parametrize('pivoting', [True, False])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_qr_raw(self, dtype, pivoting):
+ rng = np.random.default_rng(12345)
+ a = get_random((5, 3, 2, 4), dtype=dtype, rng=rng)
+ (q_raw, tau), r, *other = linalg.qr(a, mode="raw", pivoting=pivoting)
+
+ # return argument contains a tuple, hence `batch_test` is not applicable.
+ for i in range(a.shape[0]):
+ for j in range(a.shape[1]):
+ (q_raw_ij, tau_ij), r_ij, *other_ij = linalg.qr(
+ a[i, j, :, :], mode="raw", pivoting=pivoting
+ )
+
+ assert_allclose(q_raw[i, j, :, :], q_raw_ij)
+ assert_allclose(tau[i, j, :], tau_ij)
+ assert_allclose(r[i, j, :, :], r_ij)
+
+ if pivoting:
+ assert_allclose(other[0][i, j, :], other_ij[0])
+
+
+ @pytest.mark.parametrize('cdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_qr_multiply(self, cdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ c = get_random(cdim, dtype=dtype, rng=rng)
+ res = linalg.qr_multiply(A, c, mode='left')
+ q, r = linalg.qr(A)
+ ref = q @ c
+ atol = 1e-6 if dtype in {np.float32, np.complex64} else 1e-12
+ assert_allclose(res[0], ref, atol=atol)
+ assert_allclose(res[1], r, atol=atol)
+
+ @pytest.mark.parametrize('uvdim', [[(5,), (3,)], [(4, 5, 2), (4, 3, 2)]])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_qr_update(self, uvdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ udim, vdim = uvdim
+ A = get_random((4, 5, 3), dtype=dtype, rng=rng)
+ u = get_random(udim, dtype=dtype, rng=rng)
+ v = get_random(vdim, dtype=dtype, rng=rng)
+ q, r = linalg.qr(A)
+ res = linalg.qr_update(q, r, u, v)
+ for i in range(4):
+ qi, ri = q[i], r[i]
+ ui, vi = (u, v) if u.ndim == 1 else (u[i], v[i])
+ ref_i = linalg.qr_update(qi, ri, ui, vi)
+ assert_allclose(res[0][i], ref_i[0])
+ assert_allclose(res[1][i], ref_i[1])
+
+ @pytest.mark.parametrize('udim', [(5,), (4, 3, 5)])
+ @pytest.mark.parametrize('kdim', [(), (4,)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_qr_insert(self, udim, kdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((4, 5, 5), dtype=dtype, rng=rng)
+ u = get_random(udim, dtype=dtype, rng=rng)
+ k = rng.integers(0, 5, size=kdim)
+ q, r = linalg.qr(A)
+ res = linalg.qr_insert(q, r, u, k)
+ for i in range(4):
+ qi, ri = q[i], r[i]
+ ki = k if k.ndim == 0 else k[i]
+ ui = u if u.ndim == 1 else u[i]
+ ref_i = linalg.qr_insert(qi, ri, ui, ki)
+ assert_allclose(res[0][i], ref_i[0])
+ assert_allclose(res[1][i], ref_i[1])
+
+ @pytest.mark.parametrize('kdim', [(), (4,)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_qr_delete(self, kdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((4, 5, 5), dtype=dtype, rng=rng)
+ k = rng.integers(0, 4, size=kdim)
+ q, r = linalg.qr(A)
+ res = linalg.qr_delete(q, r, k)
+ for i in range(4):
+ qi, ri = q[i], r[i]
+ ki = k if k.ndim == 0 else k[i]
+ ref_i = linalg.qr_delete(qi, ri, ki)
+ assert_allclose(res[0][i], ref_i[0])
+ assert_allclose(res[1][i], ref_i[1])
+
+ @pytest.mark.parametrize('fun', [linalg.schur, linalg.lu_factor])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_schur_lu(self, fun, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+ self.batch_test(fun, A, n_out=2)
+
+ @pytest.mark.parametrize('calc_q', [False, True])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_hessenberg(self, calc_q, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+ n_out = 2 if calc_q else 1
+ self.batch_test(linalg.hessenberg, A, n_out=n_out, kwargs=dict(calc_q=calc_q))
+
+ @pytest.mark.parametrize('eigvals_only', [False, True])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_eig_banded(self, eigvals_only, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+ n_out = 1 if eigvals_only else 2
+ self.batch_test(linalg.eig_banded, A, n_out=n_out,
+ kwargs=dict(eigvals_only=eigvals_only))
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_eigvals_banded(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 4), dtype=dtype, rng=rng)
+ self.batch_test(linalg.eigvals_banded, A)
+
+ @pytest.mark.parametrize('two_in', [False, True])
+ @pytest.mark.parametrize('fun_n_nout', [(linalg.eigh, 1), (linalg.eigh, 2),
+ (linalg.eigvalsh, 1), (linalg.eigvals, 1)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_eigh(self, two_in, fun_n_nout, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ fun, n_out = fun_n_nout
+ A = get_nearly_hermitian((1, 3, 4, 4), dtype, 0, rng) # exactly Hermitian
+ B = get_nearly_hermitian((2, 1, 4, 4), dtype, 0, rng) # exactly Hermitian
+ B = B + 4*np.eye(4).astype(dtype) # needs to be positive definite
+ args = (A, B) if two_in else (A,)
+ kwargs = dict(eigvals_only=True) if (n_out == 1 and fun==linalg.eigh) else {}
+ self.batch_test(fun, args, n_out=n_out, kwargs=kwargs)
+
+ @pytest.mark.parametrize('compute_expm', [False, True])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_expm_frechet(self, compute_expm, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((1, 3, 4, 4), dtype=dtype, rng=rng)
+ E = get_random((2, 1, 4, 4), dtype=dtype, rng=rng)
+ n_out = 2 if compute_expm else 1
+ self.batch_test(linalg.expm_frechet, (A, E), n_out=n_out,
+ kwargs=dict(compute_expm=compute_expm))
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_subspace_angles(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((1, 3, 4, 3), dtype=dtype, rng=rng)
+ B = get_random((2, 1, 4, 3), dtype=dtype, rng=rng)
+ self.batch_test(linalg.subspace_angles, (A, B))
+ # just to show that A and B don't need to be broadcastable
+ M, N, K = 4, 5, 3
+ A = get_random((1, 3, M, N), dtype=dtype, rng=rng)
+ B = get_random((2, 1, M, K), dtype=dtype, rng=rng)
+ assert linalg.subspace_angles(A, B).shape == (2, 3, min(N, K))
+
+ @pytest.mark.parametrize('fun', [linalg.svdvals])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_svdvals(self, fun, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 4, 5), dtype=dtype, rng=rng)
+ self.batch_test(fun, A)
+
+ @pytest.mark.parametrize('fun_n_out', [(linalg.orthogonal_procrustes, 2),
+ (linalg.khatri_rao, 1),
+ (linalg.solve_continuous_lyapunov, 1),
+ (linalg.solve_discrete_lyapunov, 1),
+ (linalg.qz, 4),
+ (linalg.ordqz, 6)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_two_generic_matrix_inputs(self, fun_n_out, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ fun, n_out = fun_n_out
+ A = get_random((2, 3, 4, 4), dtype=dtype, rng=rng)
+ B = get_random((2, 3, 4, 4), dtype=dtype, rng=rng)
+ self.batch_test(fun, (A, B), n_out=n_out)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_cossin(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ p, q = 3, 4
+ X = get_random((2, 3, 10, 10), dtype=dtype, rng=rng)
+ x11, x12, x21, x22 = (X[..., :p, :q], X[..., :p, q:],
+ X[..., p:, :q], X[..., p:, q:])
+ res = linalg.cossin(X, p, q)
+ ref = linalg.cossin((x11, x12, x21, x22))
+ for res_i, ref_i in zip(res, ref):
+ np.testing.assert_equal(res_i, ref_i)
+
+ for j in range(2):
+ for k in range(3):
+ ref_jk = linalg.cossin(X[j, k], p, q)
+ for res_i, ref_ijk in zip(res, ref_jk):
+ np.testing.assert_equal(res_i[j, k], ref_ijk)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_sylvester(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ B = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ C = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ self.batch_test(linalg.solve_sylvester, (A, B, C))
+
+ @pytest.mark.parametrize('fun', [linalg.solve_continuous_are,
+ linalg.solve_discrete_are])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_are(self, fun, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ a = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ b = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ q = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng)
+ r = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng)
+ a = a + 5*np.eye(5) # making these positive definite seems to help
+ b = b + 5*np.eye(5)
+ q = q + 5*np.eye(5)
+ r = r + 5*np.eye(5)
+ e = np.eye(5)
+ s = np.zeros((5, 5))
+ self.batch_test(fun, (a, b, q, r))
+ self.batch_test(fun, (a, b, q, r, e))
+ self.batch_test(fun, (a, b, q, r, e, s))
+
+ res = fun(a, b, q, r)
+ ref = fun(a, b, q, r, s=s)
+ np.testing.assert_allclose(res, ref)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_rsf2cs(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 4, 4), dtype=dtype, rng=rng)
+ T, Z = linalg.schur(A)
+ self.batch_test(linalg.rsf2csf, (T, Z), n_out=2)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_cholesky_banded(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ ab = get_random((5, 4, 3, 6), dtype=dtype, rng=rng)
+ ab[..., -1, :] = 10 # make diagonal dominant
+ self.batch_test(linalg.cholesky_banded, ab)
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_block_diag(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ a = get_random((1, 3, 1, 3), dtype=dtype, rng=rng)
+ b = get_random((2, 1, 3, 6), dtype=dtype, rng=rng)
+ c = get_random((1, 1, 3, 2), dtype=dtype, rng=rng)
+
+ # batch_test doesn't have the logic to broadcast just the batch shapes,
+ # so do it manually.
+ a2 = np.broadcast_to(a, (2, 3, 1, 3))
+ b2 = np.broadcast_to(b, (2, 3, 3, 6))
+ c2 = np.broadcast_to(c, (2, 3, 3, 2))
+ ref = self.batch_test(linalg.block_diag, (a2, b2, c2),
+ check_kwargs=False, broadcast=False)
+
+ # Check that `block_diag` broadcasts the batch shapes as expected.
+ res = linalg.block_diag(a, b, c)
+ assert_allclose(res, ref)
+
+ @pytest.mark.parametrize('fun_n_out', [(linalg.eigh_tridiagonal, 2),
+ (linalg.eigvalsh_tridiagonal, 1)])
+ @pytest.mark.parametrize('dtype', real_floating)
+ # "Only real arrays currently supported"
+ def test_eigh_tridiagonal(self, fun_n_out, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ fun, n_out = fun_n_out
+ d = get_random((3, 4, 5), dtype=dtype, rng=rng)
+ e = get_random((3, 4, 4), dtype=dtype, rng=rng)
+ self.batch_test(fun, (d, e), core_dim=1, n_out=n_out, broadcast=False)
+
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_solve(self, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ x = linalg.solve(A, b)
+ if len(bdim) == 1:
+ x = x[..., np.newaxis]
+ b = b[..., np.newaxis]
+ assert_allclose(A @ x - b, 0, atol=2e-6)
+ atol = 3e-6
+ if dtype is np.float32:
+ atol = 4e-6
+ assert_allclose(x, np.linalg.solve(A, b), atol=atol)
+
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_lu_solve(self, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ lu_and_piv = linalg.lu_factor(A)
+ x = linalg.lu_solve(lu_and_piv, b)
+ if len(bdim) == 1:
+ x = x[..., np.newaxis]
+ b = b[..., np.newaxis]
+ assert_allclose(A @ x - b, 0, atol=2e-6)
+ atol = 3e-6
+ if dtype is np.float32:
+ atol = 4e-6
+ assert_allclose(x, np.linalg.solve(A, b), atol=atol)
+
+ @pytest.mark.parametrize('l_and_u', [(1, 1), ([2, 1, 0], [0, 1 , 2])])
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_solve_banded(self, l_and_u, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ l, u = l_and_u
+ ab = get_random((2, 3, 3, 5), dtype=dtype, rng=rng)
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ x = linalg.solve_banded((l, u), ab, b)
+ for i in range(2):
+ for j in range(3):
+ bij = b if len(bdim) <= 2 else b[i, j]
+ lj = l if np.ndim(l) == 0 else l[j]
+ uj = u if np.ndim(u) == 0 else u[j]
+ xij = linalg.solve_banded((lj, uj), ab[i, j], bij)
+ assert_allclose(x[i, j], xij)
+
+ @pytest.mark.parametrize('separate_r', [False, True])
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_solve_toeplitz(self, separate_r, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ c = get_random((2, 3, 5), dtype=dtype, rng=rng)
+ r = get_random((2, 3, 5), dtype=dtype, rng=rng)
+ c_or_cr = (c, r) if separate_r else c
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ x = linalg.solve_toeplitz(c_or_cr, b)
+ for i in range(2):
+ for j in range(3):
+ bij = b if len(bdim) <= 2 else b[i, j]
+ c_or_cr_ij = (c[i, j], r[i, j]) if separate_r else c[i, j]
+ xij = linalg.solve_toeplitz(c_or_cr_ij, bij)
+ assert_allclose(x[i, j], xij)
+
+ @pytest.mark.parametrize('separate_r', [False, True])
+ @pytest.mark.parametrize('xdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_matmul_toeplitz(self, separate_r, xdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ c = get_random((2, 3, 5), dtype=dtype, rng=rng)
+ r = get_random((2, 3, 5), dtype=dtype, rng=rng)
+ c_or_cr = (c, r) if separate_r else c
+ x = get_random(xdim, dtype=dtype, rng=rng)
+ res = linalg.matmul_toeplitz(c_or_cr, x)
+ if separate_r:
+ ref = linalg.toeplitz(c, r) @ x
+ else:
+ ref = linalg.toeplitz(c) @ x
+ atol = 1e-6 if dtype in {np.float32, np.complex64} else 1e-12
+ assert_allclose(res, ref, atol=atol)
+
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_cho_solve(self, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_nearly_hermitian((2, 3, 5, 5), dtype=dtype, atol=0, rng=rng)
+ A = A + 5*np.eye(5)
+ c_and_lower = linalg.cho_factor(A)
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ x = linalg.cho_solve(c_and_lower, b)
+ if len(bdim) == 1:
+ x = x[..., np.newaxis]
+ b = b[..., np.newaxis]
+ assert_allclose(A @ x - b, 0, atol=1e-6)
+ assert_allclose(x, np.linalg.solve(A, b), atol=2e-6)
+
+ @pytest.mark.parametrize('lower', [False, True])
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_cho_solve_banded(self, lower, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 3, 5), dtype=dtype, rng=rng)
+ row_diag = 0 if lower else -1
+ A[:, :, row_diag] = 10
+ cb = linalg.cholesky_banded(A, lower=lower)
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ x = linalg.cho_solve_banded((cb, lower), b)
+ for i in range(2):
+ for j in range(3):
+ bij = b if len(bdim) <= 2 else b[i, j]
+ xij = linalg.cho_solve_banded((cb[i, j], lower), bij)
+ assert_allclose(x[i, j], xij)
+
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_solveh_banded(self, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 3, 5), dtype=dtype, rng=rng)
+ A[:, :, -1] = 10
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ x = linalg.solveh_banded(A, b)
+ for i in range(2):
+ for j in range(3):
+ bij = b if len(bdim) <= 2 else b[i, j]
+ xij = linalg.solveh_banded(A[i, j], bij)
+ assert_allclose(x[i, j], xij)
+
+ @pytest.mark.parametrize('bdim', [(5,), (5, 4), (2, 3, 5, 4)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_solve_triangular(self, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 5, 5), dtype=dtype, rng=rng)
+ A = np.tril(A)
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ x = linalg.solve_triangular(A, b, lower=True)
+ if len(bdim) == 1:
+ x = x[..., np.newaxis]
+ b = b[..., np.newaxis]
+ atol = 1e-10 if dtype in (np.complex128, np.float64) else 2e-4
+ assert_allclose(A @ x - b, 0, atol=atol)
+ assert_allclose(x, np.linalg.solve(A, b), atol=5*atol)
+
+ @pytest.mark.parametrize('bdim', [(4,), (4, 3), (2, 3, 4, 3)])
+ @pytest.mark.parametrize('dtype', floating)
+ def test_lstsq(self, bdim, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((2, 3, 4, 5), dtype=dtype, rng=rng)
+ b = get_random(bdim, dtype=dtype, rng=rng)
+ res = linalg.lstsq(A, b)
+ x = res[0]
+ if len(bdim) == 1:
+ x = x[..., np.newaxis]
+ b = b[..., np.newaxis]
+ assert_allclose(A @ x - b, 0, atol=2e-6)
+ assert len(res) == 4
+
+ @pytest.mark.parametrize('dtype', floating)
+ def test_clarkson_woodruff_transform(self, dtype):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 6), dtype=dtype, rng=rng)
+ self.batch_test(linalg.clarkson_woodruff_transform, A,
+ kwargs=dict(sketch_size=3, rng=311224))
+
+ def test_clarkson_woodruff_transform_sparse(self):
+ rng = np.random.default_rng(8342310302941288912051)
+ A = get_random((5, 3, 4, 6), dtype=np.float64, rng=rng)
+ A = sparse.coo_array(A)
+ message = "Batch support for sparse arrays is not available."
+ with pytest.raises(NotImplementedError, match=message):
+ linalg.clarkson_woodruff_transform(A, sketch_size=3, rng=rng)
+
+ @pytest.mark.parametrize('f, args', [
+ (linalg.toeplitz, (np.ones((0, 4)),)),
+ ])
+ def test_zero_size_batch(self, f, args):
+ message = "does not support zero-size batches."
+ with pytest.raises(ValueError, match=message):
+ f(*args)
+
+
+@pytest.mark.parametrize(
+ "func, core_shape",
+ [
+ (linalg.solve, (3, 3)),
+ (linalg.solve_triangular, (3, 3)),
+ (lambda a, b: linalg.lstsq(a, b)[0], (3, 2)),
+ ],
+ ids=["solve", "solve_triangular", "lstsq",]
+)
+def test_shapes_solve_like(func, core_shape):
+ # test shapes for solve-like functions, where the 2nd argument may have trailing
+ # dimensions
+ m, n = core_shape
+
+ # ### 1. a.ndim == 2 ###
+
+ # 1.1 : b.ndim == 1, the "scalar" case
+ a = np.eye(m, n)
+ b = np.ones(m)
+
+ x = func(a, b)
+ assert x.shape == (n,)
+
+ # 1.2 : b.ndim == 2 : b has trailing dims
+ b = np.ones((m, 8))
+ x = func(a, b)
+ assert x.shape == (n, 8)
+
+ # 1.3 : b.ndim == 3 : b has trailing dims *and* batch dims
+ b = np.ones((4, m, 8))
+ x = func(a, b)
+ assert x.shape == (4, n, 8)
+
+ # 1.4 : b.ndim == 2 : b has batch dims *but* no trailing dims
+ b = np.ones((4, m))
+ pattern = "Shape mismatch|incompatible shapes|shapes of a|shape mismatch"
+ with pytest.raises(ValueError, match=pattern):
+ # fails to broadcast `b` vs `a` (to fix: append a length-1 trailing dim)
+ func(a, b)
+
+ # ### 2. a.ndim > 2 ###
+ a = np.broadcast_to(a, (5, 4, *a.shape)) # batch_shape = (5, 4)
+
+ # 2.1 : b is 1D
+ b = np.ones(m)
+ x = func(a, b)
+ assert x.shape == (5, 4, n)
+
+ # 2.2 : b.ndim == 2, has trailing dims
+ b = np.ones((m, 8))
+ x = func(a, b)
+ assert x.shape == (5, 4, n, 8)
+
+ # 2.3 : b has both trailing and batch dims
+ b = np.ones((5, 4, m, 8))
+ x = func(a, b)
+ assert x.shape == (5, 4, n, 8)
+
+ # 2.3.1 : b has trailing dims and (broadcastable) batch dims
+ b = np.ones((4, m, 8))
+ x = func(a, b)
+ assert x.shape == (5, 4, n, 8)
+
+ # 2.4 : b has batch dims but no trailing dims
+ b = np.ones((5, 4, m))
+ pattern = "Shape mismatch|incompatible shapes|shapes of a|shape mismatch"
+ with pytest.raises(ValueError, match=pattern):
+ # fails to broadcast `b` vs `a` (to fix: append a length-1 trailing dim)
+ func(a, b)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_blas.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea71edf1476e817787af9680bc26327c106fb75a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_blas.py
@@ -0,0 +1,1133 @@
+#
+# Created by: Pearu Peterson, April 2002
+#
+
+import math
+import pytest
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal,
+ assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+
+from numpy import (arange, triu, tril, zeros, tril_indices, ones,
+ diag, append, eye, nonzero)
+
+import scipy
+from scipy.linalg import get_blas_funcs, toeplitz, solve
+from scipy.linalg.blas import HAS_ILP64
+
+try:
+ from scipy.linalg import _fblas as fblas
+ FBLAS_ERROR = fblas.__fblas_error
+ HAS_LP64_FBLAS = True
+except ImportError:
+ fblas = None
+ HAS_LP64_FBLAS = False
+
+try:
+ from scipy.linalg import _fblas_64 as fblas_64
+ FBLAS_ERROR = fblas_64.__fblas_64_error
+except ImportError:
+ fblas_64 = None
+
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+def test_get_blas_funcs():
+ # check that it returns Fortran code for arrays that are
+ # fortran-ordered
+ f1, f2, f3 = get_blas_funcs(
+ ('axpy', 'axpy', 'axpy'),
+ (np.empty((2, 2), dtype=np.complex64, order='F'),
+ np.empty((2, 2), dtype=np.complex128, order='C'))
+ )
+
+ # get_blas_funcs will choose libraries depending on most generic
+ # array
+ assert_equal(f1.typecode, 'z')
+ assert_equal(f2.typecode, 'z')
+
+ # check defaults.
+ f1 = get_blas_funcs('rotg')
+ assert_equal(f1.typecode, 'd')
+
+ # check also dtype interface
+ f1 = get_blas_funcs('gemm', dtype=np.complex64)
+ assert_equal(f1.typecode, 'c')
+ f1 = get_blas_funcs('gemm', dtype='F')
+ assert_equal(f1.typecode, 'c')
+
+ # extended precision complex
+ f1 = get_blas_funcs('gemm', dtype=np.clongdouble)
+ assert_equal(f1.typecode, 'z')
+
+ # check safe complex upcasting
+ f1 = get_blas_funcs('axpy',
+ (np.empty((2, 2), dtype=np.float64),
+ np.empty((2, 2), dtype=np.complex64))
+ )
+ assert_equal(f1.typecode, 'z')
+
+
+def test_get_blas_funcs_ilp_preferred():
+ # "preferred" mean ILP64 if available LP64 otherwise
+ gemm = get_blas_funcs('gemm', (np.eye(3),), ilp64="preferred")
+ assert gemm.int_dtype == np.int64 if HAS_ILP64 else np.int32
+ assert gemm.module_name == 'fblas_64' if HAS_ILP64 else 'fblas'
+
+ # default is "preferred"
+ gemm = get_blas_funcs('gemm', (np.eye(3),))
+ assert gemm.int_dtype == np.int64 if HAS_ILP64 else np.int32
+ assert gemm.module_name == 'fblas_64' if HAS_ILP64 else 'fblas'
+
+
+def test_get_blas_funcs_ilp_true():
+ # True is ILP64 or fail if not available
+ if HAS_ILP64:
+ gemm = get_blas_funcs('gemm', (np.eye(3),), ilp64=True)
+ assert gemm.int_dtype == np.int64
+ assert gemm.module_name == 'fblas_64'
+ else:
+ with pytest.raises(RuntimeError):
+ get_blas_funcs('gemm', (np.eye(3),), ilp64=True)
+
+
+def test_get_blas_funcs_ilp_false():
+ # False is LP64 or fail if not available
+ if HAS_LP64_FBLAS:
+ gemm = get_blas_funcs('gemm', (np.eye(3),), ilp64=False)
+ assert gemm.int_dtype == np.int32
+ assert gemm.module_name == 'fblas'
+ else:
+ with pytest.raises(ValueError):
+ get_blas_funcs('gemm', (np.eye(3),), ilp64=False)
+
+
+def test_get_blas_funcs_alias():
+ # check alias for get_blas_funcs
+ f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
+ assert f.typecode == 'c'
+ assert g.typecode == 'c'
+
+ f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
+ assert f is g
+ assert f is h
+
+
+def _dt_from_prefix(prefix):
+ """Array dtype from a blas-style prefix."""
+ if prefix.startswith('i'):
+ prefix = prefix[1:] # isamax, idamax etc
+ elif prefix in ['sc', 'dz']:
+ prefix = prefix[0] # scasum, dzasum
+ elif prefix in ['cs', 'zd']:
+ prefix = prefix[0] # zdscal, csscal
+
+ dt_map = {'z': np.complex128, 'c': np.complex64, 'd': np.float64, 's': np.float32}
+ return dt_map[prefix]
+
+
+def parametrize_blas(func_name, prefixes, modules=None):
+ """Parametrize a test over BLAS prefixes, "sdcz", and over the BLAS modules,
+ `fblas,fblas_64.
+
+ Given a func_name "gemm", this generates a pytest parametrization over up to 8
+ variants: sgemm, dgemm, cgemm, zgemm, each loaded from `fblas` (i.e. 32-bit LP64
+ variants) and `fblas_64` (i.e. 64-bit ILP64 variants)..
+
+ If a module is not available, the pytest parameter has a skip mark, so that the
+ test is skipped with a descriptive message.
+
+ Parameters
+ ----------
+ func_name : str
+ The base name of a BLAS function, e.g. "gemm"
+ prefixes : str or sequence
+ BLAS prefixes to prepend to `func_name`.
+ E.g. ``func_name='gemm', prefixes='cz'`` generates `cgemm` and `zgemm`.
+ modules : sequence of ``(module, str)`` pairs
+ BLAS modules to fetch functions from. By default, use `fblas` (LP64 variant)
+ and fblas_64 (ILP64 variant).
+ """
+ if modules is None:
+ modules = [(fblas, "fblas"), (fblas_64, "fblas_64")]
+
+ params = []
+ for mod, mod_name in modules:
+ for prefix in prefixes:
+ dtype = _dt_from_prefix(prefix)
+ if mod is None:
+ param_ = pytest.param(
+ None, dtype,
+ id=f"{mod_name}.{prefix}{func_name}",
+ marks=pytest.mark.skip(reason=f"{mod_name} is not available")
+ )
+ else:
+ # Fetch the BLAS function from the BLAS module. NB: if the name is not
+ # found in the module, it's a hard failure (all names must be present).
+ f = getattr(mod, prefix + func_name)
+ param_ = pytest.param(f, dtype, id=f"{mod_name}.{prefix}{func_name}")
+
+ params.append(param_)
+
+ return pytest.mark.parametrize("f, dtype", params)
+
+
+class TestFBLAS1Simple:
+
+ @parametrize_blas("axpy", "sdcz")
+ def test_axpy(self, f, dtype):
+ assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
+ [7, 9, 18])
+ if dtype in COMPLEX_DTYPES:
+ assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
+ [7, 10j-1, 18])
+
+ @parametrize_blas("copy", "sdcz")
+ def test_copy(self, f, dtype):
+ assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5])
+ if dtype in COMPLEX_DTYPES:
+ assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
+
+ @parametrize_blas("asum", ["s", "d", "sc", "dz"])
+ def test_asum(self, f, dtype):
+ assert_almost_equal(f([3, -4, 5]), 12)
+ if dtype in COMPLEX_DTYPES:
+ assert_almost_equal(f([3j, -4, 3-4j]), 14)
+
+ @parametrize_blas("dot", "sd")
+ def test_dot(self, f, dtype):
+ assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
+
+ @parametrize_blas("dotu", "cz")
+ def test_dotu(self, f, dtype):
+ assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
+
+ @parametrize_blas("dotc", "cz")
+ def test_dotc(self, f, dtype):
+ assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
+
+ @parametrize_blas("nrm2", ["s", "d", "sc", "dz"])
+ def test_nrm2(self, f, dtype):
+ assert_almost_equal(f([3, -4, 5]), math.sqrt(50))
+ if dtype in COMPLEX_DTYPES:
+ assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
+
+ @parametrize_blas("scal", ["s", "d", "cs", "zd"])
+ def test_scal(self, f, dtype):
+ assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10])
+ if dtype in COMPLEX_DTYPES:
+ assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
+
+ @parametrize_blas("swap", "sdcz")
+ def test_swap(self, f, dtype):
+ x, y = [2, 3, 1], [-2, 3, 7]
+ x1, y1 = f(x, y)
+ assert_array_almost_equal(x1, y)
+ assert_array_almost_equal(y1, x)
+
+ if dtype in COMPLEX_DTYPES:
+ x, y = [2, 3j, 1], [-2, 3, 7-3j]
+ x1, y1 = f(x, y)
+ assert_array_almost_equal(x1, y)
+ assert_array_almost_equal(y1, x)
+
+ @parametrize_blas("amax", ["is", "id", "ic", "iz"])
+ def test_amax(self, f, dtype):
+ assert_equal(f([-2, 4, 3]), 1)
+ if dtype in COMPLEX_DTYPES:
+ assert_equal(f([-5, 4+3j, 6]), 1)
+
+ # XXX: need tests for rot,rotm,rotg,rotmg
+
+
+class TestFBLAS2Simple:
+ @parametrize_blas("gemv", "sdcz")
+ def test_gemv(self, f, dtype):
+ assert_array_almost_equal(f(3, [[3]], [-4]), [-36])
+ assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21])
+ if dtype in COMPLEX_DTYPES:
+ assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j])
+ assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]),
+ [-48-21j])
+
+ @parametrize_blas("ger", "sd")
+ def test_ger(self, f, dtype):
+ assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]])
+ assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]),
+ [[6, 8], [12, 16], [18, 24]])
+ assert_array_almost_equal(f(1, [1, 2], [3, 4],
+ a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]])
+ if dtype in COMPLEX_DTYPES:
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
+ [[3j, 4j], [6, 8]])
+ assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
+ [[6, 8], [12, 16], [18, 24]])
+
+ @parametrize_blas("geru", "cz")
+ def test_geru(self, f, dtype):
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
+ [[3j, 4j], [6, 8]])
+ assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]),
+ [[6, 8], [12, 16], [18, 24]])
+
+ @parametrize_blas("gerc", "cz")
+ def test_gerc(self, f, dtype):
+ assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
+ [[3j, 4j], [6, 8]])
+ assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
+ [[6, 8], [12, 16], [18, 24]])
+
+ @parametrize_blas("syr", "sdcz")
+ def test_syr(self, f, dtype):
+ x = np.arange(1, 5, dtype='d')
+ resx = np.triu(x[:, np.newaxis] * x)
+ resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
+ y = np.linspace(0, 8.5, 17, endpoint=False)
+ z = np.arange(1, 9, dtype='d').view('D')
+ resz = np.triu(z[:, np.newaxis] * z)
+ resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1])
+ w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
+
+ rtol = np.finfo(dtype).eps
+
+ assert_allclose(f(1.0, x), resx, rtol=rtol)
+ assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol)
+ assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol)
+ # negative increments imply reversed vectors in blas
+ assert_allclose(f(1.0, y, incx=-2, offx=2, n=4),
+ resx_reverse, rtol=rtol)
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(f(1.0, z), resz, rtol=rtol)
+ assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol)
+ assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol)
+ # negative increments imply reversed vectors in blas
+ assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
+ resz_reverse, rtol=rtol)
+
+ a = np.zeros((4, 4), dtype, 'F')
+ b = f(1.0, z, a=a, overwrite_a=True)
+ assert_allclose(a, resz, rtol=rtol)
+ b = f(2.0, z, a=a)
+ assert a is not b
+ assert_allclose(b, 3*resz, rtol=rtol)
+
+ else:
+ a = np.zeros((4, 4), dtype, 'F')
+ b = f(1.0, x, a=a, overwrite_a=True)
+ assert_allclose(a, resx, rtol=rtol)
+ b = f(2.0, x, a=a)
+ assert a is not b
+ assert_allclose(b, 3*resx, rtol=rtol)
+
+ assert_raises(Exception, f, 1.0, x, incx=0)
+ assert_raises(Exception, f, 1.0, x, offx=5)
+ assert_raises(Exception, f, 1.0, x, offx=-2)
+ assert_raises(Exception, f, 1.0, x, n=-2)
+ assert_raises(Exception, f, 1.0, x, n=5)
+ assert_raises(Exception, f, 1.0, x, lower=2)
+ assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+ @parametrize_blas("her", "cz")
+ def test_her(self, f, dtype):
+ x = np.arange(1, 5, dtype='d')
+ z = np.arange(1, 9, dtype='d').view('D')
+ rehz = np.triu(z[:, np.newaxis] * z.conj())
+ rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
+ w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
+
+ rtol = np.finfo(dtype).eps
+
+ assert_allclose(f(1.0, z), rehz, rtol=rtol)
+ assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol)
+ assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol)
+ # negative increments imply reversed vectors in blas
+ assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
+ rehz_reverse, rtol=rtol)
+
+ a = np.zeros((4, 4), dtype, 'F')
+ b = f(1.0, z, a=a, overwrite_a=True)
+ assert_allclose(a, rehz, rtol=rtol)
+
+ b = f(2.0, z, a=a)
+ assert a is not b
+ assert_allclose(b, 3*rehz, rtol=rtol)
+
+ assert_raises(Exception, f, 1.0, x, incx=0)
+ assert_raises(Exception, f, 1.0, x, offx=5)
+ assert_raises(Exception, f, 1.0, x, offx=-2)
+ assert_raises(Exception, f, 1.0, x, n=-2)
+ assert_raises(Exception, f, 1.0, x, n=5)
+ assert_raises(Exception, f, 1.0, x, lower=2)
+ assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+ @parametrize_blas("syr2", "sd")
+ def test_syr2(self, f, dtype):
+ x = np.arange(1, 5, dtype='d')
+ y = np.arange(5, 9, dtype='d')
+ resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x)
+ resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1]
+ + y[::-1, np.newaxis] * x[::-1])
+
+ q = np.linspace(0, 8.5, 17, endpoint=False)
+ rtol = np.finfo(dtype).eps
+
+ assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
+ assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
+ assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
+
+ assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10),
+ resxy, rtol=rtol)
+ assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3),
+ resxy[:3, :3], rtol=rtol)
+ # negative increments imply reversed vectors in blas
+ assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10),
+ resxy_reverse, rtol=rtol)
+
+ a = np.zeros((4, 4), dtype, 'F')
+ b = f(1.0, x, y, a=a, overwrite_a=True)
+ assert_allclose(a, resxy, rtol=rtol)
+
+ b = f(2.0, x, y, a=a)
+ assert a is not b
+ assert_allclose(b, 3*resxy, rtol=rtol)
+
+ assert_raises(Exception, f, 1.0, x, y, incx=0)
+ assert_raises(Exception, f, 1.0, x, y, offx=5)
+ assert_raises(Exception, f, 1.0, x, y, offx=-2)
+ assert_raises(Exception, f, 1.0, x, y, incy=0)
+ assert_raises(Exception, f, 1.0, x, y, offy=5)
+ assert_raises(Exception, f, 1.0, x, y, offy=-2)
+ assert_raises(Exception, f, 1.0, x, y, n=-2)
+ assert_raises(Exception, f, 1.0, x, y, n=5)
+ assert_raises(Exception, f, 1.0, x, y, lower=2)
+ assert_raises(Exception, f, 1.0, x, y, a=np.zeros((2, 2), 'd', 'F'))
+
+ @parametrize_blas("her2", "cz")
+ def test_her2(self, f, dtype):
+ x = np.arange(1, 9, dtype='d').view('D')
+ y = np.arange(9, 17, dtype='d').view('D')
+ resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj()
+ resxy = np.triu(resxy)
+
+ resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj()
+ resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj()
+ resxy_reverse = np.triu(resxy_reverse)
+
+ u = np.c_[np.zeros(4), x, np.zeros(4)].ravel()
+ v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
+
+ rtol = np.finfo(dtype).eps
+
+ assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
+ assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
+ assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(),
+ rtol=rtol)
+
+ assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1),
+ resxy, rtol=rtol)
+ assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3),
+ resxy[:3, :3], rtol=rtol)
+ # negative increments imply reversed vectors in blas
+ assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1),
+ resxy_reverse, rtol=rtol)
+
+ a = np.zeros((4, 4), dtype, 'F')
+ b = f(1.0, x, y, a=a, overwrite_a=True)
+ assert_allclose(a, resxy, rtol=rtol)
+
+ b = f(2.0, x, y, a=a)
+ assert a is not b
+ assert_allclose(b, 3*resxy, rtol=rtol)
+
+ assert_raises(Exception, f, 1.0, x, y, incx=0)
+ assert_raises(Exception, f, 1.0, x, y, offx=5)
+ assert_raises(Exception, f, 1.0, x, y, offx=-2)
+ assert_raises(Exception, f, 1.0, x, y, incy=0)
+ assert_raises(Exception, f, 1.0, x, y, offy=5)
+ assert_raises(Exception, f, 1.0, x, y, offy=-2)
+ assert_raises(Exception, f, 1.0, x, y, n=-2)
+ assert_raises(Exception, f, 1.0, x, y, n=5)
+ assert_raises(Exception, f, 1.0, x, y, lower=2)
+ assert_raises(Exception, f, 1.0, x, y,
+ a=np.zeros((2, 2), 'd', 'F'))
+
+ @parametrize_blas("gbmv", "sdcz")
+ def test_gbmv(self, f, dtype):
+ rng = np.random.default_rng(1234)
+ n = 7
+ m = 5
+ kl = 1
+ ku = 2
+ # fake a banded matrix via toeplitz
+ A = toeplitz(append(rng.random(kl+1), zeros(m-kl-1)),
+ append(rng.random(ku+1), zeros(n-ku-1)))
+ A = A.astype(dtype)
+ Ab = zeros((kl+ku+1, n), dtype=dtype)
+
+ # Form the banded storage
+ Ab[2, :5] = A[0, 0] # diag
+ Ab[1, 1:6] = A[0, 1] # sup1
+ Ab[0, 2:7] = A[0, 2] # sup2
+ Ab[3, :4] = A[1, 0] # sub1
+
+ x = rng.random(n).astype(dtype)
+ y = rng.random(m).astype(dtype)
+ alpha, beta = dtype(3), dtype(-5)
+
+ func = f
+ y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
+ x=x, y=y, beta=beta)
+ y2 = alpha * A.dot(x) + beta * y
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
+ x=y, y=x, beta=beta, trans=1)
+ y2 = alpha * A.T.dot(y) + beta * x
+ assert_array_almost_equal(y1, y2)
+
+ @pytest.mark.parametrize("ilp64", [True, False])
+ @pytest.mark.parametrize("dtype", DTYPES)
+ def test_sbmv_hbmv(self, dtype, ilp64):
+ mod = fblas_64 if ilp64 else fblas
+ if mod is None:
+ mod_name = "fblas_64" if ilp64 else "fblas"
+ pytest.skip(f"{mod_name} is not available")
+
+ rng = np.random.default_rng(1234)
+ n = 6
+ k = 2
+ A = zeros((n, n), dtype=dtype)
+ Ab = zeros((k+1, n), dtype=dtype)
+
+ # Form the array and its packed banded storage
+ A[arange(n), arange(n)] = rng.random(n)
+ for ind2 in range(1, k+1):
+ temp = rng.random(n-ind2)
+ A[arange(n-ind2), arange(ind2, n)] = temp
+ Ab[-1-ind2, ind2:] = temp
+ A = A.astype(dtype)
+ if dtype in COMPLEX_DTYPES:
+ A += A.conj().T
+ func, = get_blas_funcs(('hbmv',), dtype=dtype, ilp64="preferred")
+ else:
+ A += A.T
+ func, = get_blas_funcs(('sbmv',), dtype=dtype, ilp64="preferred")
+
+ Ab[-1, :] = diag(A)
+ x = rng.random(n).astype(dtype)
+ y = rng.random(n).astype(dtype)
+ alpha, beta = dtype(1.25), dtype(3)
+
+ y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta)
+ y2 = alpha * A.dot(x) + beta * y
+ assert_array_almost_equal(y1, y2)
+
+ @pytest.mark.parametrize("ilp64", [True, False])
+ @pytest.mark.parametrize("fname,dtype", [
+ *[('spmv', dtype) for dtype in REAL_DTYPES + COMPLEX_DTYPES],
+ *[('hpmv', dtype) for dtype in COMPLEX_DTYPES],
+ ])
+ def test_spmv_hpmv(self, fname, dtype, ilp64):
+ mod = fblas_64 if ilp64 else fblas
+ if mod is None:
+ mod_name = "fblas_64" if ilp64 else "fblas"
+ pytest.skip(f"{mod_name} is not available")
+
+ rng = np.random.default_rng(1234)
+ n = 3
+ A = rng.random((n, n)).astype(dtype)
+ if dtype in COMPLEX_DTYPES:
+ A += rng.random((n, n))*1j
+ A += A.T if fname == 'spmv' else A.conj().T
+ c, r = tril_indices(n)
+ Ap = A[r, c]
+ x = rng.random(n).astype(dtype)
+ y = rng.random(n).astype(dtype)
+ xlong = arange(2*n).astype(dtype)
+ ylong = ones(2*n).astype(dtype)
+ alpha, beta = dtype(1.25), dtype(2)
+
+ func, = get_blas_funcs((fname,), dtype=dtype, ilp64="preferred")
+ y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta)
+ y2 = alpha * A.dot(x) + beta * y
+ assert_array_almost_equal(y1, y2)
+
+ # Test inc and offsets
+ y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap,
+ incx=2, incy=2, offx=n, offy=n)
+ y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2]
+ assert_array_almost_equal(y1[3::2], y2)
+ assert_almost_equal(y1[4], ylong[4])
+
+ @pytest.mark.parametrize("ilp64", [True, False])
+ @pytest.mark.parametrize("fname,dtype", [
+ *[('spr', dtype) for dtype in REAL_DTYPES + COMPLEX_DTYPES],
+ *[('hpr', dtype) for dtype in COMPLEX_DTYPES],
+ ])
+ def test_spr_hpr(self, fname, dtype, ilp64):
+ mod = fblas_64 if ilp64 else fblas
+ if mod is None:
+ mod_name = "fblas_64" if ilp64 else "fblas"
+ pytest.skip(f"{mod_name} is not available")
+
+ rng = np.random.default_rng(1234)
+ n = 3
+ A = rng.random((n, n)).astype(dtype)
+ if dtype in COMPLEX_DTYPES:
+ A += rng.random((n, n))*1j
+ A += A.T if fname == 'spr' else A.conj().T
+ c, r = tril_indices(n)
+ Ap = A[r, c]
+ x = rng.random(n).astype(dtype)
+
+ alpha = np.finfo(dtype).dtype.type(2.5)
+ if fname == 'hpr':
+ func, = get_blas_funcs(('hpr',), dtype=dtype, ilp64="preferred")
+ y2 = alpha * x[:, None].dot(x[None, :].conj()) + A
+ else:
+ func, = get_blas_funcs(('spr',), dtype=dtype, ilp64="preferred")
+ y2 = alpha * x[:, None].dot(x[None, :]) + A
+
+ y1 = func(n=n, alpha=alpha, ap=Ap, x=x)
+ y1f = zeros((3, 3), dtype=dtype)
+ y1f[r, c] = y1
+ y1f[c, r] = y1.conj() if fname == 'hpr' else y1
+ assert_array_almost_equal(y1f, y2)
+
+ @pytest.mark.parametrize("ilp64", [True, False])
+ @pytest.mark.parametrize("dtype", DTYPES)
+ def test_spr2_hpr2(self, dtype, ilp64):
+ mod = fblas_64 if ilp64 else fblas
+ if mod is None:
+ mod_name = "fblas_64" if ilp64 else "fblas"
+ pytest.skip(f"{mod_name} is not available")
+
+ rng = np.random.default_rng(1234)
+ n = 3
+ A = rng.random((n, n)).astype(dtype)
+ if dtype in COMPLEX_DTYPES:
+ A += rng.random((n, n))*1j
+ A += A.conj().T
+ func, = get_blas_funcs(('hpr2',), dtype=dtype, ilp64="preferred")
+ else:
+ A += A.T
+ func, = get_blas_funcs(('spr2',), dtype=dtype, ilp64="preferred")
+
+ c, r = tril_indices(n)
+ Ap = A[r, c]
+ x = rng.random(n).astype(dtype)
+ y = rng.random(n).astype(dtype)
+ alpha = dtype(2)
+
+ u = alpha.conj() * x[:, None].dot(y[None, :].conj())
+ y2 = A + u + u.conj().T
+ y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap)
+ y1f = zeros((3, 3), dtype=dtype)
+ y1f[r, c] = y1
+ y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj()
+ assert_array_almost_equal(y1f, y2)
+
+ @parametrize_blas('tbmv', 'sdcz')
+ def test_tbmv(self, f, dtype):
+ rng = np.random.default_rng(1234)
+ n = 10
+ k = 3
+ x = rng.random(n).astype(dtype)
+ A = zeros((n, n), dtype=dtype)
+ # Banded upper triangular array
+ for sup in range(k+1):
+ A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
+
+ # Add complex parts for c,z
+ if dtype in COMPLEX_DTYPES:
+ A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
+
+ # Form the banded storage
+ Ab = zeros((k+1, n), dtype=dtype)
+ for row in range(k+1):
+ Ab[-row-1, row:] = diag(A, k=row)
+ func = f
+
+ y1 = func(k=k, a=Ab, x=x)
+ y2 = A.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(k=k, a=Ab, x=x, diag=1)
+ A[arange(n), arange(n)] = dtype(1)
+ y2 = A.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
+ y2 = A.T.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
+ y2 = A.conj().T.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ @parametrize_blas('tbsv', 'sdcz')
+ def test_tbsv(self, f, dtype):
+ rng = np.random.default_rng(12345)
+ n = 6
+ k = 3
+ x = rng.random(n).astype(dtype)
+ A = zeros((n, n), dtype=dtype)
+ # Banded upper triangular array
+ for sup in range(k+1):
+ A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
+
+ # Add complex parts for c,z
+ if dtype in COMPLEX_DTYPES:
+ A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
+
+ # Form the banded storage
+ Ab = zeros((k+1, n), dtype=dtype)
+ for row in range(k+1):
+ Ab[-row-1, row:] = diag(A, k=row)
+ func = f
+
+ y1 = func(k=k, a=Ab, x=x)
+ y2 = solve(A, x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(k=k, a=Ab, x=x, diag=1)
+ A[arange(n), arange(n)] = dtype(1)
+ y2 = solve(A, x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
+ y2 = solve(A.T, x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
+ y2 = solve(A.conj().T, x)
+ assert_array_almost_equal(y1, y2)
+
+ @parametrize_blas('tpmv', 'sdcz')
+ def test_tpmv(self, f, dtype):
+ rng = np.random.default_rng(1234)
+ n = 10
+ x = rng.random(n).astype(dtype)
+ # Upper triangular array
+ if dtype in COMPLEX_DTYPES:
+ A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+ else:
+ A = triu(rng.random((n, n)))
+
+ # Form the packed storage
+ c, r = tril_indices(n)
+ Ap = A[r, c]
+ func = f
+
+ y1 = func(n=n, ap=Ap, x=x)
+ y2 = A.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(n=n, ap=Ap, x=x, diag=1)
+ A[arange(n), arange(n)] = dtype(1)
+ y2 = A.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
+ y2 = A.T.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
+ y2 = A.conj().T.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ @parametrize_blas('tpsv', 'sdcz')
+ def test_tpsv(self, f, dtype):
+ rng = np.random.default_rng(1234)
+ n = 10
+ x = rng.random(n).astype(dtype)
+ # Upper triangular array
+ if dtype in COMPLEX_DTYPES:
+ A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+ else:
+ A = triu(rng.random((n, n)))
+ A += eye(n)
+ # Form the packed storage
+ c, r = tril_indices(n)
+ Ap = A[r, c]
+ func = f
+
+ y1 = func(n=n, ap=Ap, x=x)
+ y2 = solve(A, x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(n=n, ap=Ap, x=x, diag=1)
+ A[arange(n), arange(n)] = dtype(1)
+ y2 = solve(A, x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
+ y2 = solve(A.T, x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
+ y2 = solve(A.conj().T, x)
+ assert_array_almost_equal(y1, y2)
+
+ @parametrize_blas('trmv', 'sdcz')
+ def test_trmv(self, f, dtype):
+ rng = np.random.default_rng(1234)
+ n = 3
+ A = (rng.random((n, n))+eye(n)).astype(dtype)
+ x = rng.random(3).astype(dtype)
+ func = f
+
+ y1 = func(a=A, x=x)
+ y2 = triu(A).dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(a=A, x=x, diag=1)
+ A[arange(n), arange(n)] = dtype(1)
+ y2 = triu(A).dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(a=A, x=x, diag=1, trans=1)
+ y2 = triu(A).T.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(a=A, x=x, diag=1, trans=2)
+ y2 = triu(A).conj().T.dot(x)
+ assert_array_almost_equal(y1, y2)
+
+ @parametrize_blas('trsv', 'sdcz')
+ def test_trsv(self, f, dtype):
+ rng = np.random.default_rng(1234)
+ n = 15
+ A = (rng.random((n, n))+eye(n)).astype(dtype)
+ x = rng.random(n).astype(dtype)
+ func = f
+
+ y1 = func(a=A, x=x)
+ y2 = solve(triu(A), x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(a=A, x=x, lower=1)
+ y2 = solve(tril(A), x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(a=A, x=x, diag=1)
+ A[arange(n), arange(n)] = dtype(1)
+ y2 = solve(triu(A), x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(a=A, x=x, diag=1, trans=1)
+ y2 = solve(triu(A).T, x)
+ assert_array_almost_equal(y1, y2)
+
+ y1 = func(a=A, x=x, diag=1, trans=2)
+ y2 = solve(triu(A).conj().T, x)
+ assert_array_almost_equal(y1, y2)
+
+
+class TestFBLAS3Simple:
+ @parametrize_blas("gemm", "sdcz")
+ def test_gemm(self, f, dtype):
+ assert_array_almost_equal(f(3, [3], [-4]), [[-36]])
+ assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21])
+ if dtype in COMPLEX_DTYPES:
+ assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]])
+ assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
+
+
+class TestBLAS3Symm:
+
+ def setup_method(self):
+ self.a = np.array([[1., 2.],
+ [0., 1.]])
+ self.b = np.array([[1., 0., 3.],
+ [0., -1., 2.]])
+ self.c = np.ones((2, 3))
+ self.t = np.array([[2., -1., 8.],
+ [3., 0., 9.]])
+
+ @parametrize_blas("symm", "sdcz")
+ def test_symm(self, f, dtype):
+ res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
+ assert_array_almost_equal(res, self.t)
+
+ res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
+ assert_array_almost_equal(res, self.t)
+
+ res = f(a=self.a, b=self.b.T, side=1, c=self.c.T,
+ alpha=1., beta=1.)
+ assert_array_almost_equal(res, self.t.T)
+
+ @parametrize_blas("symm", "sdcz")
+ def test_symm_wrong_side(self, f, dtype):
+ """`side=1` means C <- B*A, hence shapes of A and B are to be
+ compatible. Otherwise, f2py exception is raised.
+ """
+ # FIXME narrow down to _fblas.error
+ with pytest.raises(Exception):
+ f(a=self.a, b=self.b, alpha=1, side=1)
+
+ @parametrize_blas("symm", "sdcz")
+ def test_symm_wrong_uplo(self, f, dtype):
+ """SYMM only considers the upper/lower part of A. Hence setting
+ wrong value for `lower` (default is lower=0, meaning upper triangle)
+ gives a wrong result.
+ """
+ res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
+ assert np.allclose(res, self.t)
+ res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
+ assert not np.allclose(res, self.t)
+
+
+class TestBLAS3Syrk:
+ def setup_method(self):
+ self.a = np.array([[1., 0.],
+ [0., -2.],
+ [2., 3.]])
+ self.t = np.array([[1., 0., 2.],
+ [0., 4., -6.],
+ [2., -6., 13.]])
+ self.tt = np.array([[5., 6.],
+ [6., 13.]])
+
+ @parametrize_blas("syrk", "sdcz")
+ def test_syrk(self, f, dtype):
+ c = f(a=self.a, alpha=1.)
+ assert_array_almost_equal(np.triu(c), np.triu(self.t))
+
+ c = f(a=self.a, alpha=1., lower=1)
+ assert_array_almost_equal(np.tril(c), np.tril(self.t))
+
+ c0 = np.ones(self.t.shape)
+ c = f(a=self.a, alpha=1., beta=1., c=c0)
+ assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
+
+ c = f(a=self.a, alpha=1., trans=1)
+ assert_array_almost_equal(np.triu(c), np.triu(self.tt))
+
+ # prints '0-th dimension must be fixed to 3 but got 5',
+ # FIXME: suppress?
+ @parametrize_blas("syrk", "sdcz")
+ def test_syrk_wrong_c(self, f, dtype):
+ # FIXME narrow down to _fblas.error
+ with pytest.raises(Exception):
+ f(a=self.a, alpha=1., c=np.ones((5, 8)))
+ # if C is supplied, it must have compatible dimensions
+
+
+class TestBLAS3Syr2k:
+ def setup_method(self):
+ self.a = np.array([[1., 0.],
+ [0., -2.],
+ [2., 3.]])
+ self.b = np.array([[0., 1.],
+ [1., 0.],
+ [0, 1.]])
+ self.t = np.array([[0., -1., 3.],
+ [-1., 0., 0.],
+ [3., 0., 6.]])
+ self.tt = np.array([[0., 1.],
+ [1., 6]])
+
+ @parametrize_blas("syr2k", "sdcz")
+ def test_syr2k(self, f, dtype):
+ c = f(a=self.a, b=self.b, alpha=1.)
+ assert_array_almost_equal(np.triu(c), np.triu(self.t))
+
+ c = f(a=self.a, b=self.b, alpha=1., lower=1)
+ assert_array_almost_equal(np.tril(c), np.tril(self.t))
+
+ c0 = np.ones(self.t.shape)
+ c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
+ assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
+
+ c = f(a=self.a, b=self.b, alpha=1., trans=1)
+ assert_array_almost_equal(np.triu(c), np.triu(self.tt))
+
+ # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
+ @parametrize_blas("syr2k", "sdcz")
+ def test_syr2k_wrong_c(self, f, dtype):
+ with pytest.raises(Exception):
+ f(a=self.a, b=self.b, alpha=1., c=np.zeros((15, 8)))
+ # if C is supplied, it must have compatible dimensions
+
+
+class TestSyHe:
+ """Quick and simple tests for (zc)-symm, syrk, syr2k."""
+
+ def setup_method(self):
+ self.sigma_y = np.array([[0., -1.j],
+ [1.j, 0.]])
+
+ @parametrize_blas("symm", "zc")
+ def test_symm(self, f, dtype):
+ # NB: a is symmetric w/upper diag of ONLY
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+ assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
+
+ @parametrize_blas("hemm", "zc")
+ def test_hemm(self, f, dtype):
+ # NB: a is hermitian w/upper diag of ONLY
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+ assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
+
+ @parametrize_blas("syrk", "zc")
+ def test_syrk(self, f, dtype):
+ res = f(a=self.sigma_y, alpha=1.)
+ assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
+
+ @parametrize_blas("herk", "zc")
+ def test_herk(self, f, dtype):
+ res = f(a=self.sigma_y, alpha=1.)
+ assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
+
+ @parametrize_blas("syr2k", "zc")
+ def test_syr2k_zr(self, f, dtype):
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+ assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
+
+ @parametrize_blas("her2k", "zc")
+ def test_her2k_zr(self, f, dtype):
+ res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+ assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
+
+
+class TestTRMM:
+ """Quick and simple tests for *trmm."""
+
+ def setup_method(self):
+ self.a = np.array([[1., 2., ],
+ [-2., 1.]])
+ self.b = np.array([[3., 4., -1.],
+ [5., 6., -2.]])
+
+ self.a2 = np.array([[1, 1, 2, 3],
+ [0, 1, 4, 5],
+ [0, 0, 1, 6],
+ [0, 0, 0, 1]], order="f")
+ self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]],
+ order="f")
+
+ @parametrize_blas("trmm", "sdzc")
+ def test_side(self, f, dtype):
+ trmm = f
+ # Provide large A array that works for side=1 but not 0 (see gh-10841)
+ assert_raises(Exception, trmm, 1.0, self.a2, self.b2)
+ res = trmm(1.0, self.a2.astype(dtype), self.b2.astype(dtype),
+ side=1)
+ k = self.b2.shape[1]
+ assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0.,
+ atol=100*np.finfo(dtype).eps)
+
+ @parametrize_blas("trmm", "sdcz")
+ def test_ab(self, f, dtype):
+ result = f(1., self.a, self.b)
+ # default a is upper triangular
+ expected = np.array([[13., 16., -5.],
+ [ 5., 6., -2.]])
+ assert_array_almost_equal(result, expected)
+
+ @parametrize_blas("trmm", "sdcz")
+ def test_ab_lower(self, f, dtype):
+ result = f(1., self.a, self.b, lower=True)
+ expected = np.array([[ 3., 4., -1.],
+ [-1., -2., 0.]]) # now a is lower triangular
+ assert_array_almost_equal(result, expected)
+
+ @parametrize_blas("trmm", "sdcz")
+ def test_b_overwrites(self, f, dtype):
+ # BLAS *trmm modifies B argument in-place.
+ # Here the default is to copy, but this can be overridden
+ b = self.b.astype(dtype)
+ for overwr in [True, False]:
+ bcopy = b.copy()
+ result = f(1., self.a, bcopy, overwrite_b=overwr)
+ # C-contiguous arrays are copied
+ assert not bcopy.flags.f_contiguous
+ assert not np.may_share_memory(bcopy, result)
+ assert_equal(bcopy, b)
+
+ bcopy = np.asfortranarray(b.copy()) # or just transpose it
+ result = f(1., self.a, bcopy, overwrite_b=True)
+ assert bcopy.flags.f_contiguous
+ assert np.may_share_memory(bcopy, result)
+ assert_array_almost_equal(bcopy, result)
+
+
+@parametrize_blas("trsm", "sdcz")
+def test_trsm(f, dtype):
+ rng = np.random.default_rng(1234)
+ tol = np.finfo(dtype).eps*1000
+ func = f
+
+ # Test protection against size mismatches
+ A = rng.random((4, 5)).astype(dtype)
+ B = rng.random((4, 4)).astype(dtype)
+ alpha = dtype(1)
+ assert_raises(Exception, func, alpha, A, B)
+ assert_raises(Exception, func, alpha, A.T, B)
+
+ n = 8
+ m = 7
+ alpha = dtype(-2.5)
+ if dtype in COMPLEX_DTYPES:
+ A = (rng.random((m, m)) + rng.random((m, m))*1j) + eye(m)
+ else:
+ A = rng.random((m, m)) + eye(m)
+ A = A.astype(dtype)
+ Au = triu(A)
+ Al = tril(A)
+ B1 = rng.random((m, n)).astype(dtype)
+ B2 = rng.random((n, m)).astype(dtype)
+
+ x1 = func(alpha=alpha, a=A, b=B1)
+ assert_equal(B1.shape, x1.shape)
+ x2 = solve(Au, alpha*B1)
+ assert_allclose(x1, x2, atol=tol)
+
+ x1 = func(alpha=alpha, a=A, b=B1, trans_a=1)
+ x2 = solve(Au.T, alpha*B1)
+ assert_allclose(x1, x2, atol=tol)
+
+ x1 = func(alpha=alpha, a=A, b=B1, trans_a=2)
+ x2 = solve(Au.conj().T, alpha*B1)
+ assert_allclose(x1, x2, atol=tol)
+
+ x1 = func(alpha=alpha, a=A, b=B1, diag=1)
+ Au[arange(m), arange(m)] = dtype(1)
+ x2 = solve(Au, alpha*B1)
+ assert_allclose(x1, x2, atol=tol)
+
+ x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1)
+ x2 = solve(Au.conj().T, alpha*B2.conj().T)
+ assert_allclose(x1, x2.conj().T, atol=tol)
+
+ x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1)
+ Al[arange(m), arange(m)] = dtype(1)
+ x2 = solve(Al.conj().T, alpha*B2.conj().T)
+ assert_allclose(x1, x2.conj().T, atol=tol)
+
+
+@pytest.mark.xfail(run=False,
+ reason="gh-16930")
+def test_gh_169309():
+ x = np.repeat(10, 9)
+ actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1)
+ expected = math.sqrt(500)
+ assert_allclose(actual, expected)
+
+
+@pytest.mark.xfail(HAS_ILP64, reason='does not fail with ILP64 MKL')
+def test_dnrm2_neg_incx():
+ # check that dnrm2(..., incx < 0) raises
+ # XXX: remove the test after the lowest supported BLAS implements
+ # negative incx (new in LAPACK 3.10)
+ x = np.repeat(10, 9)
+ incx = -1
+ dnrm2 = scipy.linalg.blas.get_blas_funcs('nrm2', (x,), ilp64='preferred')
+ with assert_raises(FBLAS_ERROR):
+ dnrm2(x, 5, 3, incx)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_abi.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_abi.py
new file mode 100644
index 0000000000000000000000000000000000000000..e77c39d44c2be2d6bb99f62b41cb95dff100f702
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_abi.py
@@ -0,0 +1,120 @@
+# ---------------------------------------------------------------------------
+# AUTO-GENERATED - do not edit by hand.
+# Re-generate with: python tools/generate_cython_abi_tests.py linalg
+#
+# Generated against SciPy 1.17.1 on 2026-03-29
+# Python 3.12.13
+# ---------------------------------------------------------------------------
+
+"""
+Regression test for the cython_blas / cython_lapack binary interface.
+
+The __pyx_capi__ dict of each module contains PyCapsule objects whose
+*name* string encodes the C-level function signature that Cython checks
+at import time when another module does ``cimport``. Any change to
+those strings is a binary incompatibility that breaks every downstream
+package (e.g., scikit-learn, statsmodels) compiled against the previous release,
+without any compile-time warning.
+
+The expected signatures are stored in cython_abi_signatures.json.
+The test fails if:
+ * an existing name disappears, or
+ * an existing name's signature string changes.
+Adding new names is explicitly allowed (it is not a break).
+"""
+
+import ctypes
+import importlib
+import importlib.resources
+import json
+
+import pytest
+import scipy
+
+CYTHON_BLAS_ILP64 = (
+ scipy.show_config(mode='dicts')['Build Dependencies']['blas']['cython blas ilp64']
+)
+
+
+# ---------------------------------------------------------------------------
+# Helper
+# ---------------------------------------------------------------------------
+
+_get_capsule_name = ctypes.pythonapi.PyCapsule_GetName
+_get_capsule_name.restype = ctypes.c_char_p
+_get_capsule_name.argtypes = [ctypes.py_object]
+
+
+def _extract_capi(module):
+ """Return {name: signature} for every entry in module.__pyx_capi__."""
+ result = {}
+ for name, capsule in module.__pyx_capi__.items():
+ raw = _get_capsule_name(capsule)
+ if raw is not None:
+ result[name] = raw.decode('utf-8')
+ return result
+
+
+_sig_file = importlib.resources.files('scipy.linalg.tests').joinpath(
+ 'cython_abi_signatures.json'
+)
+with importlib.resources.as_file(_sig_file) as _f:
+ _EXPECTED = json.loads(_f.read_text())
+
+
+@pytest.mark.skipif(
+ CYTHON_BLAS_ILP64,
+ reason='cython_blas/cython_lapack ABI depends on ILP64 BLAS',
+)
+def test_cython_blas_abi_stability():
+ """No existing cython_blas signature may change or disappear."""
+ expected = _EXPECTED['scipy.linalg.cython_blas']
+ mod = importlib.import_module('scipy.linalg.cython_blas')
+ actual = _extract_capi(mod)
+ errors = []
+ for name, expected_sig in expected.items():
+ if name not in actual:
+ errors.append(
+ f"REMOVED {name!r} (was {expected_sig!r})"
+ )
+ elif actual[name] != expected_sig:
+ errors.append(
+ f"CHANGED {name!r}\n"
+ f" expected: {expected_sig!r}\n"
+ f" actual: {actual[name]!r}"
+ )
+ if errors:
+ joined = '\n'.join(errors)
+ pytest.fail(
+ f"scipy.linalg.cython_blas.__pyx_capi__ has {len(errors)} "
+ f"ABI breakage(s):\n{joined}"
+ )
+
+
+@pytest.mark.skipif(
+ CYTHON_BLAS_ILP64,
+ reason='cython_blas/cython_lapack ABI depends on ILP64 BLAS',
+)
+def test_cython_lapack_abi_stability():
+ """No existing cython_lapack signature may change or disappear."""
+ expected = _EXPECTED['scipy.linalg.cython_lapack']
+ mod = importlib.import_module('scipy.linalg.cython_lapack')
+ actual = _extract_capi(mod)
+ errors = []
+ for name, expected_sig in expected.items():
+ if name not in actual:
+ errors.append(
+ f"REMOVED {name!r} (was {expected_sig!r})"
+ )
+ elif actual[name] != expected_sig:
+ errors.append(
+ f"CHANGED {name!r}\n"
+ f" expected: {expected_sig!r}\n"
+ f" actual: {actual[name]!r}"
+ )
+ if errors:
+ joined = '\n'.join(errors)
+ pytest.fail(
+ f"scipy.linalg.cython_lapack.__pyx_capi__ has {len(errors)} "
+ f"ABI breakage(s):\n{joined}"
+ )
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_blas.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa99ffaa096d1c636ab2c7e045ffb8f2e38407d7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_blas.py
@@ -0,0 +1,147 @@
+import numpy as np
+from numpy.testing import (assert_allclose,
+ assert_equal)
+import scipy.linalg.cython_blas as blas
+
+
+class TestBlasInt:
+ """Tests for blas_int type used in cython_blas/cython_lapack."""
+
+ def test_blas_int_size(self):
+ """Verify blas_int size matches the build configuration."""
+ from scipy.__config__ import CONFIG
+ size = blas._blas_int_size()
+ cython_blas_ilp64 = CONFIG['Build Dependencies']['blas']['cython blas ilp64']
+ if cython_blas_ilp64:
+ assert size == 8, f"ILP64 build but blas_int is {size} bytes"
+ else:
+ assert size == 4, f"LP64 build but blas_int is {size} bytes"
+
+ # also verify blas_bint size
+ bint_sizes = blas._blas_bint_bint_sizes() # (sizeof(blas_bint), sizeof(bint))
+ if cython_blas_ilp64:
+ assert bint_sizes == (8, 4)
+ else:
+ assert bint_sizes == (4, 4)
+
+ def test_dgemm_with_blas_int_dimensions(self):
+ """Test dgemm works correctly - exercises blas_int for dimensions."""
+ a = np.eye(3, dtype=np.float64)
+ b = np.arange(9, dtype=np.float64).reshape((3, 3))
+ c = np.empty((3, 3), dtype=np.float64)
+ blas._test_dgemm(1., a, b, 0., c)
+ assert_allclose(c, b)
+
+
+class TestDGEMM:
+
+ def test_transposes(self):
+
+ a = np.arange(12, dtype=np.float64).reshape((3, 4))[:2,:2]
+ b = np.arange(1, 13, dtype=np.float64).reshape((4, 3))[:2,:2]
+ c = np.empty((2, 4), dtype=np.float64)[:2,:2]
+
+ blas._test_dgemm(1., a, b, 0., c)
+ assert_allclose(c, a.dot(b))
+
+ blas._test_dgemm(1., a.T, b, 0., c)
+ assert_allclose(c, a.T.dot(b))
+
+ blas._test_dgemm(1., a, b.T, 0., c)
+ assert_allclose(c, a.dot(b.T))
+
+ blas._test_dgemm(1., a.T, b.T, 0., c)
+ assert_allclose(c, a.T.dot(b.T))
+
+ blas._test_dgemm(1., a, b, 0., c.T)
+ assert_allclose(c, a.dot(b).T)
+
+ blas._test_dgemm(1., a.T, b, 0., c.T)
+ assert_allclose(c, a.T.dot(b).T)
+
+ blas._test_dgemm(1., a, b.T, 0., c.T)
+ assert_allclose(c, a.dot(b.T).T)
+
+ blas._test_dgemm(1., a.T, b.T, 0., c.T)
+ assert_allclose(c, a.T.dot(b.T).T)
+
+ def test_shapes(self):
+ a = np.arange(6, dtype=np.float64).reshape((3, 2))
+ b = np.arange(-6, 2, dtype=np.float64).reshape((2, 4))
+ c = np.empty((3, 4), dtype=np.float64)
+
+ blas._test_dgemm(1., a, b, 0., c)
+ assert_allclose(c, a.dot(b))
+
+ blas._test_dgemm(1., b.T, a.T, 0., c.T)
+ assert_allclose(c, b.T.dot(a.T).T)
+
+class TestWfuncPointers:
+ """ Test the function pointers that are expected to fail on
+ Mac OS X without the additional entry statement in their definitions
+ in fblas_l1.pyf.src. """
+
+ def test_complex_args(self):
+
+ cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64)
+ cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64)
+
+ assert_allclose(blas._test_cdotc(cx, cy),
+ -17.6468753815+21.3718757629j)
+ assert_allclose(blas._test_cdotu(cx, cy),
+ -6.11562538147+30.3156242371j)
+
+ assert_equal(blas._test_icamax(cx), 3)
+
+ assert_allclose(blas._test_scasum(cx), 18.625)
+ assert_allclose(blas._test_scnrm2(cx), 13.1796483994)
+
+ assert_allclose(blas._test_cdotc(cx[::2], cy[::2]),
+ -18.1000003815+21.2000007629j)
+ assert_allclose(blas._test_cdotu(cx[::2], cy[::2]),
+ -6.10000038147+30.7999992371j)
+ assert_allclose(blas._test_scasum(cx[::2]), 18.)
+ assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499)
+
+ def test_double_args(self):
+
+ x = np.array([5., -3, -.5], np.float64)
+ y = np.array([2, 1, .5], np.float64)
+
+ assert_allclose(blas._test_dasum(x), 8.5)
+ assert_allclose(blas._test_ddot(x, y), 6.75)
+ assert_allclose(blas._test_dnrm2(x), 5.85234975815)
+
+ assert_allclose(blas._test_dasum(x[::2]), 5.5)
+ assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75)
+ assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297)
+
+ assert_equal(blas._test_idamax(x), 1)
+
+ def test_float_args(self):
+
+ x = np.array([5., -3, -.5], np.float32)
+ y = np.array([2, 1, .5], np.float32)
+
+ assert_equal(blas._test_isamax(x), 1)
+
+ assert_allclose(blas._test_sasum(x), 8.5)
+ assert_allclose(blas._test_sdot(x, y), 6.75)
+ assert_allclose(blas._test_snrm2(x), 5.85234975815)
+
+ assert_allclose(blas._test_sasum(x[::2]), 5.5)
+ assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75)
+ assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297)
+
+ def test_double_complex_args(self):
+
+ cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128)
+ cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128)
+
+ assert_equal(blas._test_izamax(cx), 3)
+
+ assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j)
+ assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j)
+
+ assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j)
+ assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_lapack.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..01f15803a09e54ae46e6d13aa06437e364a0a810
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cython_lapack.py
@@ -0,0 +1,56 @@
+from numpy.testing import assert_allclose
+from scipy.linalg import cython_lapack as cython_lapack
+from scipy.linalg import lapack
+
+
+class TestLamch:
+
+ def test_slamch(self):
+ lapack_slamch = lapack.get_lapack_funcs(
+ 'lamch', dtype='float32', ilp64='preferred'
+ )
+ for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
+ assert_allclose(cython_lapack._test_slamch(c),
+ lapack_slamch(c))
+
+ def test_dlamch(self):
+ lapack_dlamch = lapack.get_lapack_funcs(
+ 'lamch', dtype='float64', ilp64='preferred'
+ )
+
+ for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
+ assert_allclose(cython_lapack._test_dlamch(c),
+ lapack_dlamch(c))
+
+ def test_complex_ladiv(self):
+ cx = .5 + 1.j
+ cy = .875 + 2.j
+ assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j)
+ assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j)
+
+
+class TestBlasInt:
+ """Test for blas_int/blas_bint types used in cython_blas/cython_lapack.
+
+ Note similar test is in test_blas.py: both cython_blas.pyx and cython_lapack.pyx
+ define the types, so we smoke test that `blas_int` and `blas_bint` types
+ can be cimported from both `cython_blas` and `cython_lapack` extensions.
+ """
+
+ def test_blas_int_size(self):
+ """Verify blas_int and blas_bint sizes matches the build configuration."""
+ from scipy.__config__ import CONFIG
+ size = cython_lapack._blas_int_size()
+ cython_blas_ilp64 = CONFIG['Build Dependencies']['blas']['cython blas ilp64']
+ if cython_blas_ilp64:
+ assert size == 8, f"ILP64 build but blas_int is {size} bytes"
+ else:
+ assert size == 4, f"LP64 build but blas_int is {size} bytes"
+
+ # also verify blas_bint size
+ # bint_sizes is a 2-tuple, (sizeof(blas_bint), sizeof(bint))
+ bint_sizes = cython_lapack._blas_bint_bint_sizes()
+ if cython_blas_ilp64:
+ assert bint_sizes == (8, 4)
+ else:
+ assert bint_sizes == (4, 4)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ab8f05f4401f055316a9ccd39848e2b3fc0e5a2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
@@ -0,0 +1,161 @@
+import numpy as np
+from scipy.linalg import bandwidth, issymmetric, ishermitian
+from scipy.conftest import skip_xp_invalid_arg
+import pytest
+from pytest import raises
+from numpy.testing import assert_equal
+
+BANDWIDTH_DTYPES = (
+ np.bool,
+ np.int8, np.int16, np.int32, np.int64,
+ np.uint8, np.uint16, np.uint32, np.uint64,
+ np.float32, np.float64,
+ np.complex64, np.complex128,
+)
+
+
+@skip_xp_invalid_arg
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+def test_bandwidth_dtypes():
+ n = 5
+ for dt in BANDWIDTH_DTYPES:
+ _ = bandwidth(np.zeros([n, n], dtype=dt))
+
+ unsupported_dtypes = [np.float16, np.longdouble, np.clongdouble,
+ np.bytes_, np.str_, np.void, np.object_,
+ np.datetime64, np.timedelta64]
+ for dt in unsupported_dtypes:
+ raises(TypeError, bandwidth, np.zeros([n, n], dtype=dt))
+
+
+@pytest.mark.parametrize('T', BANDWIDTH_DTYPES)
+def test_bandwidth_square_inputs(T):
+ n = 20
+ k = 4
+ R = np.zeros([n, n], dtype=T, order='F')
+ # form a banded matrix inplace
+ R[[x for x in range(n)], [x for x in range(n)]] = 1
+ R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
+ R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
+ R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
+ assert bandwidth(R) == (k, k)
+ A = np.array([
+ [1, 1, 0, 0, 0, 0, 0, 0],
+ [1, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ ])
+ assert bandwidth(A) == (2, 2)
+
+ A = np.array(
+ [
+ [[1, 0, 0], [0, 1, 0], [0, 0, 1]], # diagonal
+ [[0, 0, 1], [0, 0, 0], [0, 0, 0]], # upper triangular
+ [[0, 0, 0], [0, 0, 0], [1, 0, 0]], # lower triangular
+ [[0, 0, 1], [0, 0, 0], [1, 0, 0]], # full
+ [[0, 0, 1], [0, 0, 0], [0, 1, 0.]], # upper hessenberg
+ ]
+ )
+ lo, hi = bandwidth(A)
+ assert_equal(lo, [0, 0, 2, 2, 1])
+ assert_equal(hi, [0, 2, 0, 2, 2])
+
+
+@skip_xp_invalid_arg
+@pytest.mark.parametrize('T', BANDWIDTH_DTYPES)
+def test_bandwidth_rect_inputs(T):
+ n, m = 10, 20
+ k = 5
+ R = np.zeros([n, m], dtype=T, order='F')
+ # form a banded matrix inplace
+ R[[x for x in range(n)], [x for x in range(n)]] = 1
+ R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
+ R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
+ R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
+ assert bandwidth(R) == (k, k)
+
+ R2 = np.tril(np.ones((2, 10, 2), dtype=T))
+ lo, hi = bandwidth(R2)
+ assert_equal(lo, [9, 9])
+ assert_equal(hi, [0, 0])
+
+ R3 = np.triu(np.ones((2, 10, 2), dtype=T))
+ lo, hi = bandwidth(R3)
+ assert_equal(lo, [0, 0])
+ assert_equal(hi, [1, 1])
+
+
+@skip_xp_invalid_arg
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+def test_issymetric_ishermitian_dtypes():
+ n = 5
+ for t in np.typecodes['All']:
+ A = np.zeros([n, n], dtype=t)
+ if t in 'eUVOMm':
+ raises(TypeError, issymmetric, A)
+ raises(TypeError, ishermitian, A)
+ elif t == 'G': # No-op test. On win these pass on others fail.
+ pass
+ else:
+ assert issymmetric(A)
+ assert ishermitian(A)
+
+
+def test_issymmetric_ishermitian_invalid_input():
+ A = np.array([1, 2, 3])
+ raises(ValueError, issymmetric, A)
+ raises(ValueError, ishermitian, A)
+ A = np.array([[[1, 2, 3], [4, 5, 6]]])
+ raises(ValueError, issymmetric, A)
+ raises(ValueError, ishermitian, A)
+ A = np.array([[1, 2, 3], [4, 5, 6]])
+ raises(ValueError, issymmetric, A)
+ raises(ValueError, ishermitian, A)
+
+
+def test_issymetric_complex_decimals():
+ A = np.arange(1, 10).astype(complex).reshape(3, 3)
+ A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
+ # make entries decimal
+ A /= np.pi
+ A = A + A.T
+ assert issymmetric(A)
+
+
+def test_ishermitian_complex_decimals():
+ A = np.arange(1, 10).astype(complex).reshape(3, 3)
+ A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
+ # make entries decimal
+ A /= np.pi
+ A = A + A.T.conj()
+ assert ishermitian(A)
+
+
+def test_issymmetric_approximate_results():
+ n = 20
+ rng = np.random.RandomState(123456789)
+ x = rng.uniform(high=5., size=[n, n])
+ y = x @ x.T # symmetric
+ p = rng.standard_normal([n, n])
+ z = p @ y @ p.T
+ assert issymmetric(z, atol=1e-10)
+ assert issymmetric(z, atol=1e-10, rtol=0.)
+ assert issymmetric(z, atol=0., rtol=1e-12)
+ assert issymmetric(z, atol=1e-13, rtol=1e-12)
+
+
+def test_ishermitian_approximate_results():
+ n = 20
+ rng = np.random.RandomState(987654321)
+ x = rng.uniform(high=5., size=[n, n])
+ y = x @ x.T # symmetric
+ p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j
+ z = p @ y @ p.conj().T
+ assert ishermitian(z, atol=1e-10)
+ assert ishermitian(z, atol=1e-10, rtol=0.)
+ assert ishermitian(z, atol=0., rtol=1e-12)
+ assert ishermitian(z, atol=1e-13, rtol=1e-12)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..f950661aa39d48db15cb0772fdf93f0bb329cd9f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp.py
@@ -0,0 +1,3543 @@
+import itertools
+import platform
+import sys
+import warnings
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal,
+ assert_array_almost_equal, assert_array_equal,
+ assert_, assert_allclose)
+
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import (eig, eigvals, lu, svd, svdvals, cholesky, qr,
+ schur, rsf2csf, lu_solve, lu_factor, solve, diagsvd,
+ hessenberg, rq, eig_banded, eigvals_banded, eigh,
+ eigvalsh, qr_multiply, qz, orth, ordqz,
+ subspace_angles, hadamard, eigvalsh_tridiagonal,
+ eigh_tridiagonal, null_space, cdf2rdf, LinAlgError)
+
+from scipy.linalg.lapack import get_lapack_funcs
+from scipy.linalg._misc import norm
+from scipy.linalg._decomp_qz import _select_function
+from scipy.stats import ortho_group
+
+from numpy import (array, diag, full, linalg, argsort, zeros, arange,
+ float32, complex64, ravel, sqrt, iscomplex, shape, sort,
+ sign, asarray, isfinite, ndarray, eye,)
+
+from scipy.linalg._testutils import assert_no_overwrite
+from scipy.sparse._sputils import matrix
+
+from scipy._lib._testutils import check_free_memory
+from scipy.linalg.blas import HAS_ILP64
+from scipy.conftest import skip_xp_invalid_arg
+from scipy.__config__ import CONFIG
+
+from .test_basic import parametrize_overwrite_arg
+
+IS_WASM = (sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"])
+
+
+def _random_hermitian_matrix(n, posdef=False, dtype=float):
+ "Generate random sym/hermitian array of the given size n"
+ # FIXME non-deterministic rng
+ if dtype in COMPLEX_DTYPES:
+ A = np.random.rand(n, n) + np.random.rand(n, n)*1.0j
+ A = (A + A.conj().T)/2
+ else:
+ A = np.random.rand(n, n)
+ A = (A + A.T)/2
+
+ if posdef:
+ A += sqrt(2*n)*np.eye(n)
+
+ return A.astype(dtype)
+
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+# XXX: This function should not be defined here, but somewhere in
+# scipy.linalg namespace
+def symrand(dim_or_eigv, rng):
+ """Return a random symmetric (Hermitian) matrix.
+
+ If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues
+ uniformly distributed on (-1,1).
+
+ If 'dim_or_eigv' is 1-D real array 'a', return a matrix whose
+ eigenvalues are 'a'.
+ """
+ if isinstance(dim_or_eigv, int):
+ dim = dim_or_eigv
+ d = rng.random(dim)*2 - 1
+ elif (isinstance(dim_or_eigv, ndarray) and
+ len(dim_or_eigv.shape) == 1):
+ dim = dim_or_eigv.shape[0]
+ d = dim_or_eigv
+ else:
+ raise TypeError("input type not supported.")
+
+ v = ortho_group.rvs(dim)
+ h = v.T.conj() @ diag(d) @ v
+ # to avoid roundoff errors, symmetrize the matrix (again)
+ h = 0.5*(h.T+h)
+ return h
+
+
+class TestEigVals:
+
+ def test_simple(self):
+ a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+ w = eigvals(a)
+ exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+ assert_array_almost_equal(w, exact_w)
+
+ def test_simple_tr(self):
+ a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]], 'd').T
+ a = a.copy()
+ a = a.T
+ w = eigvals(a)
+ exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+ assert_array_almost_equal(w, exact_w)
+
+ def test_simple_complex(self):
+ a = [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]]
+ w = eigvals(a)
+ exact_w = [(9+1j+sqrt(92+6j))/2,
+ 0,
+ (9+1j-sqrt(92+6j))/2]
+ assert_array_almost_equal(w, exact_w)
+
+ def test_finite(self):
+ a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+ w = eigvals(a, check_finite=False)
+ exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+ assert_array_almost_equal(w, exact_w)
+
+ @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ w = eigvals(a)
+ assert w.shape == (0,)
+ assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype
+
+ w = eigvals(a, homogeneous_eigvals=True)
+ assert w.shape == (2, 0)
+ assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype
+
+
+class TestEig:
+
+ def test_simple(self):
+ a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+ w, v = eig(a)
+ exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+ v0 = array([1, 1, (1+sqrt(93)/3)/2])
+ v1 = array([3., 0, -1])
+ v2 = array([1, 1, (1-sqrt(93)/3)/2])
+ v0 = v0 / norm(v0)
+ v1 = v1 / norm(v1)
+ v2 = v2 / norm(v2)
+ assert_array_almost_equal(w, exact_w)
+ assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0]))
+ assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1]))
+ assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2]))
+ for i in range(3):
+ assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i])
+
+ w, v = eig(a, left=1, right=0)
+ for i in range(3):
+ assert_array_almost_equal(a.T @ v[:, i], w[i]*v[:, i])
+
+ def test_simple_dtype(self):
+ # Backwards compat: the input matrix is real, eigenvalues have zero
+ # imaginary part =>
+ # - eigenvectors are real,
+ # - *but* eigenvalues are still complex-valued!
+ # the `a` matrix is from test_simple
+ a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+ w, vl, vr = eig(a, left=True, right=True)
+ assert w.dtype == np.complex128
+ assert (w.imag == 0).all()
+ assert vl.dtype == np.float64
+ assert vr.dtype == np.float64
+
+ # repeat for a generalized eigenvalue problem
+ b = np.diag([3, 2, 1])
+ w, vl, vr = eig(a, b, left=True, right=True)
+ assert w.dtype == np.complex128
+ assert (w.imag == 0.).all()
+ assert vl.dtype == np.float64
+ assert vr.dtype == np.float64
+
+ def test_simple_complex_eig(self):
+ a = array([[1, 2], [-2, 1]])
+ w, vl, vr = eig(a, left=1, right=1)
+ assert_array_almost_equal(w, array([1+2j, 1-2j]))
+ for i in range(2):
+ assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i])
+ for i in range(2):
+ assert_array_almost_equal(a.conj().T @ vl[:, i],
+ w[i].conj()*vl[:, i])
+
+ def test_simple_complex_eig_dtype(self):
+ # Backwards compat: the matrix is real, the true eigenvalues are complex
+ # Thus, all of `w`, `vr` and `vl` arrays have a complex dtype
+ # The matrix `a` is from test_simple_complex_eig
+
+ a = np.asarray([[1, 2], [-2, 1]])
+ w, vl, vr = eig(a, left=True, right=True)
+ assert w.dtype == np.complex128
+ assert vl.dtype == np.complex128
+ assert vr.dtype == np.complex128
+
+
+ def test_simple_complex(self):
+ a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]])
+ w, vl, vr = eig(a, left=1, right=1)
+ for i in range(3):
+ assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i])
+ for i in range(3):
+ assert_array_almost_equal(a.conj().T @ vl[:, i],
+ w[i].conj()*vl[:, i])
+
+ def test_gh_3054(self):
+ a = [[1]]
+ b = [[0]]
+ w, vr = eig(a, b, homogeneous_eigvals=True)
+ assert_allclose(w[1, 0], 0)
+ assert_(w[0, 0] != 0)
+ assert_allclose(vr, 1)
+
+ w, vr = eig(a, b)
+ assert_equal(w, np.inf)
+ assert_allclose(vr, 1)
+
+ def _check_gen_eig(self, A, B, atol_homog=1e-13, rtol_homog=1e-13,
+ atol=1e-13, rtol=1e-13):
+ if B is not None:
+ A, B = asarray(A), asarray(B)
+ B0 = B
+ else:
+ A = asarray(A)
+ B0 = B
+ B = np.eye(*A.shape)
+ msg = f"\n{A!r}\n{B!r}"
+
+ # Eigenvalues in homogeneous coordinates
+ w, vr = eig(A, B0, homogeneous_eigvals=True)
+ wt = eigvals(A, B0, homogeneous_eigvals=True)
+ val1 = A @ vr * w[1, :]
+ val2 = B @ vr * w[0, :]
+ for i in range(val1.shape[1]):
+ assert_allclose(val1[:, i], val2[:, i],
+ rtol=rtol_homog, atol=atol_homog, err_msg=msg)
+
+ if B0 is None:
+ assert_allclose(w[1, :], 1)
+ assert_allclose(wt[1, :], 1)
+
+ perm = np.lexsort(w)
+ permt = np.lexsort(wt)
+ assert_allclose(w[:, perm], wt[:, permt], atol=1e-7, rtol=1e-7,
+ err_msg=msg)
+
+ length = np.empty(len(vr))
+
+ for i in range(len(vr)):
+ length[i] = norm(vr[:, i])
+
+ assert_allclose(length, np.ones(length.size), err_msg=msg,
+ atol=1e-7, rtol=1e-7)
+
+ # Convert homogeneous coordinates
+ beta_nonzero = (w[1, :] != 0)
+ wh = w[0, beta_nonzero] / w[1, beta_nonzero]
+
+ # Eigenvalues in standard coordinates
+ w, vr = eig(A, B0)
+ wt = eigvals(A, B0)
+ val1 = A @ vr
+ val2 = B @ vr * w
+ res = val1 - val2
+ for i in range(res.shape[1]):
+ if np.all(isfinite(res[:, i])):
+ assert_allclose(res[:, i], 0,
+ rtol=rtol, atol=atol, err_msg=msg)
+
+ # try to consistently order eigenvalues, including complex conjugate pairs
+ w_fin = w[isfinite(w)]
+ wt_fin = wt[isfinite(wt)]
+
+ # prune noise in the real parts
+ w_fin = -1j * np.real_if_close(1j*w_fin, tol=1e-10)
+ wt_fin = -1j * np.real_if_close(1j*wt_fin, tol=1e-10)
+
+ perm = argsort(abs(w_fin) + w_fin.imag)
+ permt = argsort(abs(wt_fin) + wt_fin.imag)
+
+ assert_allclose(w_fin[perm], wt_fin[permt],
+ atol=1e-7, rtol=1e-7, err_msg=msg)
+
+ length = np.empty(len(vr))
+ for i in range(len(vr)):
+ length[i] = norm(vr[:, i])
+ assert_allclose(length, np.ones(length.size), err_msg=msg)
+
+ # Compare homogeneous and nonhomogeneous versions
+ assert_allclose(sort(wh), sort(w[np.isfinite(w)]))
+
+ def test_singular(self):
+ # Example taken from
+ # https://web.archive.org/web/20040903121217/http://www.cs.umu.se/research/nla/singular_pairs/guptri/matlab.html
+ A = array([[22, 34, 31, 31, 17],
+ [45, 45, 42, 19, 29],
+ [39, 47, 49, 26, 34],
+ [27, 31, 26, 21, 15],
+ [38, 44, 44, 24, 30]])
+ B = array([[13, 26, 25, 17, 24],
+ [31, 46, 40, 26, 37],
+ [26, 40, 19, 25, 25],
+ [16, 25, 27, 14, 23],
+ [24, 35, 18, 21, 22]])
+
+ with np.errstate(all='ignore'):
+ self._check_gen_eig(A, B, atol_homog=5e-13, atol=5e-13)
+
+ def test_falker(self):
+ # Test matrices giving some Nan generalized eigenvalues.
+ M = diag(array([1, 0, 3]))
+ K = array(([2, -1, -1], [-1, 2, -1], [-1, -1, 2]))
+ D = array(([1, -1, 0], [-1, 1, 0], [0, 0, 0]))
+ Z = zeros((3, 3))
+ I3 = eye(3)
+ A = np.block([[I3, Z], [Z, -K]])
+ B = np.block([[Z, I3], [M, D]])
+
+ with np.errstate(all='ignore'):
+ self._check_gen_eig(A, B)
+
+ def test_bad_geneig(self):
+ # Ticket #709 (strange return values from DGGEV)
+
+ def matrices(omega):
+ c1 = -9 + omega**2
+ c2 = 2*omega
+ A = [[1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, c1, 0],
+ [0, 0, 0, c1]]
+ B = [[0, 0, 1, 0],
+ [0, 0, 0, 1],
+ [1, 0, 0, -c2],
+ [0, 1, c2, 0]]
+ return A, B
+
+ # With a buggy LAPACK, this can fail for different omega on different
+ # machines -- so we need to test several values
+ with np.errstate(all='ignore'):
+ for k in range(100):
+ A, B = matrices(omega=k*5./100)
+ self._check_gen_eig(A, B)
+
+ def test_make_eigvals(self):
+ # Step through all paths in _make_eigvals
+ # Real eigenvalues
+ rng = np.random.RandomState(1234)
+ A = symrand(3, rng)
+ self._check_gen_eig(A, None)
+ B = symrand(3, rng)
+ self._check_gen_eig(A, B)
+ # Complex eigenvalues
+ A = rng.random((3, 3)) + 1j*rng.random((3, 3))
+ self._check_gen_eig(A, None)
+ B = rng.random((3, 3)) + 1j*rng.random((3, 3))
+ self._check_gen_eig(A, B)
+
+ def test_check_finite(self):
+ a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+ w, v = eig(a, check_finite=False)
+ exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+ v0 = array([1, 1, (1+sqrt(93)/3)/2])
+ v1 = array([3., 0, -1])
+ v2 = array([1, 1, (1-sqrt(93)/3)/2])
+ v0 = v0 / norm(v0)
+ v1 = v1 / norm(v1)
+ v2 = v2 / norm(v2)
+ assert_array_almost_equal(w, exact_w)
+ assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0]))
+ assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1]))
+ assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2]))
+ for i in range(3):
+ assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i])
+
+ def test_not_square_error(self):
+ """Check that passing a non-square array raises a ValueError."""
+ A = np.arange(6).reshape(3, 2)
+ assert_raises(ValueError, eig, A)
+
+ def test_shape_mismatch(self):
+ """Check that passing arrays of with different shapes
+ raises a ValueError."""
+ A = eye(2)
+ B = np.arange(9.0).reshape(3, 3)
+ assert_raises(ValueError, eig, A, B)
+ assert_raises(ValueError, eig, B, A)
+
+ def test_gh_11577(self):
+ # https://github.com/scipy/scipy/issues/11577
+ # `A - lambda B` should have 4 and 8 among the eigenvalues, and this
+ # was apparently broken on some platforms
+ A = np.array([[12.0, 28.0, 76.0, 220.0],
+ [16.0, 32.0, 80.0, 224.0],
+ [24.0, 40.0, 88.0, 232.0],
+ [40.0, 56.0, 104.0, 248.0]], dtype='float64')
+ B = np.array([[2.0, 4.0, 10.0, 28.0],
+ [3.0, 5.0, 11.0, 29.0],
+ [5.0, 7.0, 13.0, 31.0],
+ [9.0, 11.0, 17.0, 35.0]], dtype='float64')
+
+ D, V = eig(A, B)
+
+ # The problem is ill-conditioned, and two other eigenvalues
+ # depend on ATLAS/OpenBLAS version, compiler version etc
+ # see gh-11577 for discussion
+ #
+ # NB: it is tempting to use `assert_allclose(D[:2], [4, 8])` instead but
+ # the ordering of eigenvalues also comes out different on different
+ # systems depending on who knows what.
+ with warnings.catch_warnings():
+ # isclose chokes on inf/nan values
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered in multiply", RuntimeWarning)
+ assert np.isclose(D, 4.0, atol=1e-14).any()
+ assert np.isclose(D, 8.0, atol=1e-14).any()
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ w, vr = eig(a)
+
+ w_n, vr_n = eig(np.eye(2, dtype=dt))
+
+ assert w.shape == (0,)
+ assert w.dtype == w_n.dtype #eigvals(np.eye(2, dtype=dt)).dtype
+
+ assert_allclose(vr, np.empty((0, 0)))
+ assert vr.shape == (0, 0)
+ assert vr.dtype == vr_n.dtype
+
+ w, vr = eig(a, homogeneous_eigvals=True)
+ assert w.shape == (2, 0)
+ assert w.dtype == w_n.dtype
+
+ assert vr.shape == (0, 0)
+ assert vr.dtype == vr_n.dtype
+
+ @pytest.mark.parametrize("include_B", [False, True])
+ @pytest.mark.parametrize("left", [False, True])
+ @pytest.mark.parametrize("right", [False, True])
+ @pytest.mark.parametrize("homogeneous_eigvals", [False, True])
+ @pytest.mark.parametrize("dtype", [np.float32, np.complex128])
+ def test_nd_input(self, include_B, left, right, homogeneous_eigvals, dtype):
+ batch_shape = (3, 2)
+ core_shape = (4, 4)
+ rng = np.random.default_rng(3249823598235)
+ A = rng.random(batch_shape + core_shape).astype(dtype)
+ B = rng.random(batch_shape + core_shape).astype(dtype)
+ kwargs = dict(right=right, homogeneous_eigvals=homogeneous_eigvals)
+
+ if include_B:
+ res = eig(A, b=B, left=left, **kwargs)
+ else:
+ res = eig(A, left=left, **kwargs)
+
+ for i in range(batch_shape[0]):
+ for j in range(batch_shape[1]):
+ if include_B:
+ ref = eig(A[i, j], b=B[i, j], left=left, **kwargs)
+ else:
+ ref = eig(A[i, j], left=left, **kwargs)
+
+ if left or right:
+ for k in range(len(ref)):
+ assert_allclose(res[k][i, j], ref[k])
+ else:
+ assert_allclose(res[i, j], ref)
+
+ @pytest.mark.parametrize("dtyp", [int, float, complex])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ @pytest.mark.parametrize("ndim", [2, 3])
+ @pytest.mark.parametrize("overwrite_a", [True, False])
+ def test_overwrite_reg(self, dtyp, order, ndim, overwrite_a):
+ n = 3
+ a = np.arange(n*n).reshape(n, n)
+ a = a.astype(dtype=dtyp, order=order)
+
+ if ndim == 3:
+ a = np.stack([a, 2*a])
+
+ a_ref = a.copy()
+
+ w, v = eig(a, overwrite_a=overwrite_a)
+
+ # see if the memory was reused
+ a_inplace = (
+ overwrite_a and
+ (a.dtype != int) and
+ (a.ndim == 2) and
+ a.flags['F_CONTIGUOUS']
+ )
+
+ assert (a == a_ref).all() != a_inplace
+
+ @pytest.mark.parametrize("dtyp_a", [int, float, complex])
+ @pytest.mark.parametrize("dtyp_b", [int, float, complex])
+ @pytest.mark.parametrize("order_a", ["C", "F"])
+ @pytest.mark.parametrize("order_b", ["C", "F"])
+ @pytest.mark.parametrize("ndim_a", [2, 3])
+ @pytest.mark.parametrize("ndim_b", [2, 3])
+ @pytest.mark.parametrize("overwrite_a", [True, False])
+ @pytest.mark.parametrize("overwrite_b", [True, False])
+ def test_overwrite_gen(
+ self, dtyp_a, dtyp_b, order_a, order_b, ndim_a, ndim_b, overwrite_a, overwrite_b
+ ):
+ n = 3
+ a = np.arange(n*n).reshape(n, n)
+ a = a.astype(dtype=dtyp_a, order=order_a)
+
+ b = np.arange(n*n).reshape(n, n)
+ b = b.astype(dtype=dtyp_b, order=order_b)
+
+ if ndim_a == 3:
+ a = np.stack([a, 2*a])
+ if ndim_b == 3:
+ b = np.stack([b, 2*b])
+
+ a_ref = a.copy()
+ b_ref = b.copy()
+
+ w, v = eig(a, b, overwrite_a=overwrite_a, overwrite_b=overwrite_b)
+
+ # see if the memory was reused
+ a_inplace = (
+ overwrite_a and
+ (a.dtype != int) and (a.dtype == np.result_type(a, b)) and
+ (a.ndim == 2) and (b.ndim == 2) and
+ a.flags['F_CONTIGUOUS']
+ )
+
+ b_inplace = (
+ overwrite_b and
+ (b.dtype != int) and (b.dtype == np.result_type(a, b)) and
+ (a.ndim == 2) and (b.ndim == 2) and
+ b.flags['F_CONTIGUOUS']
+ )
+
+ assert (a == a_ref).all() != a_inplace, 'A'
+ assert (b == b_ref).all() != b_inplace, 'B'
+
+
+class TestEigBanded:
+ def setup_method(self):
+ self.create_bandmat()
+
+ def create_bandmat(self):
+ """Create the full matrix `self.fullmat` and
+ the corresponding band matrix `self.bandmat`."""
+ N = 10
+ self.KL = 2 # number of subdiagonals (below the diagonal)
+ self.KU = 2 # number of superdiagonals (above the diagonal)
+
+ # symmetric band matrix
+ self.sym_mat = (diag(full(N, 1.0))
+ + diag(full(N-1, -1.0), -1) + diag(full(N-1, -1.0), 1)
+ + diag(full(N-2, -2.0), -2) + diag(full(N-2, -2.0), 2))
+
+ # hermitian band matrix
+ self.herm_mat = (diag(full(N, -1.0))
+ + 1j*diag(full(N-1, 1.0), -1)
+ - 1j*diag(full(N-1, 1.0), 1)
+ + diag(full(N-2, -2.0), -2)
+ + diag(full(N-2, -2.0), 2))
+
+ # general real band matrix
+ self.real_mat = (diag(full(N, 1.0))
+ + diag(full(N-1, -1.0), -1) + diag(full(N-1, -3.0), 1)
+ + diag(full(N-2, 2.0), -2) + diag(full(N-2, -2.0), 2))
+
+ # general complex band matrix
+ self.comp_mat = (1j*diag(full(N, 1.0))
+ + diag(full(N-1, -1.0), -1)
+ + 1j*diag(full(N-1, -3.0), 1)
+ + diag(full(N-2, 2.0), -2)
+ + diag(full(N-2, -2.0), 2))
+
+ # Eigenvalues and -vectors from linalg.eig
+ ew, ev = linalg.eig(self.sym_mat)
+ ew = ew.real
+ args = argsort(ew)
+ self.w_sym_lin = ew[args]
+ self.evec_sym_lin = ev[:, args]
+
+ ew, ev = linalg.eig(self.herm_mat)
+ ew = ew.real
+ args = argsort(ew)
+ self.w_herm_lin = ew[args]
+ self.evec_herm_lin = ev[:, args]
+
+ # Extract upper bands from symmetric and hermitian band matrices
+ # (for use in dsbevd, dsbevx, zhbevd, zhbevx
+ # and their single precision versions)
+ LDAB = self.KU + 1
+ self.bandmat_sym = zeros((LDAB, N), dtype=float)
+ self.bandmat_herm = zeros((LDAB, N), dtype=complex)
+ for i in range(LDAB):
+ self.bandmat_sym[LDAB-i-1, i:N] = diag(self.sym_mat, i)
+ self.bandmat_herm[LDAB-i-1, i:N] = diag(self.herm_mat, i)
+
+ # Extract bands from general real and complex band matrix
+ # (for use in dgbtrf, dgbtrs and their single precision versions)
+ LDAB = 2*self.KL + self.KU + 1
+ self.bandmat_real = zeros((LDAB, N), dtype=float)
+ self.bandmat_real[2*self.KL, :] = diag(self.real_mat) # diagonal
+ for i in range(self.KL):
+ # superdiagonals
+ self.bandmat_real[2*self.KL-1-i, i+1:N] = diag(self.real_mat, i+1)
+ # subdiagonals
+ self.bandmat_real[2*self.KL+1+i, 0:N-1-i] = diag(self.real_mat,
+ -i-1)
+
+ self.bandmat_comp = zeros((LDAB, N), dtype=complex)
+ self.bandmat_comp[2*self.KL, :] = diag(self.comp_mat) # diagonal
+ for i in range(self.KL):
+ # superdiagonals
+ self.bandmat_comp[2*self.KL-1-i, i+1:N] = diag(self.comp_mat, i+1)
+ # subdiagonals
+ self.bandmat_comp[2*self.KL+1+i, 0:N-1-i] = diag(self.comp_mat,
+ -i-1)
+
+ # absolute value for linear equation system A*x = b
+ self.b = 1.0*arange(N)
+ self.bc = self.b * (1 + 1j)
+
+ #####################################################################
+
+ def test_dsbev(self):
+ """Compare dsbev eigenvalues and eigenvectors with
+ the result of linalg.eig."""
+ dsbev = get_lapack_funcs('sbev', dtype=np.float64, ilp64="preferred")
+
+ w, evec, info = dsbev(self.bandmat_sym, compute_v=1)
+ evec_ = evec[:, argsort(w)]
+ assert_array_almost_equal(sort(w), self.w_sym_lin)
+ assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+ def test_dsbevd(self):
+ """Compare dsbevd eigenvalues and eigenvectors with
+ the result of linalg.eig."""
+ dsbevd = get_lapack_funcs('sbevd', dtype=np.float64, ilp64="preferred")
+
+ w, evec, info = dsbevd(self.bandmat_sym, compute_v=1)
+ evec_ = evec[:, argsort(w)]
+ assert_array_almost_equal(sort(w), self.w_sym_lin)
+ assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+ def test_dsbevx(self):
+ """Compare dsbevx eigenvalues and eigenvectors
+ with the result of linalg.eig."""
+ N, N = shape(self.sym_mat)
+ dsbevx = get_lapack_funcs('sbevx', dtype=np.float64, ilp64="preferred")
+
+ # Achtung: Argumente 0.0,0.0,range?
+ w, evec, num, ifail, info = dsbevx(self.bandmat_sym, 0.0, 0.0, 1, N,
+ compute_v=1, range=2)
+ evec_ = evec[:, argsort(w)]
+ assert_array_almost_equal(sort(w), self.w_sym_lin)
+ assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+ def test_zhbevd(self):
+ """Compare zhbevd eigenvalues and eigenvectors
+ with the result of linalg.eig."""
+ zhbevd = get_lapack_funcs('hbevd', dtype=np.complex128, ilp64="preferred")
+
+ w, evec, info = zhbevd(self.bandmat_herm, compute_v=1)
+ evec_ = evec[:, argsort(w)]
+ assert_array_almost_equal(sort(w), self.w_herm_lin)
+ assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin))
+
+ def test_zhbevx(self):
+ """Compare zhbevx eigenvalues and eigenvectors
+ with the result of linalg.eig."""
+ N, N = shape(self.herm_mat)
+ zhbevx = get_lapack_funcs('hbevx', dtype=np.complex128, ilp64="preferred")
+
+ # Achtung: Argumente 0.0,0.0,range?
+ w, evec, num, ifail, info = zhbevx(self.bandmat_herm, 0.0, 0.0, 1, N,
+ compute_v=1, range=2)
+ evec_ = evec[:, argsort(w)]
+ assert_array_almost_equal(sort(w), self.w_herm_lin)
+ assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin))
+
+ def test_eigvals_banded(self):
+ """Compare eigenvalues of eigvals_banded with those of linalg.eig."""
+ w_sym = eigvals_banded(self.bandmat_sym)
+ w_sym = w_sym.real
+ assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+
+ w_herm = eigvals_banded(self.bandmat_herm)
+ w_herm = w_herm.real
+ assert_array_almost_equal(sort(w_herm), self.w_herm_lin)
+
+ # extracting eigenvalues with respect to an index range
+ ind1 = 2
+ ind2 = np.longlong(6)
+ w_sym_ind = eigvals_banded(self.bandmat_sym,
+ select='i', select_range=(ind1, ind2))
+ assert_array_almost_equal(sort(w_sym_ind),
+ self.w_sym_lin[ind1:ind2+1])
+ w_herm_ind = eigvals_banded(self.bandmat_herm,
+ select='i', select_range=(ind1, ind2))
+ assert_array_almost_equal(sort(w_herm_ind),
+ self.w_herm_lin[ind1:ind2+1])
+
+ # extracting eigenvalues with respect to a value range
+ v_lower = self.w_sym_lin[ind1] - 1.0e-5
+ v_upper = self.w_sym_lin[ind2] + 1.0e-5
+ w_sym_val = eigvals_banded(self.bandmat_sym,
+ select='v', select_range=(v_lower, v_upper))
+ assert_array_almost_equal(sort(w_sym_val),
+ self.w_sym_lin[ind1:ind2+1])
+
+ v_lower = self.w_herm_lin[ind1] - 1.0e-5
+ v_upper = self.w_herm_lin[ind2] + 1.0e-5
+ w_herm_val = eigvals_banded(self.bandmat_herm,
+ select='v',
+ select_range=(v_lower, v_upper))
+ assert_array_almost_equal(sort(w_herm_val),
+ self.w_herm_lin[ind1:ind2+1])
+
+ w_sym = eigvals_banded(self.bandmat_sym, check_finite=False)
+ w_sym = w_sym.real
+ assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+
+ def test_eig_banded(self):
+ """Compare eigenvalues and eigenvectors of eig_banded
+ with those of linalg.eig. """
+ w_sym, evec_sym = eig_banded(self.bandmat_sym)
+ evec_sym_ = evec_sym[:, argsort(w_sym.real)]
+ assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+ assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin))
+
+ w_herm, evec_herm = eig_banded(self.bandmat_herm)
+ evec_herm_ = evec_herm[:, argsort(w_herm.real)]
+ assert_array_almost_equal(sort(w_herm), self.w_herm_lin)
+ assert_array_almost_equal(abs(evec_herm_), abs(self.evec_herm_lin))
+
+ # extracting eigenvalues with respect to an index range
+ ind1 = 2
+ ind2 = 6
+ w_sym_ind, evec_sym_ind = eig_banded(self.bandmat_sym,
+ select='i',
+ select_range=(ind1, ind2))
+ assert_array_almost_equal(sort(w_sym_ind),
+ self.w_sym_lin[ind1:ind2+1])
+ assert_array_almost_equal(abs(evec_sym_ind),
+ abs(self.evec_sym_lin[:, ind1:ind2+1]))
+
+ w_herm_ind, evec_herm_ind = eig_banded(self.bandmat_herm,
+ select='i',
+ select_range=(ind1, ind2))
+ assert_array_almost_equal(sort(w_herm_ind),
+ self.w_herm_lin[ind1:ind2+1])
+ assert_array_almost_equal(abs(evec_herm_ind),
+ abs(self.evec_herm_lin[:, ind1:ind2+1]))
+
+ # extracting eigenvalues with respect to a value range
+ v_lower = self.w_sym_lin[ind1] - 1.0e-5
+ v_upper = self.w_sym_lin[ind2] + 1.0e-5
+ w_sym_val, evec_sym_val = eig_banded(self.bandmat_sym,
+ select='v',
+ select_range=(v_lower, v_upper))
+ assert_array_almost_equal(sort(w_sym_val),
+ self.w_sym_lin[ind1:ind2+1])
+ assert_array_almost_equal(abs(evec_sym_val),
+ abs(self.evec_sym_lin[:, ind1:ind2+1]))
+
+ v_lower = self.w_herm_lin[ind1] - 1.0e-5
+ v_upper = self.w_herm_lin[ind2] + 1.0e-5
+ w_herm_val, evec_herm_val = eig_banded(self.bandmat_herm,
+ select='v',
+ select_range=(v_lower, v_upper))
+ assert_array_almost_equal(sort(w_herm_val),
+ self.w_herm_lin[ind1:ind2+1])
+ assert_array_almost_equal(abs(evec_herm_val),
+ abs(self.evec_herm_lin[:, ind1:ind2+1]))
+
+ w_sym, evec_sym = eig_banded(self.bandmat_sym, check_finite=False)
+ evec_sym_ = evec_sym[:, argsort(w_sym.real)]
+ assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+ assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin))
+
+ def test_dgbtrf(self):
+ """Compare dgbtrf LU factorisation with the LU factorisation result
+ of linalg.lu."""
+ dgbtrf = get_lapack_funcs('gbtrf', dtype=np.float64, ilp64="preferred")
+
+ M, N = shape(self.real_mat)
+ lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU)
+
+ # extract matrix u from lu_symm_band
+ u = diag(lu_symm_band[2*self.KL, :])
+ for i in range(self.KL + self.KU):
+ u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1)
+
+ p_lin, l_lin, u_lin = lu(self.real_mat, permute_l=0)
+ assert_array_almost_equal(u, u_lin)
+
+ def test_zgbtrf(self):
+ """Compare zgbtrf LU factorisation with the LU factorisation result
+ of linalg.lu."""
+ M, N = shape(self.comp_mat)
+ zgbtrf = get_lapack_funcs('gbtrf', dtype=np.complex128, ilp64="preferred")
+
+ lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU)
+
+ # extract matrix u from lu_symm_band
+ u = diag(lu_symm_band[2*self.KL, :])
+ for i in range(self.KL + self.KU):
+ u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1)
+
+ p_lin, l_lin, u_lin = lu(self.comp_mat, permute_l=0)
+ assert_array_almost_equal(u, u_lin)
+
+ def test_dgbtrs(self):
+ """Compare dgbtrs solutions for linear equation system A*x = b
+ with solutions of linalg.solve."""
+ dgbtrf, dgbtrs = get_lapack_funcs(
+ ('gbtrf', 'gbtrs'), dtype=np.float64, ilp64="preferred"
+ )
+
+ lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU)
+ y, info = dgbtrs(lu_symm_band, self.KL, self.KU, self.b, ipiv)
+
+ y_lin = linalg.solve(self.real_mat, self.b)
+ assert_array_almost_equal(y, y_lin)
+
+ def test_zgbtrs(self):
+ """Compare zgbtrs solutions for linear equation system A*x = b
+ with solutions of linalg.solve."""
+ zgbtrf, zgbtrs = get_lapack_funcs(
+ ('gbtrf', 'gbtrs'), dtype=np.complex128, ilp64="preferred"
+ )
+
+ lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU)
+ y, info = zgbtrs(lu_symm_band, self.KL, self.KU, self.bc, ipiv)
+
+ y_lin = linalg.solve(self.comp_mat, self.bc)
+ assert_array_almost_equal(y, y_lin)
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a_band = np.empty((0, 0), dtype=dt)
+ w, v = eig_banded(a_band)
+
+ w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=dt))
+
+ assert w.shape == (0,)
+ assert w.dtype == w_n.dtype
+
+ assert v.shape == (0, 0)
+ assert v.dtype == v_n.dtype
+
+ w = eig_banded(a_band, eigvals_only=True)
+ assert w.shape == (0,)
+ assert w.dtype == w_n.dtype
+
+class TestEigTridiagonal:
+ def setup_method(self):
+ self.create_trimat()
+
+ def create_trimat(self):
+ """Create the full matrix `self.fullmat`, `self.d`, and `self.e`."""
+ N = 10
+
+ # symmetric band matrix
+ self.d = full(N, 1.0)
+ self.e = full(N-1, -1.0)
+ self.full_mat = (diag(self.d) + diag(self.e, -1) + diag(self.e, 1))
+
+ ew, ev = linalg.eig(self.full_mat)
+ ew = ew.real
+ args = argsort(ew)
+ self.w = ew[args]
+ self.evec = ev[:, args]
+
+ def test_degenerate(self):
+ """Test error conditions."""
+ # Wrong sizes
+ assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e[:-1])
+ # Must be real
+ assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e * 1j)
+ # Bad driver
+ assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e,
+ lapack_driver=1.)
+ assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+ lapack_driver='foo')
+ # Bad bounds
+ assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+ select='i', select_range=(0, -1))
+
+ def test_eigvalsh_tridiagonal(self):
+ """Compare eigenvalues of eigvalsh_tridiagonal with those of eig."""
+ # can't use ?STERF with subselection
+ for driver in ('sterf', 'stev', 'stevd', 'stebz', 'stemr', 'auto'):
+ w = eigvalsh_tridiagonal(self.d, self.e, lapack_driver=driver)
+ assert_array_almost_equal(sort(w), self.w)
+
+ for driver in ('sterf', 'stev', 'stevd'):
+ assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+ lapack_driver=driver, select='i',
+ select_range=(0, 1))
+ for driver in ('stebz', 'stemr', 'auto'):
+ # extracting eigenvalues with respect to the full index range
+ w_ind = eigvalsh_tridiagonal(
+ self.d, self.e, select='i', select_range=(0, len(self.d)-1),
+ lapack_driver=driver)
+ assert_array_almost_equal(sort(w_ind), self.w)
+
+ # extracting eigenvalues with respect to an index range
+ ind1 = 2
+ ind2 = 6
+ w_ind = eigvalsh_tridiagonal(
+ self.d, self.e, select='i', select_range=(ind1, ind2),
+ lapack_driver=driver)
+ assert_array_almost_equal(sort(w_ind), self.w[ind1:ind2+1])
+
+ # extracting eigenvalues with respect to a value range
+ v_lower = self.w[ind1] - 1.0e-5
+ v_upper = self.w[ind2] + 1.0e-5
+ w_val = eigvalsh_tridiagonal(
+ self.d, self.e, select='v', select_range=(v_lower, v_upper),
+ lapack_driver=driver)
+ assert_array_almost_equal(sort(w_val), self.w[ind1:ind2+1])
+
+ def test_eigh_tridiagonal(self):
+ """Compare eigenvalues and eigenvectors of eigh_tridiagonal
+ with those of eig. """
+ # can't use ?STERF when eigenvectors are requested
+ assert_raises(ValueError, eigh_tridiagonal, self.d, self.e,
+ lapack_driver='sterf')
+ for driver in ('stebz', 'stev', 'stevd', 'stemr', 'auto'):
+ w, evec = eigh_tridiagonal(self.d, self.e, lapack_driver=driver)
+ evec_ = evec[:, argsort(w)]
+ assert_array_almost_equal(sort(w), self.w)
+ assert_array_almost_equal(abs(evec_), abs(self.evec))
+
+ assert_raises(ValueError, eigh_tridiagonal, self.d, self.e,
+ lapack_driver='stev', select='i', select_range=(0, 1))
+ for driver in ('stebz', 'stemr', 'auto'):
+ # extracting eigenvalues with respect to an index range
+ ind1 = 0
+ ind2 = len(self.d)-1
+ w, evec = eigh_tridiagonal(
+ self.d, self.e, select='i', select_range=(ind1, ind2),
+ lapack_driver=driver)
+ assert_array_almost_equal(sort(w), self.w)
+ assert_array_almost_equal(abs(evec), abs(self.evec))
+ ind1 = 2
+ ind2 = 6
+ w, evec = eigh_tridiagonal(
+ self.d, self.e, select='i', select_range=(ind1, ind2),
+ lapack_driver=driver)
+ assert_array_almost_equal(sort(w), self.w[ind1:ind2+1])
+ assert_array_almost_equal(abs(evec),
+ abs(self.evec[:, ind1:ind2+1]))
+
+ # extracting eigenvalues with respect to a value range
+ v_lower = self.w[ind1] - 1.0e-5
+ v_upper = self.w[ind2] + 1.0e-5
+ w, evec = eigh_tridiagonal(
+ self.d, self.e, select='v', select_range=(v_lower, v_upper),
+ lapack_driver=driver)
+ assert_array_almost_equal(sort(w), self.w[ind1:ind2+1])
+ assert_array_almost_equal(abs(evec),
+ abs(self.evec[:, ind1:ind2+1]))
+
+ def test_eigh_tridiagonal_1x1(self):
+ """See gh-20075"""
+ a = np.array([-2.0])
+ b = np.array([])
+ x = eigh_tridiagonal(a, b, eigvals_only=True)
+ assert x.ndim == 1
+ assert_allclose(x, a)
+ x, V = eigh_tridiagonal(a, b, select="i", select_range=(0, 0))
+ assert x.ndim == 1
+ assert V.ndim == 2
+ assert_allclose(x, a)
+ assert_allclose(V, array([[1.]]))
+
+ x, V = eigh_tridiagonal(a, b, select="v", select_range=(-2, 0))
+ assert x.size == 0
+ assert x.shape == (0,)
+ assert V.shape == (1, 0)
+
+
+class TestEigh:
+ def test_wrong_inputs(self):
+ # Nonsquare a
+ assert_raises(ValueError, eigh, np.ones([1, 2]))
+ # Nonsquare b
+ assert_raises(ValueError, eigh, np.ones([2, 2]), np.ones([2, 1]))
+ # Incompatible a, b sizes
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([2, 2]))
+ # Wrong type parameter for generalized problem
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ type=4)
+ # Both value and index subsets requested
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ subset_by_value=[1, 2], subset_by_index=[2, 4])
+ # Invalid upper index spec
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ subset_by_index=[0, 4])
+ # Invalid lower index
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ subset_by_index=[-2, 2])
+ # Invalid index spec #2
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ subset_by_index=[2, 0])
+ # Invalid value spec
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ subset_by_value=[2, 0])
+ # Invalid driver name
+ assert_raises(ValueError, eigh, np.ones([2, 2]), driver='wrong')
+ # Generalized driver selection without b
+ assert_raises(ValueError, eigh, np.ones([3, 3]), None, driver='gvx')
+ # Standard driver with b
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ driver='evr')
+ # Subset request from invalid driver
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ driver='gvd', subset_by_index=[1, 2])
+ assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+ driver='gvd', subset_by_index=[1, 2])
+
+ def test_nonpositive_b(self):
+ assert_raises(LinAlgError, eigh, np.ones([3, 3]), np.ones([3, 3]))
+
+ # index based subsets are done in the legacy test_eigh()
+ def test_value_subsets(self):
+ for ind, dt in enumerate(DTYPES):
+
+ a = _random_hermitian_matrix(20, dtype=dt)
+ w, v = eigh(a, subset_by_value=[-2, 2])
+ assert_equal(v.shape[1], len(w))
+ assert all((w > -2) & (w < 2))
+
+ b = _random_hermitian_matrix(20, posdef=True, dtype=dt)
+ w, v = eigh(a, b, subset_by_value=[-2, 2])
+ assert_equal(v.shape[1], len(w))
+ assert all((w > -2) & (w < 2))
+
+ def test_eigh_integer(self):
+ a = array([[1, 2], [2, 7]])
+ b = array([[3, 1], [1, 5]])
+ w, z = eigh(a)
+ w, z = eigh(a, b)
+
+ @skip_xp_invalid_arg
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_eigh_of_sparse(self):
+ # This tests the rejection of inputs that eigh cannot currently handle.
+ import scipy.sparse
+ a = scipy.sparse.eye_array(2).tocsc()
+ b = np.atleast_2d(a)
+ assert_raises(ValueError, eigh, a)
+ assert_raises(ValueError, eigh, b)
+
+ @pytest.mark.parametrize('dtype_', DTYPES)
+ @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx"))
+ def test_various_drivers_standard(self, driver, dtype_):
+ a = _random_hermitian_matrix(n=20, dtype=dtype_)
+ w, v = eigh(a, driver=driver)
+ assert_allclose(a @ v - (v * w), 0.,
+ atol=1000*np.finfo(dtype_).eps,
+ rtol=0.)
+
+ @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx"))
+ def test_1x1_lwork(self, driver):
+ w, v = eigh([[1]], driver=driver)
+ assert_allclose(w, array([1.]), atol=1e-15)
+ assert_allclose(v, array([[1.]]), atol=1e-15)
+
+ # complex case now
+ w, v = eigh([[1j]], driver=driver)
+ assert_allclose(w, array([0]), atol=1e-15)
+ assert_allclose(v, array([[1.]]), atol=1e-15)
+
+ @pytest.mark.parametrize('type', (1, 2, 3))
+ @pytest.mark.parametrize('driver', ("gv", "gvd", "gvx"))
+ def test_various_drivers_generalized(self, driver, type):
+ atol = np.spacing(5000.)
+ a = _random_hermitian_matrix(20)
+ b = _random_hermitian_matrix(20, posdef=True)
+ w, v = eigh(a=a, b=b, driver=driver, type=type)
+ if type == 1:
+ assert_allclose(a @ v - w*(b @ v), 0., atol=atol, rtol=0.)
+ elif type == 2:
+ assert_allclose(a @ b @ v - v * w, 0., atol=atol, rtol=0.)
+ else:
+ assert_allclose(b @ a @ v - v * w, 0., atol=atol, rtol=0.)
+
+ def test_eigvalsh_new_args(self):
+ a = _random_hermitian_matrix(5)
+ w = eigvalsh(a, subset_by_index=[1, 2])
+ assert_equal(len(w), 2)
+
+ w2 = eigvalsh(a, subset_by_index=[1, 2])
+ assert_equal(len(w2), 2)
+ assert_allclose(w, w2)
+
+ b = np.diag([1, 1.2, 1.3, 1.5, 2])
+ w3 = eigvalsh(b, subset_by_value=[1, 1.4])
+ assert_equal(len(w3), 2)
+ assert_allclose(w3, np.array([1.2, 1.3]))
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ w, v = eigh(a)
+
+ w_n, v_n = eigh(np.eye(2, dtype=dt))
+
+ assert w.shape == (0,)
+ assert w.dtype == w_n.dtype
+
+ assert v.shape == (0, 0)
+ assert v.dtype == v_n.dtype
+
+ w = eigh(a, eigvals_only=True)
+ assert_allclose(w, np.empty((0,)))
+
+ assert w.shape == (0,)
+ assert w.dtype == w_n.dtype
+
+class TestSVD_GESDD:
+ lapack_driver = 'gesdd'
+
+ def test_degenerate(self):
+ assert_raises(TypeError, svd, [[1.]], lapack_driver=1.)
+ assert_raises(ValueError, svd, [[1.]], lapack_driver='foo')
+
+ def test_simple(self):
+ a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]]
+ for full_matrices in (True, False):
+ u, s, vh = svd(a, full_matrices=full_matrices,
+ lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.T @ u, eye(3))
+ assert_array_almost_equal(vh.T @ vh, eye(3))
+ sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_simple_singular(self):
+ a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+ for full_matrices in (True, False):
+ u, s, vh = svd(a, full_matrices=full_matrices,
+ lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.T @ u, eye(3))
+ assert_array_almost_equal(vh.T @ vh, eye(3))
+ sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_simple_underdet(self):
+ a = [[1, 2, 3], [4, 5, 6]]
+ for full_matrices in (True, False):
+ u, s, vh = svd(a, full_matrices=full_matrices,
+ lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.T @ u, eye(u.shape[0]))
+ sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_simple_overdet(self):
+ a = [[1, 2], [4, 5], [3, 4]]
+ for full_matrices in (True, False):
+ u, s, vh = svd(a, full_matrices=full_matrices,
+ lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.T @ u, eye(u.shape[1]))
+ assert_array_almost_equal(vh.T @ vh, eye(2))
+ sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_random(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ m = 15
+ for i in range(3):
+ for a in [rng.random([n, m]), rng.random([m, n])]:
+ for full_matrices in (True, False):
+ u, s, vh = svd(a, full_matrices=full_matrices,
+ lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.T @ u, eye(u.shape[1]))
+ assert_array_almost_equal(vh @ vh.T, eye(vh.shape[0]))
+ sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_simple_complex(self):
+ a = [[1, 2, 3], [1, 2j, 3], [2, 5, 6]]
+ for full_matrices in (True, False):
+ u, s, vh = svd(a, full_matrices=full_matrices,
+ lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.conj().T @ u, eye(u.shape[1]))
+ assert_array_almost_equal(vh.conj().T @ vh, eye(vh.shape[0]))
+ sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_random_complex(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ m = 15
+ for i in range(3):
+ for full_matrices in (True, False):
+ for a in [rng.random([n, m]), rng.random([m, n])]:
+ a = a + 1j*rng.random(list(a.shape))
+ u, s, vh = svd(a, full_matrices=full_matrices,
+ lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.conj().T @ u,
+ eye(u.shape[1]))
+ # This fails when [m,n]
+ # assert_array_almost_equal(vh.conj().T @ vh,
+ # eye(len(vh),dtype=vh.dtype.char))
+ sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_crash_1580(self):
+ rng = np.random.RandomState(1234)
+ sizes = [(13, 23), (30, 50), (60, 100)]
+ for sz in sizes:
+ for dt in [np.float32, np.float64, np.complex64, np.complex128]:
+ a = rng.rand(*sz).astype(dt)
+ # should not crash
+ svd(a, lapack_driver=self.lapack_driver)
+
+ def test_check_finite(self):
+ a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]]
+ u, s, vh = svd(a, check_finite=False, lapack_driver=self.lapack_driver)
+ assert_array_almost_equal(u.T @ u, eye(3))
+ assert_array_almost_equal(vh.T @ vh, eye(3))
+ sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+ for i in range(len(s)):
+ sigma[i, i] = s[i]
+ assert_array_almost_equal(u @ sigma @ vh, a)
+
+ def test_gh_5039(self):
+ # This is a smoke test for https://github.com/scipy/scipy/issues/5039
+ #
+ # The following is reported to raise "ValueError: On entry to DGESDD
+ # parameter number 12 had an illegal value".
+ # `interp1d([1,2,3,4], [1,2,3,4], kind='cubic')`
+ # This is reported to only show up on LAPACK 3.0.3.
+ #
+ # The matrix below is taken from the call to
+ # `B = _fitpack._bsplmat(order, xk)` in interpolate._find_smoothest
+ b = np.array(
+ [[0.16666667, 0.66666667, 0.16666667, 0., 0., 0.],
+ [0., 0.16666667, 0.66666667, 0.16666667, 0., 0.],
+ [0., 0., 0.16666667, 0.66666667, 0.16666667, 0.],
+ [0., 0., 0., 0.16666667, 0.66666667, 0.16666667]])
+ svd(b, lapack_driver=self.lapack_driver)
+
+ @pytest.mark.skipif(not HAS_ILP64, reason="64-bit LAPACK required")
+ @pytest.mark.slow
+ def test_large_matrix(self):
+ check_free_memory(free_mb=17000)
+ A = np.zeros([1, 2**31], dtype=np.float32)
+ A[0, -1] = 1
+ u, s, vh = svd(A, full_matrices=False)
+ assert_allclose(s[0], 1.0)
+ assert_allclose(u[0, 0] * vh[0, -1], 1.0)
+
+ @pytest.mark.parametrize("m", [0, 1, 2])
+ @pytest.mark.parametrize("n", [0, 1, 2])
+ @pytest.mark.parametrize('dtype', DTYPES)
+ def test_shape_dtype(self, m, n, dtype):
+ a = np.zeros((m, n), dtype=dtype)
+ k = min(m, n)
+ dchar = a.dtype.char
+ real_dchar = dchar.lower() if dchar in 'FD' else dchar
+
+ u, s, v = svd(a)
+ assert_equal(u.shape, (m, m))
+ assert_equal(u.dtype, dtype)
+ assert_equal(s.shape, (k,))
+ assert_equal(s.dtype, np.dtype(real_dchar))
+ assert_equal(v.shape, (n, n))
+ assert_equal(v.dtype, dtype)
+
+ u, s, v = svd(a, full_matrices=False)
+ assert_equal(u.shape, (m, k))
+ assert_equal(u.dtype, dtype)
+ assert_equal(s.shape, (k,))
+ assert_equal(s.dtype, np.dtype(real_dchar))
+ assert_equal(v.shape, (k, n))
+ assert_equal(v.dtype, dtype)
+
+ s = svd(a, compute_uv=False)
+ assert_equal(s.shape, (k,))
+ assert_equal(s.dtype, np.dtype(real_dchar))
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+ def test_empty(self, dt, m, n):
+ a0 = np.eye(3, dtype=dt)
+ u0, s0, v0 = svd(a0)
+
+ a = np.empty((m, n), dtype=dt)
+ u, s, v = svd(a)
+ assert_allclose(u, np.identity(m))
+ assert_allclose(s, np.empty((0,)))
+ assert_allclose(v, np.identity(n))
+
+ assert u.dtype == u0.dtype
+ assert v.dtype == v0.dtype
+ assert s.dtype == s0.dtype
+
+ u, s, v = svd(a, full_matrices=False)
+ assert_allclose(u, np.empty((m, 0)))
+ assert_allclose(s, np.empty((0,)))
+ assert_allclose(v, np.empty((0, n)))
+
+ assert u.dtype == u0.dtype
+ assert v.dtype == v0.dtype
+ assert s.dtype == s0.dtype
+
+ s = svd(a, compute_uv=False)
+ assert_allclose(s, np.empty((0,)))
+
+ assert s.dtype == s0.dtype
+
+ @pytest.mark.parametrize("dtyp", [int, float, complex])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ @pytest.mark.parametrize("ndim", [2, 3])
+ @pytest.mark.parametrize("overwrite_a", [True, False])
+ @pytest.mark.parametrize("full_matrices", [True, False])
+ @pytest.mark.parametrize("mn", [(3, 5), (5, 3)])
+ def test_overwrite(self, dtyp, order, ndim, overwrite_a, full_matrices, mn):
+ m, n = mn
+ a = np.arange(m*n).reshape(m, n)
+ a = a.astype(dtype=dtyp, order=order)
+
+ if ndim == 3:
+ a = np.stack([a, 2*a])
+
+ a_ref = a.copy()
+
+ u, s, vh = svd(
+ a,
+ lapack_driver=self.lapack_driver,
+ full_matrices=full_matrices,
+ overwrite_a=overwrite_a,
+ compute_uv=True
+ )
+
+ # check that the result is correct
+ if full_matrices:
+ diag_s = diagsvd(s, m, n)
+ else:
+ if ndim == 2:
+ diag_s = np.diag(s)
+ else:
+ diag_s = np.stack([np.diag(x) for x in s])
+
+ assert_allclose(u @ diag_s @ vh, a_ref, atol=1e-12)
+
+ # see if the memory was reused
+ a_inplace = (
+ overwrite_a and
+ (a.dtype != int) and
+ (a.ndim == 2) and
+ a.flags['F_CONTIGUOUS']
+ )
+
+ assert (a == a_ref).all() != a_inplace
+
+
+class TestSVD_GESVD(TestSVD_GESDD):
+ lapack_driver = 'gesvd'
+
+
+# Allocating an array of such a size leads to _ArrayMemoryError(s)
+# since the maximum memory that can be in 32-bit (WASM) is 4GB
+@pytest.mark.skipif(IS_WASM, reason="out of memory in WASM")
+@pytest.mark.xfail_on_32bit("out of memory in 32-bit CI workflow")
+@pytest.mark.parallel_threads_limit(2) # 1.9 GiB per thread RAM usage
+@pytest.mark.fail_slow(10)
+@pytest.mark.skipif(HAS_ILP64, reason="does not fail; is too slow")
+def test_svd_gesdd_nosegfault():
+ # svd(a) with {U,VT}.size > INT_MAX does not segfault
+ # cf https://github.com/scipy/scipy/issues/14001
+ check_free_memory(free_mb=19_000)
+ df=np.ones((4799, 53130), dtype=np.float64)
+ with assert_raises(ValueError):
+ svd(df)
+
+
+def test_gesdd_nan_error_message():
+ A = np.eye(2)
+ A[0, 0] = np.nan
+ with pytest.raises(ValueError, match="NaN"):
+ svd(A, check_finite=False)
+
+
+class TestSVDVals:
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ for a in [[]], np.empty((2, 0)), np.ones((0, 3)):
+ a = np.array(a, dtype=dt)
+ s = svdvals(a)
+ assert_equal(s, np.empty(0))
+
+ s0 = svdvals(np.eye(2, dtype=dt))
+ assert s.dtype == s0.dtype
+
+ def test_simple(self):
+ a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+ s = svdvals(a)
+ assert_(len(s) == 3)
+ assert_(s[0] >= s[1] >= s[2])
+
+ def test_simple_underdet(self):
+ a = [[1, 2, 3], [4, 5, 6]]
+ s = svdvals(a)
+ assert_(len(s) == 2)
+ assert_(s[0] >= s[1])
+
+ def test_simple_overdet(self):
+ a = [[1, 2], [4, 5], [3, 4]]
+ s = svdvals(a)
+ assert_(len(s) == 2)
+ assert_(s[0] >= s[1])
+
+ def test_simple_complex(self):
+ a = [[1, 2, 3], [1, 20, 3j], [2, 5, 6]]
+ s = svdvals(a)
+ assert_(len(s) == 3)
+ assert_(s[0] >= s[1] >= s[2])
+
+ def test_simple_underdet_complex(self):
+ a = [[1, 2, 3], [4, 5j, 6]]
+ s = svdvals(a)
+ assert_(len(s) == 2)
+ assert_(s[0] >= s[1])
+
+ def test_simple_overdet_complex(self):
+ a = [[1, 2], [4, 5], [3j, 4]]
+ s = svdvals(a)
+ assert_(len(s) == 2)
+ assert_(s[0] >= s[1])
+
+ def test_check_finite(self):
+ a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+ s = svdvals(a, check_finite=False)
+ assert_(len(s) == 3)
+ assert_(s[0] >= s[1] >= s[2])
+
+ @pytest.mark.slow
+ def test_crash_2609(self):
+ rng = np.random.default_rng(1234)
+ a = rng.random((1500, 2800))
+ # Shouldn't crash:
+ svdvals(a)
+
+
+class TestDiagSVD:
+
+ def test_simple(self):
+ assert_array_almost_equal(diagsvd([1, 0, 0], 3, 3),
+ [[1, 0, 0], [0, 0, 0], [0, 0, 0]])
+
+
+class TestQR:
+ def test_simple(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ q, r = qr(a)
+ assert_array_almost_equal(q.T @ q, eye(3))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_simple_left(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ q, r = qr(a)
+ c = [1, 2, 3]
+ qc, r2 = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ assert_array_almost_equal(r, r2)
+ qc, r2 = qr_multiply(a, eye(3), "left")
+ assert_array_almost_equal(q, qc)
+
+ def test_simple_right(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ q, r = qr(a)
+ c = [1, 2, 3]
+ qc, r2 = qr_multiply(a, c)
+ assert_array_almost_equal(c @ q, qc)
+ assert_array_almost_equal(r, r2)
+ qc, r = qr_multiply(a, eye(3))
+ assert_array_almost_equal(q, qc)
+
+ def test_simple_pivoting(self):
+ a = np.asarray([[8, 2, 3], [2, 9, 3], [5, 3, 6]])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(3))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_simple_left_pivoting(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ q, r, jpvt = qr(a, pivoting=True)
+ c = [1, 2, 3]
+ qc, r, jpvt = qr_multiply(a, c, "left", True)
+ assert_array_almost_equal(q @ c, qc)
+
+ def test_simple_right_pivoting(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ q, r, jpvt = qr(a, pivoting=True)
+ c = [1, 2, 3]
+ qc, r, jpvt = qr_multiply(a, c, pivoting=True)
+ assert_array_almost_equal(c @ q, qc)
+
+ def test_simple_trap(self):
+ a = [[8, 2, 3], [2, 9, 3]]
+ q, r = qr(a)
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_simple_trap_pivoting(self):
+ a = np.asarray([[8, 2, 3], [2, 9, 3]])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_simple_tall(self):
+ # full version
+ a = [[8, 2], [2, 9], [5, 3]]
+ q, r = qr(a)
+ assert_array_almost_equal(q.T @ q, eye(3))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_simple_tall_pivoting(self):
+ # full version pivoting
+ a = np.asarray([[8, 2], [2, 9], [5, 3]])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(3))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_simple_tall_e(self):
+ # economy version
+ a = [[8, 2], [2, 9], [5, 3]]
+ q, r = qr(a, mode='economic')
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a)
+ assert_equal(q.shape, (3, 2))
+ assert_equal(r.shape, (2, 2))
+
+ def test_simple_tall_e_pivoting(self):
+ # economy version pivoting
+ a = np.asarray([[8, 2], [2, 9], [5, 3]])
+ q, r, p = qr(a, pivoting=True, mode='economic')
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p], mode='economic')
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_simple_tall_left(self):
+ a = [[8, 2], [2, 9], [5, 3]]
+ q, r = qr(a, mode="economic")
+ c = [1, 2]
+ qc, r2 = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ assert_array_almost_equal(r, r2)
+ c = array([1, 2, 0])
+ qc, r2 = qr_multiply(a, c, "left", overwrite_c=True)
+ assert_array_almost_equal(q @ c[:2], qc)
+ qc, r = qr_multiply(a, eye(2), "left")
+ assert_array_almost_equal(qc, q)
+
+ def test_simple_tall_left_pivoting(self):
+ a = [[8, 2], [2, 9], [5, 3]]
+ q, r, jpvt = qr(a, mode="economic", pivoting=True)
+ c = [1, 2]
+ qc, r, kpvt = qr_multiply(a, c, "left", True)
+ assert_array_equal(jpvt, kpvt)
+ assert_array_almost_equal(q @ c, qc)
+ qc, r, jpvt = qr_multiply(a, eye(2), "left", True)
+ assert_array_almost_equal(qc, q)
+
+ def test_simple_tall_right(self):
+ a = [[8, 2], [2, 9], [5, 3]]
+ q, r = qr(a, mode="economic")
+ c = [1, 2, 3]
+ cq, r2 = qr_multiply(a, c)
+ assert_array_almost_equal(c @ q, cq)
+ assert_array_almost_equal(r, r2)
+ cq, r = qr_multiply(a, eye(3))
+ assert_array_almost_equal(cq, q)
+
+ def test_simple_tall_right_pivoting(self):
+ a = [[8, 2], [2, 9], [5, 3]]
+ q, r, jpvt = qr(a, pivoting=True, mode="economic")
+ c = [1, 2, 3]
+ cq, r, jpvt = qr_multiply(a, c, pivoting=True)
+ assert_array_almost_equal(c @ q, cq)
+ cq, r, jpvt = qr_multiply(a, eye(3), pivoting=True)
+ assert_array_almost_equal(cq, q)
+
+ def test_simple_fat(self):
+ # full version
+ a = [[8, 2, 5], [2, 9, 3]]
+ q, r = qr(a)
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a)
+ assert_equal(q.shape, (2, 2))
+ assert_equal(r.shape, (2, 3))
+
+ def test_simple_fat_pivoting(self):
+ # full version pivoting
+ a = np.asarray([[8, 2, 5], [2, 9, 3]])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a[:, p])
+ assert_equal(q.shape, (2, 2))
+ assert_equal(r.shape, (2, 3))
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_simple_fat_e(self):
+ # economy version
+ a = [[8, 2, 3], [2, 9, 5]]
+ q, r = qr(a, mode='economic')
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a)
+ assert_equal(q.shape, (2, 2))
+ assert_equal(r.shape, (2, 3))
+
+ def test_simple_fat_e_pivoting(self):
+ # economy version pivoting
+ a = np.asarray([[8, 2, 3], [2, 9, 5]])
+ q, r, p = qr(a, pivoting=True, mode='economic')
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(q @ r, a[:, p])
+ assert_equal(q.shape, (2, 2))
+ assert_equal(r.shape, (2, 3))
+ q2, r2 = qr(a[:, p], mode='economic')
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_simple_fat_left(self):
+ a = [[8, 2, 3], [2, 9, 5]]
+ q, r = qr(a, mode="economic")
+ c = [1, 2]
+ qc, r2 = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ assert_array_almost_equal(r, r2)
+ qc, r = qr_multiply(a, eye(2), "left")
+ assert_array_almost_equal(qc, q)
+
+ def test_simple_fat_left_pivoting(self):
+ a = [[8, 2, 3], [2, 9, 5]]
+ q, r, jpvt = qr(a, mode="economic", pivoting=True)
+ c = [1, 2]
+ qc, r, jpvt = qr_multiply(a, c, "left", True)
+ assert_array_almost_equal(q @ c, qc)
+ qc, r, jpvt = qr_multiply(a, eye(2), "left", True)
+ assert_array_almost_equal(qc, q)
+
+ def test_simple_fat_right(self):
+ a = [[8, 2, 3], [2, 9, 5]]
+ q, r = qr(a, mode="economic")
+ c = [1, 2]
+ cq, r2 = qr_multiply(a, c)
+ assert_array_almost_equal(c @ q, cq)
+ assert_array_almost_equal(r, r2)
+ cq, r = qr_multiply(a, eye(2))
+ assert_array_almost_equal(cq, q)
+
+ def test_simple_fat_right_pivoting(self):
+ a = [[8, 2, 3], [2, 9, 5]]
+ q, r, jpvt = qr(a, pivoting=True, mode="economic")
+ c = [1, 2]
+ cq, r, jpvt = qr_multiply(a, c, pivoting=True)
+ assert_array_almost_equal(c @ q, cq)
+ cq, r, jpvt = qr_multiply(a, eye(2), pivoting=True)
+ assert_array_almost_equal(cq, q)
+
+ def test_simple_complex(self):
+ a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+ q, r = qr(a)
+ assert_array_almost_equal(q.conj().T @ q, eye(3))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_simple_complex_left(self):
+ a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+ q, r = qr(a)
+ c = [1, 2, 3+4j]
+ qc, r = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ qc, r = qr_multiply(a, eye(3), "left")
+ assert_array_almost_equal(q, qc)
+
+ def test_simple_complex_right(self):
+ a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+ q, r = qr(a)
+ c = [1, 2, 3+4j]
+ qc, r = qr_multiply(a, c)
+ assert_array_almost_equal(c @ q, qc)
+ qc, r = qr_multiply(a, eye(3))
+ assert_array_almost_equal(q, qc)
+
+ def test_simple_tall_complex_left(self):
+ a = [[8, 2+3j], [2, 9], [5+7j, 3]]
+ q, r = qr(a, mode="economic")
+ c = [1, 2+2j]
+ qc, r2 = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ assert_array_almost_equal(r, r2)
+ c = array([1, 2, 0])
+ qc, r2 = qr_multiply(a, c, "left", overwrite_c=True)
+ assert_array_almost_equal(q @ c[:2], qc)
+ qc, r = qr_multiply(a, eye(2), "left")
+ assert_array_almost_equal(qc, q)
+
+ def test_simple_complex_left_conjugate(self):
+ a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+ q, r = qr(a)
+ c = [1, 2, 3+4j]
+ qc, r = qr_multiply(a, c, "left", conjugate=True)
+ assert_array_almost_equal(q.conj() @ c, qc)
+
+ def test_simple_complex_tall_left_conjugate(self):
+ a = [[3, 3+4j], [5, 2+2j], [3, 2]]
+ q, r = qr(a, mode='economic')
+ c = [1, 3+4j]
+ qc, r = qr_multiply(a, c, "left", conjugate=True)
+ assert_array_almost_equal(q.conj() @ c, qc)
+
+ def test_simple_complex_right_conjugate(self):
+ a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+ q, r = qr(a)
+ c = np.array([1, 2, 3+4j])
+ qc, r = qr_multiply(a, c, conjugate=True)
+ assert_array_almost_equal(c @ q.conj(), qc)
+
+ def test_simple_complex_pivoting(self):
+ a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.conj().T @ q, eye(3))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_simple_complex_left_pivoting(self):
+ a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+ q, r, jpvt = qr(a, pivoting=True)
+ c = [1, 2, 3+4j]
+ qc, r, jpvt = qr_multiply(a, c, "left", True)
+ assert_array_almost_equal(q @ c, qc)
+
+ def test_simple_complex_right_pivoting(self):
+ a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+ q, r, jpvt = qr(a, pivoting=True)
+ c = [1, 2, 3+4j]
+ qc, r, jpvt = qr_multiply(a, c, pivoting=True)
+ assert_array_almost_equal(c @ q, qc)
+
+ def test_random(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n])
+ q, r = qr(a)
+ assert_array_almost_equal(q.T @ q, eye(n))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_random_left(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n])
+ q, r = qr(a)
+ c = rng.random([n])
+ qc, r = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ qc, r = qr_multiply(a, eye(n), "left")
+ assert_array_almost_equal(q, qc)
+
+ def test_random_right(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n])
+ q, r = qr(a)
+ c = rng.random([n])
+ cq, r = qr_multiply(a, c)
+ assert_array_almost_equal(c @ q, cq)
+ cq, r = qr_multiply(a, eye(n))
+ assert_array_almost_equal(q, cq)
+
+ def test_random_pivoting(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(n))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_random_tall(self):
+ rng = np.random.RandomState(1234)
+ # full version
+ m = 200
+ n = 100
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r = qr(a)
+ assert_array_almost_equal(q.T @ q, eye(m))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_random_tall_left(self):
+ rng = np.random.RandomState(1234)
+ # full version
+ m = 200
+ n = 100
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r = qr(a, mode="economic")
+ c = rng.random([n])
+ qc, r = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ qc, r = qr_multiply(a, eye(n), "left")
+ assert_array_almost_equal(qc, q)
+
+ def test_random_tall_right(self):
+ rng = np.random.RandomState(1234)
+ # full version
+ m = 200
+ n = 100
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r = qr(a, mode="economic")
+ c = rng.random([m])
+ cq, r = qr_multiply(a, c)
+ assert_array_almost_equal(c @ q, cq)
+ cq, r = qr_multiply(a, eye(m))
+ assert_array_almost_equal(cq, q)
+
+ def test_random_tall_pivoting(self):
+ rng = np.random.RandomState(1234)
+ # full version pivoting
+ m = 200
+ n = 100
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(m))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_random_tall_e(self):
+ rng = np.random.RandomState(1234)
+ # economy version
+ m = 200
+ n = 100
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r = qr(a, mode='economic')
+ assert_array_almost_equal(q.T @ q, eye(n))
+ assert_array_almost_equal(q @ r, a)
+ assert_equal(q.shape, (m, n))
+ assert_equal(r.shape, (n, n))
+
+ def test_random_tall_e_pivoting(self):
+ rng = np.random.RandomState(1234)
+ # economy version pivoting
+ m = 200
+ n = 100
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r, p = qr(a, pivoting=True, mode='economic')
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(n))
+ assert_array_almost_equal(q @ r, a[:, p])
+ assert_equal(q.shape, (m, n))
+ assert_equal(r.shape, (n, n))
+ q2, r2 = qr(a[:, p], mode='economic')
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_random_trap(self):
+ rng = np.random.RandomState(1234)
+ m = 100
+ n = 200
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r = qr(a)
+ assert_array_almost_equal(q.T @ q, eye(m))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_random_trap_pivoting(self):
+ rng = np.random.RandomState(1234)
+ m = 100
+ n = 200
+ for k in range(2):
+ a = rng.random([m, n])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.T @ q, eye(m))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_random_complex(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n]) + 1j*rng.random([n, n])
+ q, r = qr(a)
+ assert_array_almost_equal(q.conj().T @ q, eye(n))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_random_complex_left(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n]) + 1j*rng.random([n, n])
+ q, r = qr(a)
+ c = rng.random([n]) + 1j*rng.random([n])
+ qc, r = qr_multiply(a, c, "left")
+ assert_array_almost_equal(q @ c, qc)
+ qc, r = qr_multiply(a, eye(n), "left")
+ assert_array_almost_equal(q, qc)
+
+ def test_random_complex_right(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n]) + 1j*rng.random([n, n])
+ q, r = qr(a)
+ c = rng.random([n]) + 1j*rng.random([n])
+ cq, r = qr_multiply(a, c)
+ assert_array_almost_equal(c @ q, cq)
+ cq, r = qr_multiply(a, eye(n))
+ assert_array_almost_equal(q, cq)
+
+ def test_random_complex_pivoting(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n]) + 1j*rng.random([n, n])
+ q, r, p = qr(a, pivoting=True)
+ d = abs(diag(r))
+ assert_(np.all(d[1:] <= d[:-1]))
+ assert_array_almost_equal(q.conj().T @ q, eye(n))
+ assert_array_almost_equal(q @ r, a[:, p])
+ q2, r2 = qr(a[:, p])
+ assert_array_almost_equal(q, q2)
+ assert_array_almost_equal(r, r2)
+
+ def test_check_finite(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ q, r = qr(a, check_finite=False)
+ assert_array_almost_equal(q.T @ q, eye(3))
+ assert_array_almost_equal(q @ r, a)
+
+ def test_lwork(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ # Get comparison values
+ with pytest.warns(DeprecationWarning):
+ q, r = qr(a, lwork=None)
+
+ # Test against minimum valid lwork
+ with pytest.warns(DeprecationWarning):
+ q2, r2 = qr(a, lwork=None)
+ assert_array_almost_equal(q2, q)
+ assert_array_almost_equal(r2, r)
+
+ # Test against larger lwork
+ with pytest.warns(DeprecationWarning):
+ q3, r3 = qr(a, lwork=10)
+ assert_array_almost_equal(q3, q)
+ assert_array_almost_equal(r3, r)
+
+ # Test against explicit lwork=-1
+ with pytest.warns(DeprecationWarning):
+ q4, r4 = qr(a, lwork=-1)
+ assert_array_almost_equal(q4, q)
+ assert_array_almost_equal(r4, r)
+
+ # Test against invalid lwork
+ with assert_raises(ValueError):
+ qr(a, lwork=0)
+
+ with assert_raises(ValueError):
+ qr(a, lwork=2)
+
+ @pytest.mark.parametrize("m", [0, 1, 2])
+ @pytest.mark.parametrize("n", [0, 1, 2])
+ @pytest.mark.parametrize("pivoting", [False, True])
+ @pytest.mark.parametrize('dtype', DTYPES)
+ def test_shape_dtype(self, m, n, pivoting, dtype):
+ k = min(m, n)
+
+ a = np.zeros((m, n), dtype=dtype)
+ q, r, *other = qr(a, pivoting=pivoting)
+ assert_equal(q.shape, (m, m))
+ assert_equal(q.dtype, dtype)
+ assert_equal(r.shape, (m, n))
+ assert_equal(r.dtype, dtype)
+ assert len(other) == (1 if pivoting else 0)
+ if pivoting:
+ p, = other
+ assert_equal(p.shape, (n,))
+ assert_equal(p.dtype, np.int64 if HAS_ILP64 else np.int32)
+
+ r_r, *other = qr(a, mode='r', pivoting=pivoting)
+ assert_equal(r_r.shape, (m, n))
+ assert_equal(r_r.dtype, dtype)
+ assert_equal(r, r_r) # sanity check
+ assert len(other) == (1 if pivoting else 0)
+ if pivoting:
+ p, = other
+ assert_equal(p.shape, (n,))
+ assert_equal(p.dtype, np.int64 if HAS_ILP64 else np.int32)
+
+ q, r, *other = qr(a, mode='economic', pivoting=pivoting)
+ assert_equal(q.shape, (m, k))
+ assert_equal(q.dtype, dtype)
+ assert_equal(r.shape, (k, n))
+ assert_equal(r.dtype, dtype)
+ assert len(other) == (1 if pivoting else 0)
+ if pivoting:
+ p, = other
+ assert_equal(p.shape, (n,))
+ assert_equal(p.dtype, np.int64 if HAS_ILP64 else np.int32)
+
+ (raw, tau), r, *other = qr(a, mode='raw', pivoting=pivoting)
+ assert_equal(raw.shape, (m, n))
+ assert_equal(raw.dtype, dtype)
+ assert_equal(tau.shape, (k,))
+ assert_equal(tau.dtype, dtype)
+ assert_equal(r.shape, (k, n))
+ assert_equal(r.dtype, dtype)
+ assert len(other) == (1 if pivoting else 0)
+ if pivoting:
+ p, = other
+ assert_equal(p.shape, (n,))
+ assert_equal(p.dtype, np.int64 if HAS_ILP64 else np.int32)
+
+ @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+ def test_empty(self, m, n):
+ k = min(m, n)
+
+ a = np.empty((m, n))
+ q, r = qr(a)
+ assert_allclose(q, np.identity(m))
+ assert_allclose(r, np.empty((m, n)))
+
+ q, r, p = qr(a, pivoting=True)
+ assert_allclose(q, np.identity(m))
+ assert_allclose(r, np.empty((m, n)))
+ assert_allclose(p, np.arange(n))
+
+ r, = qr(a, mode='r')
+ assert_allclose(r, np.empty((m, n)))
+
+ q, r = qr(a, mode='economic')
+ assert_allclose(q, np.empty((m, k)))
+ assert_allclose(r, np.empty((k, n)))
+
+ (raw, tau), r = qr(a, mode='raw')
+ assert_allclose(raw, np.empty((m, n)))
+ assert_allclose(tau, np.empty((k,)))
+ assert_allclose(r, np.empty((k, n)))
+
+ def test_multiply_empty(self):
+ a = np.empty((0, 0))
+ c = np.empty((0, 0))
+ cq, r = qr_multiply(a, c)
+ assert_allclose(cq, np.empty((0, 0)))
+
+ a = np.empty((0, 2))
+ c = np.empty((2, 0))
+ cq, r = qr_multiply(a, c)
+ assert_allclose(cq, np.empty((2, 0)))
+
+ a = np.empty((2, 0))
+ c = np.empty((0, 2))
+ cq, r = qr_multiply(a, c)
+ assert_allclose(cq, np.empty((0, 2)))
+
+ @pytest.mark.parametrize("pivoting", [True, False])
+ @pytest.mark.parametrize("shape", [(3, 3), (3, 2), (2, 3), (0, 3), (3, 0)])
+ @pytest.mark.parametrize("dtype", DTYPES)
+ def test_raw(self, shape, dtype, pivoting):
+ rng = np.random.default_rng(seed=12345)
+ K = min(shape)
+
+ a = rng.normal(size=shape)
+ if np.issubdtype(dtype, np.complexfloating):
+ a = a + 1j * rng.normal(size=shape)
+ a = a.astype(dtype)
+
+ (q_raw, tau), r, *other = qr(a, mode="raw", pivoting=pivoting)
+
+ assert q_raw.shape == shape
+ assert q_raw.dtype == dtype
+ assert tau.shape == (K,)
+ assert tau.dtype == dtype
+ assert r.shape == (K, shape[1])
+ assert r.dtype == dtype
+
+ assert len(other) == (1 if pivoting else 0)
+ if pivoting:
+ jpvt = other[0]
+ assert jpvt.shape[0] == shape[1]
+ assert jpvt.dtype == np.int64 if HAS_ILP64 else np.int32
+
+ assert_array_almost_equal(np.triu(q_raw)[:K, :], r)
+
+ if shape[0] > 0: # `or_un_gqr` expects `ldab` (= `M` here) > 0
+ q_raw = q_raw[:, :K] # `or_un_gqr` expects tall/square matrices
+ or_un_gqr = get_lapack_funcs(("orgqr",), (q_raw,), ilp64="preferred")[0]
+ q, _, _ = or_un_gqr(q_raw, tau)
+
+ if pivoting:
+ assert_array_almost_equal(q @ r, a[:, jpvt])
+ else:
+ assert_array_almost_equal(q @ r, a)
+
+ if q.size != 0: # sanity check to prevent `q.T @ q` from being all zero
+ assert_array_almost_equal(np.conj(q.T) @ q, np.eye(q.shape[1]))
+
+ def test_raw_flags(self):
+ # internally, the implementation manipulates strides and flags; make sure
+ # that strides and flags are consistent
+ n = 3
+ a = np.eye(n, dtype=np.float32)
+ aa = np.stack([a, 2*a])
+
+ # 2D:
+ q = qr(a, mode="raw")[0][0]
+ itemsize = q.dtype.itemsize
+ assert q.strides == (itemsize, itemsize*n) # F-ordered
+ assert q.flags.f_contiguous
+ assert q.flags.c_contiguous is False
+
+ # Batched case: core dims F-ordered
+ qq = qr(aa, mode="raw")[0][0]
+ assert qq.strides == (n*n*itemsize, itemsize, itemsize*n)
+ assert qq.flags.f_contiguous is False
+ assert q.flags.c_contiguous is False
+
+ @pytest.mark.parametrize("dtype", DTYPES)
+ def test_smoke_economic(self, dtype):
+ # smoke test to check if buffer size if not all too large
+ rng = np.random.default_rng(seed=12345)
+
+ a = rng.normal(size=(10000, 2))
+ if np.issubdtype(dtype, np.complexfloating):
+ a = a + 1j * rng.normal(size=a.shape)
+ a = a.astype(dtype)
+
+ q, r = qr(a, mode="economic")
+
+ # lower precision to deal with the size of the matrices involved
+ decimal = 5 if dtype in (np.float32, np.complex64) else 13
+ assert_array_almost_equal(q @ r, a, decimal=decimal)
+ assert_array_almost_equal(np.conj(q.T) @ q, np.eye(q.shape[1]), decimal=decimal)
+
+ @parametrize_overwrite_arg
+ @pytest.mark.parametrize("dtype", [int, float])
+ @pytest.mark.parametrize("mode", ["raw", "r", "economic", "full"])
+ @pytest.mark.parametrize("pivoting", [True, False])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ @pytest.mark.parametrize("shape", [(4, 3), (3, 4), (2, 4, 3), (2, 3, 4)])
+ def test_overwrite_args(self, dtype, overwrite_kw, mode, pivoting, order, shape):
+ rng = np.random.default_rng(seed=42)
+
+ if order == "F":
+ # ensure slices are F-ordered, which is not the case
+ # for > 2D F-ordered arrays.
+ shape = (*shape[:-2], shape[-1], shape[-2])
+ a = rng.normal(size=shape).astype(dtype)
+ a = np.swapaxes(a, -2, -1)
+ else:
+ a = rng.normal(size=shape).astype(dtype)
+
+ a_ref = np.copy(a)
+ out = qr(a, mode=mode, pivoting=pivoting, **overwrite_kw)
+
+ overwrite_a = overwrite_kw.get("overwrite_a", False)
+ overwrite_a = (
+ overwrite_a and
+ (len(shape) == 2) and
+ (order == "F") and
+ dtype is not int
+ )
+
+ # Check if the result is actually correct & check overwrite behavior
+ if mode == "raw":
+ # if overwrite is enabled `a` will contain `q_raw`
+ (q_raw, tau), r, *other = out
+
+ if a_ref.ndim > 2:
+ for i in range(a_ref.shape[0]):
+ or_un_gqr = get_lapack_funcs(
+ ("orgqr",), (q_raw[0, :, :],), ilp64="preferred"
+ )[0]
+ q, _, _ = or_un_gqr(q_raw[i, :, :np.min(shape[-2:])], tau[i, :])
+
+ if pivoting:
+ jpvt = other[0]
+ assert_allclose(
+ q @ r[i, :, :], a_ref[i, :, :][:, jpvt[i, :]], atol=1e-12
+ )
+ else:
+ assert_allclose(q @ r[i, :, :], a_ref[i, :, :], atol=1e-12)
+ else:
+ or_un_gqr = get_lapack_funcs(("orgqr",), (q_raw,), ilp64="preferred")[0]
+ q, _, _ = or_un_gqr(q_raw[:, :np.min(shape[-2:])], tau)
+
+ if pivoting:
+ jpvt = other[0]
+ assert_allclose(q @ r, a_ref[:, jpvt], atol=1e-12)
+ else:
+ assert_allclose(q @ r, a_ref, atol=1e-12)
+
+ assert overwrite_a == np.shares_memory(a, q_raw)
+
+ elif mode == "r":
+ # `a` is identical to `r` is overwrite is enabled
+ _, r_ref, *other = qr(a_ref, mode="full", pivoting=pivoting)
+
+ assert_allclose(out[0], r_ref, atol=1e-12)
+ if pivoting:
+ assert_allclose(out[-1], other[0])
+
+ assert overwrite_a == np.shares_memory(a, out[0])
+
+ elif mode == "economic" or mode == "full":
+ # `q` is a (cropped version of) `a` if overwrite is enabled for "economic".
+ # For "full" `a` contains `r`.
+
+ if pivoting:
+ jpvt = out[-1]
+ if a_ref.ndim > 2:
+ for i in range(a_ref.shape[0]):
+ assert_allclose(
+ out[0][i, :, :] @ out[1][i, :, :], a_ref[i][:, jpvt[i, :]],
+ atol=1e-12
+ )
+ else:
+ assert_allclose(out[0] @ out[1], a_ref[:, jpvt], atol=1e-12)
+ else:
+ assert_allclose(out[0] @ out[1], a_ref, atol=1e-12)
+
+
+ assert overwrite_a == np.shares_memory(
+ a, out[0 if mode == "economic" else 1]
+ )
+
+
+class TestRQ:
+ def test_simple(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ r, q = rq(a)
+ assert_array_almost_equal(q @ q.T, eye(3))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_r(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ r, q = rq(a)
+ r2 = rq(a, mode='r')
+ assert_array_almost_equal(r, r2)
+
+ def test_random(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n])
+ r, q = rq(a)
+ assert_array_almost_equal(q @ q.T, eye(n))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_simple_trap(self):
+ a = [[8, 2, 3], [2, 9, 3]]
+ r, q = rq(a)
+ assert_array_almost_equal(q.T @ q, eye(3))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_simple_tall(self):
+ a = [[8, 2], [2, 9], [5, 3]]
+ r, q = rq(a)
+ assert_array_almost_equal(q.T @ q, eye(2))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_simple_fat(self):
+ a = [[8, 2, 5], [2, 9, 3]]
+ r, q = rq(a)
+ assert_array_almost_equal(q @ q.T, eye(3))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_simple_complex(self):
+ a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+ r, q = rq(a)
+ assert_array_almost_equal(q @ q.conj().T, eye(3))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_random_tall(self):
+ rng = np.random.RandomState(1234)
+ m = 200
+ n = 100
+ for k in range(2):
+ a = rng.random([m, n])
+ r, q = rq(a)
+ assert_array_almost_equal(q @ q.T, eye(n))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_random_trap(self):
+ rng = np.random.RandomState(1234)
+ m = 100
+ n = 200
+ for k in range(2):
+ a = rng.random([m, n])
+ r, q = rq(a)
+ assert_array_almost_equal(q @ q.T, eye(n))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_random_trap_economic(self):
+ rng = np.random.RandomState(1234)
+ m = 100
+ n = 200
+ for k in range(2):
+ a = rng.random([m, n])
+ r, q = rq(a, mode='economic')
+ assert_array_almost_equal(q @ q.T, eye(m))
+ assert_array_almost_equal(r @ q, a)
+ assert_equal(q.shape, (m, n))
+ assert_equal(r.shape, (m, m))
+
+ def test_random_complex(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n]) + 1j*rng.random([n, n])
+ r, q = rq(a)
+ assert_array_almost_equal(q @ q.conj().T, eye(n))
+ assert_array_almost_equal(r @ q, a)
+
+ def test_random_complex_economic(self):
+ rng = np.random.RandomState(1234)
+ m = 100
+ n = 200
+ for k in range(2):
+ a = rng.random([m, n]) + 1j*rng.random([m, n])
+ r, q = rq(a, mode='economic')
+ assert_array_almost_equal(q @ q.conj().T, eye(m))
+ assert_array_almost_equal(r @ q, a)
+ assert_equal(q.shape, (m, n))
+ assert_equal(r.shape, (m, m))
+
+ def test_check_finite(self):
+ a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+ r, q = rq(a, check_finite=False)
+ assert_array_almost_equal(q @ q.T, eye(3))
+ assert_array_almost_equal(r @ q, a)
+
+ @pytest.mark.parametrize("m", [0, 1, 2])
+ @pytest.mark.parametrize("n", [0, 1, 2])
+ @pytest.mark.parametrize('dtype', DTYPES)
+ def test_shape_dtype(self, m, n, dtype):
+ k = min(m, n)
+
+ a = np.zeros((m, n), dtype=dtype)
+ r, q = rq(a)
+ assert_equal(q.shape, (n, n))
+ assert_equal(r.shape, (m, n))
+ assert_equal(r.dtype, dtype)
+ assert_equal(q.dtype, dtype)
+
+ r = rq(a, mode='r')
+ assert_equal(r.shape, (m, n))
+ assert_equal(r.dtype, dtype)
+
+ r, q = rq(a, mode='economic')
+ assert_equal(r.shape, (m, k))
+ assert_equal(r.dtype, dtype)
+ assert_equal(q.shape, (k, n))
+ assert_equal(q.dtype, dtype)
+
+ @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+ def test_empty(self, m, n):
+ k = min(m, n)
+
+ a = np.empty((m, n))
+ r, q = rq(a)
+ assert_allclose(r, np.empty((m, n)))
+ assert_allclose(q, np.identity(n))
+
+ r = rq(a, mode='r')
+ assert_allclose(r, np.empty((m, n)))
+
+ r, q = rq(a, mode='economic')
+ assert_allclose(r, np.empty((m, k)))
+ assert_allclose(q, np.empty((k, n)))
+
+
+class TestSchur:
+
+ def check_schur(self, a, t, u, rtol, atol):
+ # Check that the Schur decomposition is correct.
+ assert_allclose(u @ t @ u.conj().T, a, rtol=rtol, atol=atol,
+ err_msg="Schur decomposition does not match 'a'")
+ # The expected value of u @ u.H - I is all zeros, so test
+ # with absolute tolerance only.
+ assert_allclose(u @ u.conj().T - np.eye(len(u)), 0, rtol=0, atol=atol,
+ err_msg="u is not unitary")
+
+ def test_simple(self):
+ a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]]
+ t, z = schur(a)
+ self.check_schur(a, t, z, rtol=1e-14, atol=5e-15)
+ tc, zc = schur(a, 'complex')
+ assert_(np.any(ravel(iscomplex(zc))) and np.any(ravel(iscomplex(tc))))
+ self.check_schur(a, tc, zc, rtol=1e-14, atol=5e-15)
+ tc2, zc2 = rsf2csf(tc, zc)
+ self.check_schur(a, tc2, zc2, rtol=1e-14, atol=5e-15)
+
+ @pytest.mark.parametrize(
+ 'sort, expected_diag',
+ [('lhp', [-np.sqrt(2), -0.5, np.sqrt(2), 0.5]),
+ ('rhp', [np.sqrt(2), 0.5, -np.sqrt(2), -0.5]),
+ ('iuc', [-0.5, 0.5, np.sqrt(2), -np.sqrt(2)]),
+ ('ouc', [np.sqrt(2), -np.sqrt(2), -0.5, 0.5]),
+ (lambda x: x >= 0.0, [np.sqrt(2), 0.5, -np.sqrt(2), -0.5])]
+ )
+ def test_sort(self, sort, expected_diag):
+ # The exact eigenvalues of this matrix are
+ # -sqrt(2), sqrt(2), -1/2, 1/2.
+ a = [[4., 3., 1., -1.],
+ [-4.5, -3.5, -1., 1.],
+ [9., 6., -4., 4.5],
+ [6., 4., -3., 3.5]]
+ t, u, sdim = schur(a, sort=sort)
+ self.check_schur(a, t, u, rtol=1e-14, atol=5e-15)
+ assert_allclose(np.diag(t), expected_diag, rtol=1e-12)
+ assert_equal(2, sdim)
+
+ def test_sort_errors(self):
+ a = [[4., 3., 1., -1.],
+ [-4.5, -3.5, -1., 1.],
+ [9., 6., -4., 4.5],
+ [6., 4., -3., 3.5]]
+ assert_raises(ValueError, schur, a, sort='unsupported')
+ assert_raises(ValueError, schur, a, sort=1)
+
+ def test_check_finite(self):
+ a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]]
+ t, z = schur(a, check_finite=False)
+ assert_array_almost_equal(z @ t @ z.conj().T, a)
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ t, z = schur(a)
+ t0, z0 = schur(np.eye(2, dtype=dt))
+ assert_allclose(t, np.empty((0, 0)))
+ assert_allclose(z, np.empty((0, 0)))
+ assert t.dtype == t0.dtype
+ assert z.dtype == z0.dtype
+
+ t, z, sdim = schur(a, sort='lhp')
+ assert_allclose(t, np.empty((0, 0)))
+ assert_allclose(z, np.empty((0, 0)))
+ assert_equal(sdim, 0)
+ assert t.dtype == t0.dtype
+ assert z.dtype == z0.dtype
+
+ @pytest.mark.parametrize('sort', ['iuc', 'ouc'])
+ @pytest.mark.parametrize('output', ['real', 'complex'])
+ @pytest.mark.parametrize('dtype', [np.float32, np.float64,
+ np.complex64, np.complex128])
+ def test_gh_13137_sort_str(self, sort, output, dtype):
+ # gh-13137 reported that sort values 'iuc' and 'ouc' were not
+ # correct because the callables assumed that the eigenvalues would
+ # always be expressed as a single complex number.
+ # In fact, when `output='real'` and the dtype is real, the
+ # eigenvalues are passed as separate real and imaginary components
+ # (yet no error is raised if the callable accepts only one argument).
+ #
+ # This tests these sort values by counting the number of eigenvalues
+ # `schur` reports as being inside/outside the unit circle.
+
+ # Real matrix with eigenvalues 0.1 +- 2j
+ A = np.asarray([[0.1, -2], [2, 0.1]])
+
+ # Previously, this would fail for `output='real'` with real dtypes
+ sdim = schur(A.astype(dtype), sort=sort, output=output)[-1]
+ assert sdim == 0 if sort == 'iuc' else sdim == 2
+
+ @pytest.mark.parametrize('output', ['real', 'complex'])
+ @pytest.mark.parametrize('dtype', [np.float32, np.float64,
+ np.complex64, np.complex128])
+ def test_gh_13137_sort_custom(self, output, dtype):
+ # This simply tests our understanding of how eigenvalues are
+ # passed to a sort callable. If `output='real'` and the dtype is real,
+ # real and imaginary parts are passed as separate real arguments;
+ # otherwise, they are passed a single complex argument.
+ # Also, if `output='real'` and the dtype is real, when either
+ # eigenvalue in a complex conjugate pair satisfies the sort condition,
+ # `sdim` is incremented by TWO.
+
+ # Real matrix with eigenvalues 0.1 +- 2j
+ A = np.asarray([[0.1, -2], [2, 0.1]])
+
+ all_real = output=='real' and dtype in {np.float32, np.float64}
+
+ def sort(x, y=None):
+ if all_real:
+ assert not np.iscomplexobj(x)
+ assert y is not None and np.isreal(y)
+ z = x + y*1j
+ else:
+ assert np.iscomplexobj(x)
+ assert y is None
+ z = x
+ return z.imag > 1e-15
+
+ # Only one complex eigenvalue satisfies the condition, but when
+ # `all_real` applies, both eigenvalues in the complex conjugate pair
+ # are counted.
+ sdim = schur(A.astype(dtype), sort=sort, output=output)[-1]
+ assert sdim == 2 if all_real else sdim == 1
+
+
+class TestHessenberg:
+
+ def test_simple(self):
+ a = [[-149, -50, -154],
+ [537, 180, 546],
+ [-27, -9, -25]]
+ h1 = [[-149.0000, 42.2037, -156.3165],
+ [-537.6783, 152.5511, -554.9272],
+ [0, 0.0728, 2.4489]]
+ h, q = hessenberg(a, calc_q=1)
+ assert_array_almost_equal(q.T @ a @ q, h)
+ assert_array_almost_equal(h, h1, decimal=4)
+
+ def test_simple_complex(self):
+ a = [[-149, -50, -154],
+ [537, 180j, 546],
+ [-27j, -9, -25]]
+ h, q = hessenberg(a, calc_q=1)
+ assert_array_almost_equal(q.conj().T @ a @ q, h)
+
+ def test_simple2(self):
+ a = [[1, 2, 3, 4, 5, 6, 7],
+ [0, 2, 3, 4, 6, 7, 2],
+ [0, 2, 2, 3, 0, 3, 2],
+ [0, 0, 2, 8, 0, 0, 2],
+ [0, 3, 1, 2, 0, 1, 2],
+ [0, 1, 2, 3, 0, 1, 0],
+ [0, 0, 0, 0, 0, 1, 2]]
+ h, q = hessenberg(a, calc_q=1)
+ assert_array_almost_equal(q.T @ a @ q, h)
+
+ def test_simple3(self):
+ a = np.eye(3)
+ a[-1, 0] = 2
+ h, q = hessenberg(a, calc_q=1)
+ assert_array_almost_equal(q.T @ a @ q, h)
+
+ def test_random(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n])
+ h, q = hessenberg(a, calc_q=1)
+ assert_array_almost_equal(q.T @ a @ q, h)
+
+ def test_random_complex(self):
+ rng = np.random.RandomState(1234)
+ n = 20
+ for k in range(2):
+ a = rng.random([n, n]) + 1j*rng.random([n, n])
+ h, q = hessenberg(a, calc_q=1)
+ assert_array_almost_equal(q.conj().T @ a @ q, h)
+
+ def test_check_finite(self):
+ a = [[-149, -50, -154],
+ [537, 180, 546],
+ [-27, -9, -25]]
+ h1 = [[-149.0000, 42.2037, -156.3165],
+ [-537.6783, 152.5511, -554.9272],
+ [0, 0.0728, 2.4489]]
+ h, q = hessenberg(a, calc_q=1, check_finite=False)
+ assert_array_almost_equal(q.T @ a @ q, h)
+ assert_array_almost_equal(h, h1, decimal=4)
+
+ def test_2x2(self):
+ a = [[2, 1], [7, 12]]
+
+ h, q = hessenberg(a, calc_q=1)
+ assert_array_almost_equal(q, np.eye(2))
+ assert_array_almost_equal(h, a)
+
+ b = [[2-7j, 1+2j], [7+3j, 12-2j]]
+ h2, q2 = hessenberg(b, calc_q=1)
+ assert_array_almost_equal(q2, np.eye(2))
+ assert_array_almost_equal(h2, b)
+
+ @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ h = hessenberg(a)
+ assert h.shape == (0, 0)
+ assert h.dtype == hessenberg(np.eye(3, dtype=dt)).dtype
+
+ h, q = hessenberg(a, calc_q=True)
+ h3, q3 = hessenberg(a, calc_q=True)
+ assert h.shape == (0, 0)
+ assert h.dtype == h3.dtype
+
+ assert q.shape == (0, 0)
+ assert q.dtype == q3.dtype
+
+
+blas_provider = blas_version = None
+blas_provider = CONFIG['Build Dependencies']['blas']['name']
+blas_version = CONFIG['Build Dependencies']['blas']['version']
+
+
+class TestQZ:
+ def test_qz_single(self):
+ rng = np.random.RandomState(12345)
+ n = 5
+ A = rng.random([n, n]).astype(float32)
+ B = rng.random([n, n]).astype(float32)
+ AA, BB, Q, Z = qz(A, B)
+ assert_array_almost_equal(Q @ AA @ Z.T, A, decimal=5)
+ assert_array_almost_equal(Q @ BB @ Z.T, B, decimal=5)
+ assert_array_almost_equal(Q @ Q.T, eye(n), decimal=5)
+ assert_array_almost_equal(Z @ Z.T, eye(n), decimal=5)
+ assert_(np.all(diag(BB) >= 0))
+
+ def test_qz_double(self):
+ rng = np.random.RandomState(12345)
+ n = 5
+ A = rng.random([n, n])
+ B = rng.random([n, n])
+ AA, BB, Q, Z = qz(A, B)
+ assert_array_almost_equal(Q @ AA @ Z.T, A)
+ assert_array_almost_equal(Q @ BB @ Z.T, B)
+ assert_array_almost_equal(Q @ Q.T, eye(n))
+ assert_array_almost_equal(Z @ Z.T, eye(n))
+ assert_(np.all(diag(BB) >= 0))
+
+ def test_qz_complex(self):
+ rng = np.random.RandomState(12345)
+ n = 5
+ A = rng.random([n, n]) + 1j*rng.random([n, n])
+ B = rng.random([n, n]) + 1j*rng.random([n, n])
+ AA, BB, Q, Z = qz(A, B)
+ assert_array_almost_equal(Q @ AA @ Z.conj().T, A)
+ assert_array_almost_equal(Q @ BB @ Z.conj().T, B)
+ assert_array_almost_equal(Q @ Q.conj().T, eye(n))
+ assert_array_almost_equal(Z @ Z.conj().T, eye(n))
+ assert_(np.all(diag(BB) >= 0))
+ assert_(np.all(diag(BB).imag == 0))
+
+ def test_qz_complex64(self):
+ rng = np.random.RandomState(12345)
+ n = 5
+ A = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64)
+ B = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64)
+ AA, BB, Q, Z = qz(A, B)
+ assert_array_almost_equal(Q @ AA @ Z.conj().T, A, decimal=5)
+ assert_array_almost_equal(Q @ BB @ Z.conj().T, B, decimal=5)
+ assert_array_almost_equal(Q @ Q.conj().T, eye(n), decimal=5)
+ assert_array_almost_equal(Z @ Z.conj().T, eye(n), decimal=5)
+ assert_(np.all(diag(BB) >= 0))
+ assert_(np.all(diag(BB).imag == 0))
+
+ def test_qz_double_complex(self):
+ rng = np.random.RandomState(12345)
+ n = 5
+ A = rng.random([n, n])
+ B = rng.random([n, n])
+ AA, BB, Q, Z = qz(A, B, output='complex')
+ aa = Q @ AA @ Z.conj().T
+ assert_array_almost_equal(aa.real, A)
+ assert_array_almost_equal(aa.imag, 0)
+ bb = Q @ BB @ Z.conj().T
+ assert_array_almost_equal(bb.real, B)
+ assert_array_almost_equal(bb.imag, 0)
+ assert_array_almost_equal(Q @ Q.conj().T, eye(n))
+ assert_array_almost_equal(Z @ Z.conj().T, eye(n))
+ assert_(np.all(diag(BB) >= 0))
+
+ def test_qz_double_sort(self):
+ # from https://www.nag.com/lapack-ex/node119.html
+ # NOTE: These matrices may be ill-conditioned and lead to a
+ # seg fault on certain python versions when compiled with
+ # sse2 or sse3 older ATLAS/LAPACK binaries for windows
+ # A = np.array([[3.9, 12.5, -34.5, -0.5],
+ # [ 4.3, 21.5, -47.5, 7.5],
+ # [ 4.3, 21.5, -43.5, 3.5],
+ # [ 4.4, 26.0, -46.0, 6.0 ]])
+
+ # B = np.array([[ 1.0, 2.0, -3.0, 1.0],
+ # [1.0, 3.0, -5.0, 4.0],
+ # [1.0, 3.0, -4.0, 3.0],
+ # [1.0, 3.0, -4.0, 4.0]])
+ A = np.array([[3.9, 12.5, -34.5, 2.5],
+ [4.3, 21.5, -47.5, 7.5],
+ [4.3, 1.5, -43.5, 3.5],
+ [4.4, 6.0, -46.0, 6.0]])
+
+ B = np.array([[1.0, 1.0, -3.0, 1.0],
+ [1.0, 3.0, -5.0, 4.4],
+ [1.0, 2.0, -4.0, 1.0],
+ [1.2, 3.0, -4.0, 4.0]])
+
+ assert_raises(ValueError, qz, A, B, sort=lambda ar, ai, beta: ai == 0)
+ if False:
+ AA, BB, Q, Z, sdim = qz(A, B, sort=lambda ar, ai, beta: ai == 0)
+ # assert_(sdim == 2)
+ assert_(sdim == 4)
+ assert_array_almost_equal(Q @ AA @ Z.T, A)
+ assert_array_almost_equal(Q @ BB @ Z.T, B)
+
+ # test absolute values bc the sign is ambiguous and
+ # might be platform dependent
+ assert_array_almost_equal(np.abs(AA), np.abs(np.array(
+ [[35.7864, -80.9061, -12.0629, -9.498],
+ [0., 2.7638, -2.3505, 7.3256],
+ [0., 0., 0.6258, -0.0398],
+ [0., 0., 0., -12.8217]])), 4)
+ assert_array_almost_equal(np.abs(BB), np.abs(np.array(
+ [[4.5324, -8.7878, 3.2357, -3.5526],
+ [0., 1.4314, -2.1894, 0.9709],
+ [0., 0., 1.3126, -0.3468],
+ [0., 0., 0., 0.559]])), 4)
+ assert_array_almost_equal(np.abs(Q), np.abs(np.array(
+ [[-0.4193, -0.605, -0.1894, -0.6498],
+ [-0.5495, 0.6987, 0.2654, -0.3734],
+ [-0.4973, -0.3682, 0.6194, 0.4832],
+ [-0.5243, 0.1008, -0.7142, 0.4526]])), 4)
+ assert_array_almost_equal(np.abs(Z), np.abs(np.array(
+ [[-0.9471, -0.2971, -0.1217, 0.0055],
+ [-0.0367, 0.1209, 0.0358, 0.9913],
+ [0.3171, -0.9041, -0.2547, 0.1312],
+ [0.0346, 0.2824, -0.9587, 0.0014]])), 4)
+
+ # test absolute values bc the sign is ambiguous and might be platform
+ # dependent
+ # assert_array_almost_equal(abs(AA), abs(np.array([
+ # [3.8009, -69.4505, 50.3135, -43.2884],
+ # [0.0000, 9.2033, -0.2001, 5.9881],
+ # [0.0000, 0.0000, 1.4279, 4.4453],
+ # [0.0000, 0.0000, 0.9019, -1.1962]])), 4)
+ # assert_array_almost_equal(abs(BB), abs(np.array([
+ # [1.9005, -10.2285, 0.8658, -5.2134],
+ # [0.0000, 2.3008, 0.7915, 0.4262],
+ # [0.0000, 0.0000, 0.8101, 0.0000],
+ # [0.0000, 0.0000, 0.0000, -0.2823]])), 4)
+ # assert_array_almost_equal(abs(Q), abs(np.array([
+ # [0.4642, 0.7886, 0.2915, -0.2786],
+ # [0.5002, -0.5986, 0.5638, -0.2713],
+ # [0.5002, 0.0154, -0.0107, 0.8657],
+ # [0.5331, -0.1395, -0.7727, -0.3151]])), 4)
+ # assert_array_almost_equal(dot(Q,Q.T), eye(4))
+ # assert_array_almost_equal(abs(Z), abs(np.array([
+ # [0.9961, -0.0014, 0.0887, -0.0026],
+ # [0.0057, -0.0404, -0.0938, -0.9948],
+ # [0.0626, 0.7194, -0.6908, 0.0363],
+ # [0.0626, -0.6934, -0.7114, 0.0956]])), 4)
+ # assert_array_almost_equal(dot(Z,Z.T), eye(4))
+
+ # def test_qz_complex_sort(self):
+ # cA = np.array([
+ # [-21.10+22.50*1j, 53.50+-50.50*1j, -34.50+127.50*1j, 7.50+ 0.50*1j],
+ # [-0.46+ -7.78*1j, -3.50+-37.50*1j, -15.50+ 58.50*1j,-10.50+ -1.50*1j],
+ # [ 4.30+ -5.50*1j, 39.70+-17.10*1j, -68.50+ 12.50*1j, -7.50+ -3.50*1j],
+ # [ 5.50+ 4.40*1j, 14.40+ 43.30*1j, -32.50+-46.00*1j,-19.00+-32.50*1j]])
+
+ # cB = np.array([
+ # [1.00+ -5.00*1j, 1.60+ 1.20*1j,-3.00+ 0.00*1j, 0.00+ -1.00*1j],
+ # [0.80+ -0.60*1j, 3.00+ -5.00*1j,-4.00+ 3.00*1j,-2.40+ -3.20*1j],
+ # [1.00+ 0.00*1j, 2.40+ 1.80*1j,-4.00+ -5.00*1j, 0.00+ -3.00*1j],
+ # [0.00+ 1.00*1j,-1.80+ 2.40*1j, 0.00+ -4.00*1j, 4.00+ -5.00*1j]])
+
+ # AAS,BBS,QS,ZS,sdim = qz(cA,cB,sort='lhp')
+
+ # eigenvalues = diag(AAS)/diag(BBS)
+ # assert_(np.all(np.real(eigenvalues[:sdim] < 0)))
+ # assert_(np.all(np.real(eigenvalues[sdim:] > 0)))
+
+ def test_check_finite(self):
+ rng = np.random.RandomState(12345)
+ n = 5
+ A = rng.random([n, n])
+ B = rng.random([n, n])
+ AA, BB, Q, Z = qz(A, B, check_finite=False)
+ assert_array_almost_equal(Q @ AA @ Z.T, A)
+ assert_array_almost_equal(Q @ BB @ Z.T, B)
+ assert_array_almost_equal(Q @ Q.T, eye(n))
+ assert_array_almost_equal(Z @ Z.T, eye(n))
+ assert_(np.all(diag(BB) >= 0))
+
+
+class TestOrdQZ:
+ @classmethod
+ def setup_class(cls):
+ # https://www.nag.com/lapack-ex/node119.html
+ A1 = np.array([[-21.10 - 22.50j, 53.5 - 50.5j, -34.5 + 127.5j,
+ 7.5 + 0.5j],
+ [-0.46 - 7.78j, -3.5 - 37.5j, -15.5 + 58.5j,
+ -10.5 - 1.5j],
+ [4.30 - 5.50j, 39.7 - 17.1j, -68.5 + 12.5j,
+ -7.5 - 3.5j],
+ [5.50 + 4.40j, 14.4 + 43.3j, -32.5 - 46.0j,
+ -19.0 - 32.5j]])
+
+ B1 = np.array([[1.0 - 5.0j, 1.6 + 1.2j, -3 + 0j, 0.0 - 1.0j],
+ [0.8 - 0.6j, .0 - 5.0j, -4 + 3j, -2.4 - 3.2j],
+ [1.0 + 0.0j, 2.4 + 1.8j, -4 - 5j, 0.0 - 3.0j],
+ [0.0 + 1.0j, -1.8 + 2.4j, 0 - 4j, 4.0 - 5.0j]])
+
+ # https://www.nag.com/numeric/fl/nagdoc_fl23/xhtml/F08/f08yuf.xml
+ A2 = np.array([[3.9, 12.5, -34.5, -0.5],
+ [4.3, 21.5, -47.5, 7.5],
+ [4.3, 21.5, -43.5, 3.5],
+ [4.4, 26.0, -46.0, 6.0]])
+
+ B2 = np.array([[1, 2, -3, 1],
+ [1, 3, -5, 4],
+ [1, 3, -4, 3],
+ [1, 3, -4, 4]])
+
+ # example with the eigenvalues
+ # -0.33891648, 1.61217396+0.74013521j, 1.61217396-0.74013521j,
+ # 0.61244091
+ # thus featuring:
+ # * one complex conjugate eigenvalue pair,
+ # * one eigenvalue in the lhp
+ # * 2 eigenvalues in the unit circle
+ # * 2 non-real eigenvalues
+ A3 = np.array([[5., 1., 3., 3.],
+ [4., 4., 2., 7.],
+ [7., 4., 1., 3.],
+ [0., 4., 8., 7.]])
+ B3 = np.array([[8., 10., 6., 10.],
+ [7., 7., 2., 9.],
+ [9., 1., 6., 6.],
+ [5., 1., 4., 7.]])
+
+ # example with infinite eigenvalues
+ A4 = np.eye(2)
+ B4 = np.diag([0, 1])
+
+ # example with (alpha, beta) = (0, 0)
+ A5 = np.diag([1, 0])
+
+ cls.A = [A1, A2, A3, A4, A5]
+ cls.B = [B1, B2, B3, B4, A5]
+
+ def qz_decomp(self, sort):
+ with np.errstate(all='raise'):
+ ret = [ordqz(Ai, Bi, sort=sort) for Ai, Bi in zip(self.A, self.B)]
+ return tuple(ret)
+
+ def check(self, A, B, sort, AA, BB, alpha, beta, Q, Z):
+ Id = np.eye(*A.shape)
+ # make sure Q and Z are orthogonal
+ assert_array_almost_equal(Q @ Q.T.conj(), Id)
+ assert_array_almost_equal(Z @ Z.T.conj(), Id)
+ # check factorization
+ assert_array_almost_equal(Q @ AA, A @ Z)
+ assert_array_almost_equal(Q @ BB, B @ Z)
+ # check shape of AA and BB
+ assert_array_equal(np.tril(AA, -2), np.zeros(AA.shape))
+ assert_array_equal(np.tril(BB, -1), np.zeros(BB.shape))
+ # check eigenvalues
+ for i in range(A.shape[0]):
+ # does the current diagonal element belong to a 2-by-2 block
+ # that was already checked?
+ if i > 0 and A[i, i - 1] != 0:
+ continue
+ # take care of 2-by-2 blocks
+ if i < AA.shape[0] - 1 and AA[i + 1, i] != 0:
+ evals, _ = eig(AA[i:i + 2, i:i + 2], BB[i:i + 2, i:i + 2])
+ # make sure the pair of complex conjugate eigenvalues
+ # is ordered consistently (positive imaginary part first)
+ if evals[0].imag < 0:
+ evals = evals[[1, 0]]
+ tmp = alpha[i:i + 2]/beta[i:i + 2]
+ if tmp[0].imag < 0:
+ tmp = tmp[[1, 0]]
+ assert_array_almost_equal(evals, tmp)
+ else:
+ if alpha[i] == 0 and beta[i] == 0:
+ assert_equal(AA[i, i], 0)
+ assert_equal(BB[i, i], 0)
+ elif beta[i] == 0:
+ assert_equal(BB[i, i], 0)
+ else:
+ assert_almost_equal(AA[i, i]/BB[i, i], alpha[i]/beta[i])
+ sortfun = _select_function(sort)
+ lastsort = True
+ for i in range(A.shape[0]):
+ cursort = sortfun(np.array([alpha[i]]), np.array([beta[i]]))
+ # once the sorting criterion was not matched all subsequent
+ # eigenvalues also shouldn't match
+ if not lastsort:
+ assert not cursort
+ lastsort = cursort
+
+ def check_all(self, sort):
+ ret = self.qz_decomp(sort)
+
+ for reti, Ai, Bi in zip(ret, self.A, self.B):
+ self.check(Ai, Bi, sort, *reti)
+
+ def test_lhp(self):
+ self.check_all('lhp')
+
+ def test_rhp(self):
+ self.check_all('rhp')
+
+ def test_iuc(self):
+ self.check_all('iuc')
+
+ def test_ouc(self):
+ self.check_all('ouc')
+
+ def test_ref(self):
+ # real eigenvalues first (top-left corner)
+ def sort(x, y):
+ out = np.empty_like(x, dtype=bool)
+ nonzero = (y != 0)
+ out[~nonzero] = False
+ out[nonzero] = (x[nonzero]/y[nonzero]).imag == 0
+ return out
+
+ self.check_all(sort)
+
+ def test_cef(self):
+ # complex eigenvalues first (top-left corner)
+ def sort(x, y):
+ out = np.empty_like(x, dtype=bool)
+ nonzero = (y != 0)
+ out[~nonzero] = False
+ out[nonzero] = (x[nonzero]/y[nonzero]).imag != 0
+ return out
+
+ self.check_all(sort)
+
+ def test_diff_input_types(self):
+ ret = ordqz(self.A[1], self.B[2], sort='lhp')
+ self.check(self.A[1], self.B[2], 'lhp', *ret)
+
+ ret = ordqz(self.B[2], self.A[1], sort='lhp')
+ self.check(self.B[2], self.A[1], 'lhp', *ret)
+
+ def test_sort_explicit(self):
+ # Test order of the eigenvalues in the 2 x 2 case where we can
+ # explicitly compute the solution
+ A1 = np.eye(2)
+ B1 = np.diag([-2, 0.5])
+ expected1 = [('lhp', [-0.5, 2]),
+ ('rhp', [2, -0.5]),
+ ('iuc', [-0.5, 2]),
+ ('ouc', [2, -0.5])]
+ A2 = np.eye(2)
+ B2 = np.diag([-2 + 1j, 0.5 + 0.5j])
+ expected2 = [('lhp', [1/(-2 + 1j), 1/(0.5 + 0.5j)]),
+ ('rhp', [1/(0.5 + 0.5j), 1/(-2 + 1j)]),
+ ('iuc', [1/(-2 + 1j), 1/(0.5 + 0.5j)]),
+ ('ouc', [1/(0.5 + 0.5j), 1/(-2 + 1j)])]
+ # 'lhp' is ambiguous so don't test it
+ A3 = np.eye(2)
+ B3 = np.diag([2, 0])
+ expected3 = [('rhp', [0.5, np.inf]),
+ ('iuc', [0.5, np.inf]),
+ ('ouc', [np.inf, 0.5])]
+ # 'rhp' is ambiguous so don't test it
+ A4 = np.eye(2)
+ B4 = np.diag([-2, 0])
+ expected4 = [('lhp', [-0.5, np.inf]),
+ ('iuc', [-0.5, np.inf]),
+ ('ouc', [np.inf, -0.5])]
+ A5 = np.diag([0, 1])
+ B5 = np.diag([0, 0.5])
+ # 'lhp' and 'iuc' are ambiguous so don't test them
+ expected5 = [('rhp', [2, np.nan]),
+ ('ouc', [2, np.nan])]
+
+ A = [A1, A2, A3, A4, A5]
+ B = [B1, B2, B3, B4, B5]
+ expected = [expected1, expected2, expected3, expected4, expected5]
+ for Ai, Bi, expectedi in zip(A, B, expected):
+ for sortstr, expected_eigvals in expectedi:
+ _, _, alpha, beta, _, _ = ordqz(Ai, Bi, sort=sortstr)
+ azero = (alpha == 0)
+ bzero = (beta == 0)
+ x = np.empty_like(alpha)
+ x[azero & bzero] = np.nan
+ x[~azero & bzero] = np.inf
+ x[~bzero] = alpha[~bzero]/beta[~bzero]
+ assert_allclose(expected_eigvals, x)
+
+
+class TestOrdQZWorkspaceSize:
+ @pytest.mark.fail_slow(5)
+ def test_decompose(self):
+ rng = np.random.RandomState(12345)
+ N = 202
+ # raises error if lwork parameter to dtrsen is too small
+ for ddtype in [np.float32, np.float64]:
+ A = rng.random((N, N)).astype(ddtype)
+ B = rng.random((N, N)).astype(ddtype)
+ # sort = lambda ar, ai, b: ar**2 + ai**2 < b**2
+ _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta,
+ output='real')
+
+ for ddtype in [np.complex128, np.complex64]:
+ A = rng.random((N, N)).astype(ddtype)
+ B = rng.random((N, N)).astype(ddtype)
+ _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta,
+ output='complex')
+
+ @pytest.mark.slow
+ def test_decompose_ouc(self):
+ rng = np.random.RandomState(12345)
+ N = 202
+ # segfaults if lwork parameter to dtrsen is too small
+ for ddtype in [np.float32, np.float64, np.complex128, np.complex64]:
+ A = rng.random((N, N)).astype(ddtype)
+ B = rng.random((N, N)).astype(ddtype)
+ S, T, alpha, beta, U, V = ordqz(A, B, sort='ouc')
+
+
+class TestDatacopied:
+
+ def test_datacopied(self):
+ from scipy.linalg._decomp import _datacopied
+
+ M = matrix([[0, 1], [2, 3]])
+ A = asarray(M)
+ L = M.tolist()
+ M2 = M.copy()
+
+ class Fake1:
+ def __array__(self, dtype=None, copy=None):
+ return A
+
+ class Fake2:
+ __array_interface__ = A.__array_interface__
+
+ F1 = Fake1()
+ F2 = Fake2()
+
+ for item, status in [(M, False), (A, False), (L, True),
+ (M2, False), (F1, False), (F2, False)]:
+ arr = asarray(item)
+ assert_equal(_datacopied(arr, item), status,
+ err_msg=repr(item))
+
+
+def test_aligned_mem_float():
+ """Check linalg works with non-aligned memory (float32)"""
+ # Allocate 402 bytes of memory (allocated on boundary)
+ a = arange(402, dtype=np.uint8)
+
+ # Create an array with boundary offset 4
+ z = np.frombuffer(a.data, offset=2, count=100, dtype=float32)
+ z = z.reshape((10, 10))
+
+ eig(z, overwrite_a=True)
+ eig(z.T, overwrite_a=True)
+
+
+@pytest.mark.skipif(platform.machine() == 'ppc64le',
+ reason="crashes on ppc64le")
+def test_aligned_mem():
+ """Check linalg works with non-aligned memory (float64)"""
+ # Allocate 804 bytes of memory (allocated on boundary)
+ a = arange(804, dtype=np.uint8)
+
+ # Create an array with boundary offset 4
+ z = np.frombuffer(a.data, offset=4, count=100, dtype=float)
+ z = z.reshape((10, 10))
+
+ eig(z, overwrite_a=True)
+ eig(z.T, overwrite_a=True)
+
+
+def test_aligned_mem_complex():
+ """Check that complex objects don't need to be completely aligned"""
+ # Allocate 1608 bytes of memory (allocated on boundary)
+ a = zeros(1608, dtype=np.uint8)
+
+ # Create an array with boundary offset 8
+ z = np.frombuffer(a.data, offset=8, count=100, dtype=complex)
+ z = z.reshape((10, 10))
+
+ eig(z, overwrite_a=True)
+ # This does not need special handling
+ eig(z.T, overwrite_a=True)
+
+
+def check_lapack_misaligned(func, args, kwargs):
+ args = list(args)
+ for i in range(len(args)):
+ a = args[:]
+ if isinstance(a[i], np.ndarray):
+ # Try misaligning a[i]
+ aa = np.zeros(a[i].size*a[i].dtype.itemsize+8, dtype=np.uint8)
+ aa = np.frombuffer(aa.data, offset=4, count=a[i].size,
+ dtype=a[i].dtype)
+ aa = aa.reshape(a[i].shape)
+ aa[...] = a[i]
+ a[i] = aa
+ func(*a, **kwargs)
+ if len(a[i].shape) > 1:
+ a[i] = a[i].T
+ func(*a, **kwargs)
+
+
+@pytest.mark.xfail(run=False,
+ reason="Ticket #1152, triggers a segfault in rare cases.")
+def test_lapack_misaligned():
+ M = np.eye(10, dtype=float)
+ R = np.arange(100).reshape((10, 10))
+ S = np.arange(20000, dtype=np.uint8)
+ S = np.frombuffer(S.data, offset=4, count=100, dtype=float)
+ S = S.reshape((10, 10))
+ b = np.ones(10)
+ LU, piv = lu_factor(S)
+ for (func, args, kwargs) in [
+ (eig, (S,), dict(overwrite_a=True)), # crash
+ (eigvals, (S,), dict(overwrite_a=True)), # no crash
+ (lu, (S,), dict(overwrite_a=True)), # no crash
+ (lu_factor, (S,), dict(overwrite_a=True)), # no crash
+ (lu_solve, ((LU, piv), b), dict(overwrite_b=True)),
+ (solve, (S, b), dict(overwrite_a=True, overwrite_b=True)),
+ (svd, (M,), dict(overwrite_a=True)), # no crash
+ (svd, (R,), dict(overwrite_a=True)), # no crash
+ (svd, (S,), dict(overwrite_a=True)), # crash
+ (svdvals, (S,), dict()), # no crash
+ (svdvals, (S,), dict(overwrite_a=True)), # crash
+ (cholesky, (M,), dict(overwrite_a=True)), # no crash
+ (qr, (S,), dict(overwrite_a=True)), # crash
+ (rq, (S,), dict(overwrite_a=True)), # crash
+ (hessenberg, (S,), dict(overwrite_a=True)), # crash
+ (schur, (S,), dict(overwrite_a=True)), # crash
+ ]:
+ check_lapack_misaligned(func, args, kwargs)
+# not properly tested
+# cholesky, rsf2csf, lu_solve, solve, eig_banded, eigvals_banded, eigh, diagsvd
+
+
+class TestOverwrite:
+ def test_eig(self):
+ assert_no_overwrite(eig, [(3, 3)])
+ assert_no_overwrite(eig, [(3, 3), (3, 3)])
+
+ def test_eigh(self):
+ assert_no_overwrite(eigh, [(3, 3)])
+ assert_no_overwrite(eigh, [(3, 3), (3, 3)])
+
+ def test_eig_banded(self):
+ assert_no_overwrite(eig_banded, [(3, 2)])
+
+ def test_eigvals(self):
+ assert_no_overwrite(eigvals, [(3, 3)])
+
+ def test_eigvalsh(self):
+ assert_no_overwrite(eigvalsh, [(3, 3)])
+
+ def test_eigvals_banded(self):
+ assert_no_overwrite(eigvals_banded, [(3, 2)])
+
+ def test_hessenberg(self):
+ assert_no_overwrite(hessenberg, [(3, 3)])
+
+ def test_lu_factor(self):
+ assert_no_overwrite(lu_factor, [(3, 3)])
+
+ def test_lu_solve(self):
+ x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]])
+ xlu = lu_factor(x)
+ assert_no_overwrite(lambda b: lu_solve(xlu, b), [(3,)])
+
+ def test_lu(self):
+ assert_no_overwrite(lu, [(3, 3)])
+
+ def test_qr(self):
+ assert_no_overwrite(qr, [(3, 3)])
+
+ def test_rq(self):
+ assert_no_overwrite(rq, [(3, 3)])
+
+ def test_schur(self):
+ assert_no_overwrite(schur, [(3, 3)])
+
+ def test_schur_complex(self):
+ assert_no_overwrite(lambda a: schur(a, 'complex'), [(3, 3)],
+ dtypes=[np.float32, np.float64])
+
+ def test_svd(self):
+ assert_no_overwrite(svd, [(3, 3)])
+ assert_no_overwrite(lambda a: svd(a, lapack_driver='gesvd'), [(3, 3)])
+
+ def test_svdvals(self):
+ assert_no_overwrite(svdvals, [(3, 3)])
+
+
+def _check_orth(n, dtype, skip_big=False):
+ X = np.ones((n, 2), dtype=float).astype(dtype)
+
+ eps = np.finfo(dtype).eps
+ tol = 1000 * eps
+
+ Y = orth(X)
+ assert_equal(Y.shape, (n, 1))
+ assert_allclose(Y, Y.mean(), atol=tol, rtol=1.4e-7)
+
+ Y = orth(X.T)
+ assert_equal(Y.shape, (2, 1))
+ assert_allclose(Y, Y.mean(), atol=tol)
+
+ if n > 5 and not skip_big:
+ rng = np.random.RandomState(1)
+ X = rng.rand(n, 5) @ rng.rand(5, n)
+ X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n)
+ X = X.astype(dtype)
+
+ Y = orth(X, rcond=1e-3)
+ assert_equal(Y.shape, (n, 5))
+
+ Y = orth(X, rcond=1e-6)
+ assert_equal(Y.shape, (n, 5 + 1))
+
+
+@pytest.mark.slow
+@pytest.mark.skipif(np.dtype(np.intp).itemsize < 8,
+ reason="test only on 64-bit, else too slow")
+def test_orth_memory_efficiency():
+ # Pick n so that 16*n bytes is reasonable but 8*n*n bytes is unreasonable.
+ # Keep in mind that @pytest.mark.slow tests are likely to be running
+ # under configurations that support 4Gb+ memory for tests related to
+ # 32 bit overflow.
+ n = 10*1000*1000
+ try:
+ _check_orth(n, np.float64, skip_big=True)
+ except MemoryError as e:
+ raise AssertionError(
+ 'memory error perhaps caused by orth regression'
+ ) from e
+
+
+def test_orth():
+ dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+ sizes = [1, 2, 3, 10, 100]
+ for dt, n in itertools.product(dtypes, sizes):
+ _check_orth(n, dt)
+
+@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+def test_orth_empty(dt):
+ a = np.empty((0, 0), dtype=dt)
+ a0 = np.eye(2, dtype=dt)
+
+ oa = orth(a)
+ assert oa.dtype == orth(a0).dtype
+ assert oa.shape == (0, 0)
+
+
+class TestNullSpace:
+ def test_null_space(self):
+ rng = np.random.RandomState(1)
+
+ dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+ sizes = [1, 2, 3, 10, 100]
+
+ for dt, n in itertools.product(dtypes, sizes):
+ X = np.ones((2, n), dtype=dt)
+
+ eps = np.finfo(dt).eps
+ tol = 1000 * eps
+
+ Y = null_space(X)
+ assert_equal(Y.shape, (n, n-1))
+ assert_allclose(X @ Y, 0, atol=tol)
+
+ Y = null_space(X.T)
+ assert_equal(Y.shape, (2, 1))
+ assert_allclose(X.T @ Y, 0, atol=tol)
+
+ X = rng.randn(1 + n//2, n)
+ Y = null_space(X)
+ assert_equal(Y.shape, (n, n - 1 - n//2))
+ assert_allclose(X @ Y, 0, atol=tol)
+
+ if n > 5:
+ rng = np.random.RandomState(1)
+ X = rng.rand(n, 5) @ rng.rand(5, n)
+ X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n)
+ X = X.astype(dt)
+
+ Y = null_space(X, rcond=1e-3)
+ assert_equal(Y.shape, (n, n - 5))
+
+ Y = null_space(X, rcond=1e-6)
+ assert_equal(Y.shape, (n, n - 6))
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_null_space_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ a0 = np.eye(2, dtype=dt)
+ nsa = null_space(a)
+
+ assert nsa.shape == (0, 0)
+ assert nsa.dtype == null_space(a0).dtype
+
+ @pytest.mark.parametrize("overwrite_a", [True, False])
+ @pytest.mark.parametrize("check_finite", [True, False])
+ @pytest.mark.parametrize("lapack_driver", ["gesdd", "gesvd"])
+ def test_null_space_options(self, overwrite_a, check_finite, lapack_driver):
+ rng = np.random.default_rng(42887289350573064398746)
+ n = 10
+ X = rng.standard_normal((1 + n//2, n))
+ Y = null_space(X.copy(), overwrite_a=overwrite_a, check_finite=check_finite,
+ lapack_driver=lapack_driver)
+ assert_allclose(X @ Y, 0, atol=np.finfo(X.dtype).eps*100)
+
+
+def test_subspace_angles():
+ H = hadamard(8, float)
+ A = H[:, :3]
+ B = H[:, 3:]
+ assert_allclose(subspace_angles(A, B), [np.pi / 2.] * 3, atol=1e-14)
+ assert_allclose(subspace_angles(B, A), [np.pi / 2.] * 3, atol=1e-14)
+ for x in (A, B):
+ assert_allclose(subspace_angles(x, x), np.zeros(x.shape[1]),
+ atol=1e-14)
+ # From MATLAB function "subspace", which effectively only returns the
+ # last value that we calculate
+ x = np.array(
+ [[0.537667139546100, 0.318765239858981, 3.578396939725760, 0.725404224946106], # noqa: E501
+ [1.833885014595086, -1.307688296305273, 2.769437029884877, -0.063054873189656], # noqa: E501
+ [-2.258846861003648, -0.433592022305684, -1.349886940156521, 0.714742903826096], # noqa: E501
+ [0.862173320368121, 0.342624466538650, 3.034923466331855, -0.204966058299775]]) # noqa: E501
+ expected = 1.481454682101605
+ assert_allclose(subspace_angles(x[:, :2], x[:, 2:])[0], expected,
+ rtol=1e-12)
+ assert_allclose(subspace_angles(x[:, 2:], x[:, :2])[0], expected,
+ rtol=1e-12)
+ expected = 0.746361174247302
+ assert_allclose(subspace_angles(x[:, :2], x[:, [2]]), expected, rtol=1e-12)
+ assert_allclose(subspace_angles(x[:, [2]], x[:, :2]), expected, rtol=1e-12)
+ expected = 0.487163718534313
+ assert_allclose(subspace_angles(x[:, :3], x[:, [3]]), expected, rtol=1e-12)
+ assert_allclose(subspace_angles(x[:, [3]], x[:, :3]), expected, rtol=1e-12)
+ expected = 0.328950515907756
+ assert_allclose(subspace_angles(x[:, :2], x[:, 1:]), [expected, 0],
+ atol=1e-12)
+ # Degenerate conditions
+ assert_raises(ValueError, subspace_angles, x[0], x)
+ assert_raises(ValueError, subspace_angles, x, x[0])
+ assert_raises(ValueError, subspace_angles, x[:-1], x)
+
+ # Test branch if mask.any is True:
+ A = np.array([[1, 0, 0],
+ [0, 1, 0],
+ [0, 0, 1],
+ [0, 0, 0],
+ [0, 0, 0]])
+ B = np.array([[1, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 1]])
+ expected = np.array([np.pi/2, 0, 0])
+ assert_allclose(subspace_angles(A, B), expected, rtol=1e-12)
+
+ # Complex
+ # second column in "b" does not affect result, just there so that
+ # b can have more cols than a, and vice-versa (both conditional code paths)
+ a = [[1 + 1j], [0]]
+ b = [[1 - 1j, 0], [0, 1]]
+ assert_allclose(subspace_angles(a, b), 0., atol=1e-14)
+ assert_allclose(subspace_angles(b, a), 0., atol=1e-14)
+
+ # Empty
+ a = np.empty((0, 0))
+ b = np.empty((0, 0))
+ assert_allclose(subspace_angles(a, b), np.empty((0,)))
+ a = np.empty((2, 0))
+ b = np.empty((2, 0))
+ assert_allclose(subspace_angles(a, b), np.empty((0,)))
+ a = np.empty((0, 2))
+ b = np.empty((0, 3))
+ assert_allclose(subspace_angles(a, b), np.empty((0,)))
+
+
+class TestCDF2RDF:
+
+ def matmul(self, a, b):
+ return np.einsum('...ij,...jk->...ik', a, b)
+
+ def assert_eig_valid(self, w, v, x):
+ assert_array_almost_equal(
+ self.matmul(v, w),
+ self.matmul(x, v)
+ )
+
+ def test_single_array0x0real(self):
+ # eig doesn't support 0x0 in old versions of numpy
+ X = np.empty((0, 0))
+ w, v = np.empty(0), np.empty((0, 0))
+ wr, vr = cdf2rdf(w, v)
+ self.assert_eig_valid(wr, vr, X)
+
+ def test_single_array2x2_real(self):
+ X = np.array([[1, 2], [3, -1]])
+ w, v = np.linalg.eig(X)
+ wr, vr = cdf2rdf(w, v)
+ self.assert_eig_valid(wr, vr, X)
+
+ def test_single_array2x2_complex(self):
+ X = np.array([[1, 2], [-2, 1]])
+ w, v = np.linalg.eig(X)
+ wr, vr = cdf2rdf(w, v)
+ self.assert_eig_valid(wr, vr, X)
+
+ def test_single_array3x3_real(self):
+ X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+ w, v = np.linalg.eig(X)
+ wr, vr = cdf2rdf(w, v)
+ self.assert_eig_valid(wr, vr, X)
+
+ def test_single_array3x3_complex(self):
+ X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+ w, v = np.linalg.eig(X)
+ wr, vr = cdf2rdf(w, v)
+ self.assert_eig_valid(wr, vr, X)
+
+ def test_random_1d_stacked_arrays(self):
+ rng = np.random.default_rng(1234)
+ # cannot test M == 0 due to bug in old numpy
+ for M in range(1, 7):
+ X = rng.random((100, M, M))
+ w, v = np.linalg.eig(X)
+ wr, vr = cdf2rdf(w, v)
+ self.assert_eig_valid(wr, vr, X)
+
+ def test_random_2d_stacked_arrays(self):
+ rng = np.random.default_rng(1234)
+ # cannot test M == 0 due to bug in old numpy
+ for M in range(1, 7):
+ X = rng.random((10, 10, M, M))
+ w, v = np.linalg.eig(X)
+ wr, vr = cdf2rdf(w, v)
+ self.assert_eig_valid(wr, vr, X)
+
+ def test_low_dimensionality_error(self):
+ w, v = np.empty(()), np.array((2,))
+ assert_raises(ValueError, cdf2rdf, w, v)
+
+ def test_not_square_error(self):
+ # Check that passing a non-square array raises a ValueError.
+ w, v = np.arange(3), np.arange(6).reshape(3, 2)
+ assert_raises(ValueError, cdf2rdf, w, v)
+
+ def test_swapped_v_w_error(self):
+ # Check that exchanging places of w and v raises ValueError.
+ X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+ w, v = np.linalg.eig(X)
+ assert_raises(ValueError, cdf2rdf, v, w)
+
+ def test_non_associated_error(self):
+ # Check that passing non-associated eigenvectors raises a ValueError.
+ w, v = np.arange(3), np.arange(16).reshape(4, 4)
+ assert_raises(ValueError, cdf2rdf, w, v)
+
+ def test_not_conjugate_pairs(self):
+ # Check that passing non-conjugate pairs raises a ValueError.
+ X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]])
+ w, v = np.linalg.eig(X)
+ assert_raises(ValueError, cdf2rdf, w, v)
+
+ # different arrays in the stack, so not conjugate
+ X = np.array([
+ [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]],
+ [[1, 2, 3], [1, 2, 3], [2, 5, 6-1j]],
+ ])
+ w, v = np.linalg.eig(X)
+ assert_raises(ValueError, cdf2rdf, w, v)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cholesky.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce1057d8d7e387869c11d6b4efd32cc21fd392ef
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
@@ -0,0 +1,452 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+
+from numpy import array, transpose, zeros_like, empty
+from scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded,
+ cho_factor, cho_solve, LinAlgError)
+
+from scipy.linalg._testutils import assert_no_overwrite
+from .test_basic import parametrize_overwrite_arg
+
+
+class TestCholesky:
+
+ def test_simple(self):
+ a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+ c = cholesky(a)
+ assert_allclose(c.T @ c, a, atol=1e-14)
+ c = transpose(c)
+ a = c @ c.T
+ assert_allclose(cholesky(a, lower=1), c, atol=1e-14)
+
+ def test_check_finite(self):
+ a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+ c = cholesky(a, check_finite=False)
+ assert_allclose(c.T @ c, a, atol=1e-14)
+ c = transpose(c)
+ a = c @ c.T
+ assert_allclose(cholesky(a, lower=1, check_finite=False), c, atol=1e-14)
+
+ def test_simple_complex(self):
+ m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]])
+ a = np.conj(m.T) @ m
+ c = cholesky(a)
+ a1 = np.conj(c.T) @ c
+ assert_allclose(a, a1)
+ c = transpose(c)
+ a = c @ np.conj(c.T)
+ assert_allclose(cholesky(a, lower=1), c, atol=1e-14)
+
+ @pytest.mark.parametrize("n", [5, 10, 20])
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
+ np.complex64, np.complex128])
+ @pytest.mark.parametrize("order", ["F", "C"])
+ def test_random(self, n, dtype, order):
+ atol = 5e-4 if dtype in [np.float32, np.complex64] else 1e-12
+ rng = np.random.default_rng(seed=12345)
+
+ for k in range(2):
+ m = rng.normal(size=(n, n)).astype(dtype)
+ if np.issubdtype(dtype, np.complexfloating):
+ m += 1j * rng.normal(size=(n, n)).astype(dtype)
+ for i in range(n):
+ m[i, i] = 20*(.1+m[i, i])
+
+ a = np.asarray(np.conj(m.T) @ m, order=order)
+
+ c = cholesky(a, lower=0)
+ a1 = np.conj(c.T) @ c
+ assert_allclose(a, a1, atol=atol)
+
+ c = transpose(c)
+ a = c @ np.conj(c.T)
+ assert_allclose(cholesky(a, lower=1), c, atol=atol)
+
+ @pytest.mark.xslow
+ def test_int_overflow(self):
+ # regression test for
+ # https://github.com/scipy/scipy/issues/17436
+ # the problem was an int overflow in zeroing out
+ # the unused triangular part
+ n = 47_000
+ x = np.eye(n, dtype=np.float64, order='F')
+ x[:4, :4] = np.array([[4, -2, 3, -1],
+ [-2, 4, -3, 1],
+ [3, -3, 5, 0],
+ [-1, 1, 0, 5]])
+
+ cholesky(x, check_finite=False, overwrite_a=True) # should not segfault
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt, dt_b):
+ a = empty((0, 0), dtype=dt)
+
+ c = cholesky(a)
+ assert c.shape == (0, 0)
+ assert c.dtype == cholesky(np.eye(2, dtype=dt)).dtype
+
+ c_and_lower = (c, True)
+ b = np.asarray([], dtype=dt_b)
+ x = cho_solve(c_and_lower, b)
+ assert x.shape == (0,)
+ assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
+ np.ones(2, dtype=dt_b)).dtype
+
+ b = empty((0, 0), dtype=dt_b)
+ x = cho_solve(c_and_lower, b)
+ assert x.shape == (0, 0)
+ assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
+ np.ones(2, dtype=dt_b)).dtype
+
+ a1 = array([])
+ a2 = array([[]])
+ a3 = []
+ a4 = [[]]
+ for x in ([a1, a2, a3, a4]):
+ assert_raises(ValueError, cholesky, x)
+
+ @pytest.mark.parametrize("shape", [(3,), (2, 3), (3, 2)])
+ def test_invalid_shape(self, shape):
+ rng = np.random.default_rng(seed=12345)
+ a = rng.normal(size=shape)
+
+ with pytest.raises(ValueError, match="Expected a square matrix"):
+ cholesky(a)
+
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
+ np.complex64, np.complex128])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ def test_non_posdef(self, dtype, order):
+ n = 10
+ rng = np.random.default_rng(seed=12345)
+
+ lmbd = np.diag(-np.abs(rng.normal(size=(n,))).astype(dtype))
+ x = rng.normal(size=(n, n)).astype(dtype)
+ if np.issubdtype(dtype, np.complexfloating):
+ x += 1j * rng.normal(size=(n, n)).astype(dtype)
+
+ a = np.asarray(x @ lmbd @ np.conj(x.T), order=order)
+
+ with pytest.raises(LinAlgError, match="Internal potrf return info"):
+ cholesky(a)
+
+ @parametrize_overwrite_arg
+ @pytest.mark.parametrize("dtype", [int, float])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ def test_overwrite_args(self, overwrite_kw, dtype, order):
+ rng = np.random.default_rng(seed=12345)
+ n = 5
+
+ x = rng.normal(size=(n, n))
+ x = x.astype(dtype)
+ a = x @ x.T
+ a = a.astype(dtype, order=order)
+ a_ref = np.copy(a)
+
+ c = cholesky(a, **overwrite_kw)
+ overwrite_a = overwrite_kw.get("overwrite_a", False)
+ a_inplace = (overwrite_a and (dtype is not int)
+ and (a.flags["F_CONTIGUOUS"] or a.flags["C_CONTIGUOUS"]))
+
+ assert np.shares_memory(a, c) == a_inplace
+ assert np.all(a == a_ref) != a_inplace
+
+ @pytest.mark.parametrize("lower", [True, False])
+ def test_overwrite_cleaning(self, lower):
+ # Since only half the array is copied over, this checks if the other
+ # half is correctly put to 0 when the input array is passed in instead.
+ rng = np.random.default_rng(seed=12345)
+ n = 5
+
+ x = rng.normal(size=(n, n))
+ a = np.asfortranarray(x @ x.T)
+ a_ref = np.copy(a)
+
+ c = cholesky(a, lower=lower, overwrite_a=True)
+
+ if lower:
+ assert_allclose(np.triu(a, k=1), np.zeros_like(a), atol=1e-14)
+ assert_allclose(c @ c.T, a_ref, atol=1e-14)
+ else:
+ assert_allclose(np.tril(a, k=-1), np.zeros_like(a), atol=1e-14)
+ assert_allclose(c.T @ c, a_ref, atol=1e-14)
+
+ @pytest.mark.parametrize("lower", [True, False])
+ @pytest.mark.parametrize("order", ['C', 'F', 'noncontig_C', 'noncontig_F'])
+ @pytest.mark.parametrize("overwrite_a", [True, False])
+ @pytest.mark.parametrize("dtype", [np.float64, np.complex128])
+ def test_nan_in_unused_triangle(self, lower, order, overwrite_a, dtype):
+ # The unused triangle should never be read, so NaN there must not
+ # affect the result.
+ rng = np.random.default_rng(seed=12345)
+ n = 5
+ x = rng.normal(size=(n, n))
+ if np.issubdtype(dtype, np.complexfloating):
+ x = x + 1j * rng.normal(size=(n, n))
+ a = (x @ x.conj().T + n * np.eye(n)).astype(dtype)
+ c_ref = cholesky(a, lower=lower)
+
+ # Prepare the array in the desired layout
+ if order.startswith('noncontig'):
+ # Unequal strides to probe strided path thoroughly
+ big_order = 'F' if order.endswith('_F') else 'C'
+ a_big = np.zeros((2*n, 3*n), dtype=dtype, order=big_order)
+ a_big[::2, ::3] = a
+ a_nan = a_big[::2, ::3] # non-contiguous view
+ assert not a_nan.flags['C_CONTIGUOUS']
+ assert not a_nan.flags['F_CONTIGUOUS']
+ else:
+ a_nan = np.array(a, order=order)
+
+ # Put NaN in the unused triangle
+ if lower:
+ a_nan[np.triu_indices(n, 1)] = np.nan
+ else:
+ a_nan[np.tril_indices(n, -1)] = np.nan
+
+ c = cholesky(a_nan, lower=lower, overwrite_a=overwrite_a,
+ check_finite=False)
+ assert_allclose(c, c_ref, atol=1e-14)
+ # Verify reconstruction
+ if lower:
+ assert_allclose(c @ c.conj().T, a, atol=1e-13)
+ else:
+ assert_allclose(c.conj().T @ c, a, atol=1e-13)
+
+
+class TestCholeskyBanded:
+ """Tests for cholesky_banded() and cho_solve_banded."""
+
+ def test_check_finite(self):
+ # Symmetric positive definite banded matrix `a`
+ a = array([[4.0, 1.0, 0.0, 0.0],
+ [1.0, 4.0, 0.5, 0.0],
+ [0.0, 0.5, 4.0, 0.2],
+ [0.0, 0.0, 0.2, 4.0]])
+ # Banded storage form of `a`.
+ ab = array([[-1.0, 1.0, 0.5, 0.2],
+ [4.0, 4.0, 4.0, 4.0]])
+ c = cholesky_banded(ab, lower=False, check_finite=False)
+ ufac = zeros_like(a)
+ ufac[list(range(4)), list(range(4))] = c[-1]
+ ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+ assert_allclose(a, ufac.T @ ufac, atol=1e-14)
+
+ b = array([0.0, 0.5, 4.2, 4.2])
+ x = cho_solve_banded((c, False), b, check_finite=False)
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
+
+ def test_upper_real(self):
+ # Symmetric positive definite banded matrix `a`
+ a = array([[4.0, 1.0, 0.0, 0.0],
+ [1.0, 4.0, 0.5, 0.0],
+ [0.0, 0.5, 4.0, 0.2],
+ [0.0, 0.0, 0.2, 4.0]])
+ # Banded storage form of `a`.
+ ab = array([[-1.0, 1.0, 0.5, 0.2],
+ [4.0, 4.0, 4.0, 4.0]])
+ c = cholesky_banded(ab, lower=False)
+ ufac = zeros_like(a)
+ ufac[list(range(4)), list(range(4))] = c[-1]
+ ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+ assert_allclose(a, ufac.T @ ufac, atol=1e-14)
+
+ b = array([0.0, 0.5, 4.2, 4.2])
+ x = cho_solve_banded((c, False), b)
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
+
+ def test_upper_complex(self):
+ # Hermitian positive definite banded matrix `a`
+ a = array([[4.0, 1.0, 0.0, 0.0],
+ [1.0, 4.0, 0.5, 0.0],
+ [0.0, 0.5, 4.0, -0.2j],
+ [0.0, 0.0, 0.2j, 4.0]])
+ # Banded storage form of `a`.
+ ab = array([[-1.0, 1.0, 0.5, -0.2j],
+ [4.0, 4.0, 4.0, 4.0]])
+ c = cholesky_banded(ab, lower=False)
+ ufac = zeros_like(a)
+ ufac[list(range(4)), list(range(4))] = c[-1]
+ ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+ assert_allclose(a, np.conj(ufac.T) @ ufac, atol=1e-14)
+
+ b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0])
+ x = cho_solve_banded((c, False), b)
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
+
+ def test_lower_real(self):
+ # Symmetric positive definite banded matrix `a`
+ a = array([[4.0, 1.0, 0.0, 0.0],
+ [1.0, 4.0, 0.5, 0.0],
+ [0.0, 0.5, 4.0, 0.2],
+ [0.0, 0.0, 0.2, 4.0]])
+ # Banded storage form of `a`.
+ ab = array([[4.0, 4.0, 4.0, 4.0],
+ [1.0, 0.5, 0.2, -1.0]])
+ c = cholesky_banded(ab, lower=True)
+ lfac = zeros_like(a)
+ lfac[list(range(4)), list(range(4))] = c[0]
+ lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
+ assert_allclose(a, lfac @ lfac.T, atol=1e-14)
+
+ b = array([0.0, 0.5, 4.2, 4.2])
+ x = cho_solve_banded((c, True), b)
+ assert_allclose(x, [0.0, 0.0, 1.0, 1.0], atol=1e-14)
+
+ def test_lower_complex(self):
+ # Hermitian positive definite banded matrix `a`
+ a = array([[4.0, 1.0, 0.0, 0.0],
+ [1.0, 4.0, 0.5, 0.0],
+ [0.0, 0.5, 4.0, -0.2j],
+ [0.0, 0.0, 0.2j, 4.0]])
+ # Banded storage form of `a`.
+ ab = array([[4.0, 4.0, 4.0, 4.0],
+ [1.0, 0.5, 0.2j, -1.0]])
+ c = cholesky_banded(ab, lower=True)
+ lfac = zeros_like(a)
+ lfac[list(range(4)), list(range(4))] = c[0]
+ lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
+ assert_allclose(a, lfac @ np.conj(lfac.T), atol=1e-14)
+
+ b = array([0.0, 0.5j, 3.8j, 3.8])
+ x = cho_solve_banded((c, True), b)
+ assert_allclose(x, [0.0, 0.0, 1.0j, 1.0], atol=1e-14)
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt, dt_b):
+ ab = empty((0, 0), dtype=dt)
+
+ cb = cholesky_banded(ab)
+ assert cb.shape == (0, 0)
+
+ m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=dt))
+ assert cb.dtype == m.dtype
+
+ cb_and_lower = (cb, True)
+ b = np.asarray([], dtype=dt_b)
+ x = cho_solve_banded(cb_and_lower, b)
+ assert x.shape == (0,)
+
+ dtype_nonempty = cho_solve_banded((m, True), np.ones(2, dtype=dt_b)).dtype
+ assert x.dtype == dtype_nonempty
+
+ b = empty((0, 0), dtype=dt_b)
+ x = cho_solve_banded(cb_and_lower, b)
+ assert x.shape == (0, 0)
+ assert x.dtype == dtype_nonempty
+
+
+class TestOverwrite:
+ def test_cholesky(self):
+ assert_no_overwrite(cholesky, [(3, 3)])
+
+ def test_cho_factor(self):
+ assert_no_overwrite(cho_factor, [(3, 3)])
+
+ def test_cho_solve(self):
+ x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
+ xcho = cho_factor(x)
+ assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)])
+
+ def test_cholesky_banded(self):
+ assert_no_overwrite(cholesky_banded, [(2, 3)])
+
+ def test_cho_solve_banded(self):
+ x = array([[0, -1, -1], [2, 2, 2]])
+ xcho = cholesky_banded(x)
+ assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b),
+ [(3,)])
+
+
+class TestChoFactor:
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ x, lower = cho_factor(a)
+
+ assert x.shape == (0, 0)
+
+ xx, lower = cho_factor(np.eye(2, dtype=dt))
+ assert x.dtype == xx.dtype
+
+ @pytest.mark.parametrize("n", [5, 10, 20])
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
+ np.complex64, np.complex128])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ @pytest.mark.parametrize("lower", [True, False])
+ def test_random(self, n, dtype, order, lower):
+ atol = 1e-5 if dtype in [np.float32, np.complex64] else 1e-12
+ rng = np.random.default_rng(seed=12345)
+
+ lmbd = np.diag(np.abs(rng.normal(size=(n,)).astype(dtype)))
+ x = rng.normal(size=(n, n)).astype(dtype)
+ if np.issubdtype(dtype, np.complexfloating):
+ x += 1j * rng.normal(size=(n, n)).astype(dtype)
+
+ a = np.asarray(x @ lmbd @ np.conj(x.T), order=order)
+ c = cholesky(a, lower=lower)
+ c_f, lower_out = cho_factor(a, lower=lower)
+
+ assert lower_out == lower
+
+ # Theoretically exactly equal
+ # For `cho_factor` the other half of the matrix is irrelevant.
+ if lower:
+ l = np.tril(c_f)
+ assert_allclose(c, l, atol=atol)
+ assert_allclose(a, l @ np.conj(l.T), atol=atol)
+ else:
+ u = np.triu(c_f)
+ assert_allclose(c, u, atol=atol)
+ assert_allclose(a, np.conj(u.T) @ u, atol=atol)
+
+ @pytest.mark.parametrize("shape", [(3,), (3, 2), (2, 3)])
+ def test_invalid_shape(self, shape):
+ rng = np.random.default_rng(seed=12345)
+ a = rng.normal(size=shape)
+
+ with pytest.raises(ValueError, match="Expected a square matrix or batch"):
+ cho_factor(a)
+
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64,
+ np.complex64, np.complex128])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ def test_non_posdef(self, dtype, order):
+ n = 10
+ rng = np.random.default_rng(seed=12345)
+
+ lmbd = np.diag(-np.abs(rng.normal(size=(n,))).astype(dtype))
+ x = rng.normal(size=(n, n)).astype(dtype)
+ if np.issubdtype(dtype, np.complexfloating):
+ x += 1j * rng.normal(size=(n, n)).astype(dtype)
+
+ a = np.asarray(x @ lmbd @ np.conj(x.T), order=order)
+
+ with pytest.raises(LinAlgError, match="Internal potrf return info"):
+ cho_factor(a)
+
+ @parametrize_overwrite_arg
+ @pytest.mark.parametrize("dtype", [int, float])
+ @pytest.mark.parametrize("order", ["C", "F"])
+ @pytest.mark.parametrize("lower", [True, False])
+ def test_overwrite_args(self, overwrite_kw, dtype, order, lower):
+ rng = np.random.default_rng(seed=12345)
+ n = 5
+
+ x = rng.normal(size=(n, n))
+ x = x.astype(dtype)
+ a = x @ x.T
+ a = a.astype(dtype, order=order)
+ a_ref = np.copy(a)
+
+ c, lower = cho_factor(a, **overwrite_kw, lower=lower)
+ overwrite_a = overwrite_kw.get("overwrite_a", False)
+ a_inplace = (overwrite_a and (dtype is not int)
+ and (a.flags["F_CONTIGUOUS"] or a.flags["C_CONTIGUOUS"]))
+
+ assert np.shares_memory(a, c) == a_inplace
+ assert np.all(a == a_ref) != a_inplace
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cossin.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..c43d3e643d3ff6f8745386113d8a08091cb01c64
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_cossin.py
@@ -0,0 +1,314 @@
+import pytest
+import numpy as np
+from numpy.random import default_rng
+from numpy.testing import assert_allclose
+
+from scipy import linalg
+from scipy.linalg.lapack import _compute_lwork
+from scipy.stats import ortho_group, unitary_group
+from scipy.linalg import cossin, get_lapack_funcs
+
+REAL_DTYPES = (np.float32, np.float64)
+COMPLEX_DTYPES = (np.complex64, np.complex128)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+@pytest.mark.parametrize('dtype_', DTYPES)
+@pytest.mark.parametrize('m, p, q',
+ [
+ (2, 1, 1),
+ (3, 2, 1),
+ (3, 1, 2),
+ (4, 2, 2),
+ (4, 1, 2),
+ (40, 12, 20),
+ (40, 30, 1),
+ (40, 1, 30),
+ (100, 50, 1),
+ (100, 50, 50),
+ ])
+@pytest.mark.parametrize('swap_sign', [True, False])
+def test_cossin(dtype_, m, p, q, swap_sign):
+ rng = default_rng(1708093570726217)
+ if dtype_ in COMPLEX_DTYPES:
+ x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_)
+ else:
+ x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_)
+
+ u, cs, vh = cossin(x, p, q,
+ swap_sign=swap_sign)
+ assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
+ assert u.dtype == dtype_
+ # Test for float32 or float 64
+ assert cs.dtype == np.real(u).dtype
+ assert vh.dtype == dtype_
+
+ u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]],
+ swap_sign=swap_sign)
+ assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
+ assert u.dtype == dtype_
+ assert cs.dtype == np.real(u).dtype
+ assert vh.dtype == dtype_
+
+ _, cs2, vh2 = cossin(x, p, q,
+ compute_u=False,
+ swap_sign=swap_sign)
+ assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+ assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+ u2, cs2, _ = cossin(x, p, q,
+ compute_vh=False,
+ swap_sign=swap_sign)
+ assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps)
+ assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+ _, cs2, _ = cossin(x, p, q,
+ compute_u=False,
+ compute_vh=False,
+ swap_sign=swap_sign)
+ assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+
+def test_cossin_mixed_types():
+ rng = default_rng(1708093736390459)
+ x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64)
+ u, cs, vh = cossin([x[:2, :2],
+ np.array(x[:2, 2:], dtype=np.complex128),
+ x[2:, :2],
+ x[2:, 2:]])
+
+ assert u.dtype == np.complex128
+ assert cs.dtype == np.float64
+ assert vh.dtype == np.complex128
+ assert_allclose(x, u @ cs @ vh, rtol=0.,
+ atol=1e4 * np.finfo(np.complex128).eps)
+
+
+def test_cossin_error_incorrect_subblocks():
+ with pytest.raises(ValueError, match="be due to missing p, q arguments."):
+ cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10]))
+
+
+def test_cossin_error_empty_subblocks():
+ with pytest.raises(ValueError, match="x11.*empty"):
+ cossin(([], [], [], []))
+ with pytest.raises(ValueError, match="x12.*empty"):
+ cossin(([1, 2], [], [6, 7], [8, 9, 10]))
+ with pytest.raises(ValueError, match="x21.*empty"):
+ cossin(([1, 2], [3, 4, 5], [], [8, 9, 10]))
+ with pytest.raises(ValueError, match="x22.*empty"):
+ cossin(([1, 2], [3, 4, 5], [2], []))
+
+
+def test_cossin_error_missing_partitioning():
+ with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"):
+ cossin(unitary_group.rvs(2))
+
+ with pytest.raises(ValueError, match=".*might be due to missing p, q"):
+ cossin(unitary_group.rvs(4))
+
+
+def test_cossin_error_non_iterable():
+ with pytest.raises(ValueError, match="containing the subblocks of X"):
+ cossin(12j)
+
+def test_cossin_error_invalid_shape():
+ # Invalid x12 dimensions
+ p, q = 3, 4
+ invalid_x12 = np.ones((p, q + 2))
+ valid_ones = np.ones((p, q))
+ with pytest.raises(ValueError,
+ match=r"Invalid x12 dimensions: desired \(3, 4\), got \(3, 6\)"):
+ cossin((valid_ones, invalid_x12, valid_ones, valid_ones))
+
+ # Invalid x21 dimensions
+ invalid_x21 = np.ones(p + 2)
+ with pytest.raises(ValueError,
+ match=r"Invalid x21 dimensions: desired \(3, 4\), got \(1, 5\)"):
+ cossin((valid_ones, valid_ones, invalid_x21, valid_ones))
+
+def test_cossin_error_non_square():
+ with pytest.raises(ValueError, match="only supports square"):
+ cossin(np.array([[1, 2]]), 1, 1)
+
+
+def test_cossin_error_partitioning():
+ x = np.array(ortho_group.rvs(4), dtype=np.float64)
+ with pytest.raises(ValueError, match="invalid p=0.*0
= m) or (q >= m):
+ pytest.skip("`0 < p < m` and `0 < q < m` must hold")
+
+ # Generate unitary input
+ rng = np.random.default_rng(329548272348596421)
+ X = unitary_group.rvs(m, random_state=rng)
+ np.testing.assert_allclose(X @ X.conj().T, np.eye(m), atol=1e-15)
+
+ # Perform the decomposition
+ u0, cs0, vh0 = linalg.cossin(X, p=p, q=q, separate=True, swap_sign=swap_sign)
+ u1, u2 = u0
+ v1, v2 = vh0
+ v1, v2 = v1.conj().T, v2.conj().T
+
+ # "U1, U2, V1, V2 are square orthogonal/unitary matrices
+ # of dimensions (p,p), (m-p,m-p), (q,q), and (m-q,m-q) respectively"
+ np.testing.assert_allclose(u1 @ u1.conj().T, np.eye(p), atol=1e-13)
+ np.testing.assert_allclose(u2 @ u2.conj().T, np.eye(m-p), atol=1e-13)
+ np.testing.assert_allclose(v1 @ v1.conj().T, np.eye(q), atol=1e-13)
+ np.testing.assert_allclose(v2 @ v2.conj().T, np.eye(m-q), atol=1e-13)
+
+ # "and C and S are (r, r) nonnegative diagonal matrices..."
+ C = np.diag(np.cos(cs0))
+ S = np.diag(np.sin(cs0))
+ # "...satisfying C^2 + S^2 = I where r = min(p, m-p, q, m-q)."
+ r = min(p, m-p, q, m-q)
+ np.testing.assert_allclose(C**2 + S**2, np.eye(r))
+
+ # "Moreover, the rank of the identity matrices are
+ # min(p, q) - r, min(p, m - q) - r, min(m - p, q) - r,
+ # and min(m - p, m - q) - r respectively."
+ I11 = np.eye(min(p, q) - r)
+ I12 = np.eye(min(p, m - q) - r)
+ I21 = np.eye(min(m - p, q) - r)
+ I22 = np.eye(min(m - p, m - q) - r)
+
+ # From:
+ # ┌ ┐
+ # │ I 0 0 │ 0 0 0 │
+ # ┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐*
+ # │ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │
+ # │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│
+ # │ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │
+ # └ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘
+ # │ 0 0 I │ 0 0 0 │
+ # └ ┘
+
+ # We can see that U and V are block diagonal matrices like so:
+ U = linalg.block_diag(u1, u2)
+ V = linalg.block_diag(v1, v2)
+
+ # And the center matrix, which we'll call Q here, must be:
+ Q11 = np.zeros((u1.shape[1], v1.shape[0]))
+ IC11 = linalg.block_diag(I11, C)
+ Q11[:IC11.shape[0], :IC11.shape[1]] = IC11
+
+ Q12 = np.zeros((u1.shape[1], v2.shape[0]))
+ SI12 = linalg.block_diag(S, I12) if swap_sign else linalg.block_diag(-S, -I12)
+ Q12[-SI12.shape[0]:, -SI12.shape[1]:] = SI12
+
+ Q21 = np.zeros((u2.shape[1], v1.shape[0]))
+ SI21 = linalg.block_diag(-S, -I21) if swap_sign else linalg.block_diag(S, I21)
+ Q21[-SI21.shape[0]:, -SI21.shape[1]:] = SI21
+
+ Q22 = np.zeros((u2.shape[1], v2.shape[0]))
+ IC22 = linalg.block_diag(I22, C)
+ Q22[:IC22.shape[0], :IC22.shape[1]] = IC22
+
+ Q = np.block([[Q11, Q12], [Q21, Q22]])
+
+ # Confirm that `cossin` decomposes `X` as shown
+ np.testing.assert_allclose(X, U @ Q @ V.conj().T)
+
+ # And check that `separate=False` agrees
+ U0, CS0, Vh0 = linalg.cossin(X, p=p, q=q, swap_sign=swap_sign)
+ np.testing.assert_allclose(U, U0)
+ np.testing.assert_allclose(Q, CS0)
+ np.testing.assert_allclose(V, Vh0.conj().T)
+
+ # Confirm that `compute_u`/`compute_vh` don't affect the results
+ kwargs = dict(p=p, q=q, swap_sign=swap_sign)
+
+ # `compute_u=False`
+ u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, **kwargs)
+ assert u[0].shape == (0, 0) # probably not ideal, but this is what it does
+ assert u[1].shape == (0, 0)
+ assert_allclose(cs, cs0, rtol=1e-15)
+ assert_allclose(vh[0], vh0[0], rtol=1e-15)
+ assert_allclose(vh[1], vh0[1], rtol=1e-15)
+
+ U, CS, Vh = linalg.cossin(X, compute_u=False, **kwargs)
+ assert U.shape == (0, 0)
+ assert_allclose(CS, CS0, rtol=1e-15)
+ assert_allclose(Vh, Vh0, rtol=1e-15)
+
+ # `compute_vh=False`
+ u, cs, vh = linalg.cossin(X, separate=True, compute_vh=False, **kwargs)
+ assert_allclose(u[0], u[0], rtol=1e-15)
+ assert_allclose(u[1], u[1], rtol=1e-15)
+ assert_allclose(cs, cs0, rtol=1e-15)
+ assert vh[0].shape == (0, 0)
+ assert vh[1].shape == (0, 0)
+
+ U, CS, Vh = linalg.cossin(X, compute_vh=False, **kwargs)
+ assert_allclose(U, U0, rtol=1e-15)
+ assert_allclose(CS, CS0, rtol=1e-15)
+ assert Vh.shape == (0, 0)
+
+ # `compute_u=False, compute_vh=False`
+ u, cs, vh = linalg.cossin(X, separate=True, compute_u=False,
+ compute_vh=False, **kwargs)
+ assert u[0].shape == (0, 0)
+ assert u[1].shape == (0, 0)
+ assert_allclose(cs, cs0, rtol=1e-15)
+ assert vh[0].shape == (0, 0)
+ assert vh[1].shape == (0, 0)
+
+ U, CS, Vh = linalg.cossin(X, compute_u=False, compute_vh=False, **kwargs)
+ assert U.shape == (0, 0)
+ assert_allclose(CS, CS0, rtol=1e-15)
+ assert Vh.shape == (0, 0)
+
+
+def test_indexing_bug_gh19365():
+ # Regression test for gh-19365, which reported a bug with `separate=False`
+ rng = np.random.default_rng(32954827234421)
+ m = rng.integers(50, high=100)
+ p = rng.integers(10, 40) # always p < m
+ q = rng.integers(m - p + 1, m - 1) # always m-p < q < m
+ X = unitary_group.rvs(m, random_state=rng) # random unitary matrix
+ U, D, Vt = linalg.cossin(X, p=p, q=q, separate=False)
+ assert np.allclose(U @ D @ Vt, X)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_ldl.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..878b405096e353334d027edd07d799c3704f0a74
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_ldl.py
@@ -0,0 +1,136 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_allclose, assert_
+from numpy import (array, eye, zeros, empty_like, empty, tril_indices_from,
+ tril, triu_indices_from, spacing, float32, float64,
+ complex64, complex128)
+from numpy.exceptions import ComplexWarning
+from scipy.linalg import ldl
+import pytest
+
+
+def test_args():
+ A = eye(3)
+ # Nonsquare array
+ with pytest.raises(ValueError):
+ ldl(A[:, :2])
+ # Complex matrix with imaginary diagonal entries with "hermitian=True"
+ with pytest.warns(ComplexWarning):
+ ldl(A*1j)
+
+
+def test_empty_array():
+ a = empty((0, 0), dtype=complex)
+ l, d, p = ldl(empty((0, 0)))
+ assert_array_almost_equal(l, empty_like(a))
+ assert_array_almost_equal(d, empty_like(a))
+ assert_array_almost_equal(p, array([], dtype=int))
+
+
+def test_simple():
+ a = array([[-0.39-0.71j, 5.14-0.64j, -7.86-2.96j, 3.80+0.92j],
+ [5.14-0.64j, 8.86+1.81j, -3.52+0.58j, 5.32-1.59j],
+ [-7.86-2.96j, -3.52+0.58j, -2.83-0.03j, -1.54-2.86j],
+ [3.80+0.92j, 5.32-1.59j, -1.54-2.86j, -0.56+0.12j]])
+ b = array([[5., 10, 1, 18],
+ [10., 2, 11, 1],
+ [1., 11, 19, 9],
+ [18., 1, 9, 0]])
+ c = array([[52., 97, 112, 107, 50],
+ [97., 114, 89, 98, 13],
+ [112., 89, 64, 33, 6],
+ [107., 98, 33, 60, 73],
+ [50., 13, 6, 73, 77]])
+
+ d = array([[2., 2, -4, 0, 4],
+ [2., -2, -2, 10, -8],
+ [-4., -2, 6, -8, -4],
+ [0., 10, -8, 6, -6],
+ [4., -8, -4, -6, 10]])
+ e = array([[-1.36+0.00j, 0+0j, 0+0j, 0+0j],
+ [1.58-0.90j, -8.87+0j, 0+0j, 0+0j],
+ [2.21+0.21j, -1.84+0.03j, -4.63+0j, 0+0j],
+ [3.91-1.50j, -1.78-1.18j, 0.11-0.11j, -1.84+0.00j]])
+ for x in (b, c, d):
+ l, d, p = ldl(x)
+ assert_allclose(l.dot(d).dot(l.T), x, atol=spacing(1000.), rtol=0)
+
+ u, d, p = ldl(x, lower=False)
+ assert_allclose(u.dot(d).dot(u.T), x, atol=spacing(1000.), rtol=0)
+
+ l, d, p = ldl(a, hermitian=False)
+ assert_allclose(l.dot(d).dot(l.T), a, atol=spacing(1000.), rtol=0)
+
+ u, d, p = ldl(a, lower=False, hermitian=False)
+ assert_allclose(u.dot(d).dot(u.T), a, atol=spacing(1000.), rtol=0)
+
+ # Use upper part for the computation and use the lower part for comparison
+ l, d, p = ldl(e.conj().T, lower=0)
+ assert_allclose(tril(l.dot(d).dot(l.conj().T)-e), zeros((4, 4)),
+ atol=spacing(1000.), rtol=0)
+
+
+def test_permutations():
+ rng = np.random.default_rng(1234)
+ for _ in range(10):
+ n = rng.integers(1, 100)
+ # Random real/complex array
+ x = rng.random((n, n)) + 0 if rng.integers(2) else rng.random((n, n))*1j
+ x = x + x.conj().T
+ x += eye(n)*rng.integers(5, 1e6)
+ l_ind = tril_indices_from(x, k=-1)
+ u_ind = triu_indices_from(x, k=1)
+
+ # Test whether permutations lead to a triangular array
+ u, d, p = ldl(x, lower=0)
+ # lower part should be zero
+ assert_(not any(u[p, :][l_ind]), f'Spin {_} failed')
+
+ l, d, p = ldl(x, lower=1)
+ # upper part should be zero
+ assert_(not any(l[p, :][u_ind]), f'Spin {_} failed')
+
+
+@pytest.mark.parametrize("dtype", [float32, float64])
+@pytest.mark.parametrize("n", [30, 150])
+def test_ldl_type_size_combinations_real(n, dtype):
+ rng = np.random.default_rng(1234)
+ msg = (f"Failed for size: {n}, dtype: {dtype}")
+
+ x = rng.random((n, n)).astype(dtype)
+ x = x + x.T
+ x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6))
+
+ l, d1, p = ldl(x)
+ u, d2, p = ldl(x, lower=0)
+ rtol = 1e-4 if dtype is float32 else 1e-10
+ assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg)
+ assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg)
+
+
+@pytest.mark.parametrize("dtype", [complex64, complex128])
+@pytest.mark.parametrize("n", [30, 150])
+def test_ldl_type_size_combinations_complex(n, dtype):
+ rng = np.random.default_rng(1234)
+ msg1 = (f"Her failed for size: {n}, dtype: {dtype}")
+ msg2 = (f"Sym failed for size: {n}, dtype: {dtype}")
+
+ # Complex hermitian upper/lower
+ x = (rng.random((n, n))+1j*rng.random((n, n))).astype(dtype)
+ x = x+x.conj().T
+ x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6))
+
+ l, d1, p = ldl(x)
+ u, d2, p = ldl(x, lower=0)
+ rtol = 2e-4 if dtype is complex64 else 1e-10
+ assert_allclose(l.dot(d1).dot(l.conj().T), x, rtol=rtol, err_msg=msg1)
+ assert_allclose(u.dot(d2).dot(u.conj().T), x, rtol=rtol, err_msg=msg1)
+
+ # Complex symmetric upper/lower
+ x = (rng.random((n, n))+1j*rng.random((n, n))).astype(dtype)
+ x = x+x.T
+ x += eye(n, dtype=dtype)*dtype(rng.integers(5, 1e6))
+
+ l, d1, p = ldl(x, hermitian=0)
+ u, d2, p = ldl(x, lower=0, hermitian=0)
+ assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg2)
+ assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg2)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_lu.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..51506d54abccf16c26b0324f0a253e0dfcf80427
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_lu.py
@@ -0,0 +1,310 @@
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from scipy.linalg import lu, lu_factor, lu_solve, get_lapack_funcs, solve
+from numpy.testing import assert_allclose, assert_array_equal, assert_equal
+from scipy.linalg.lapack import HAS_ILP64
+
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+class TestLU:
+ def setup_method(self):
+ self.rng = np.random.default_rng(1682281250228846)
+
+ def test_old_lu_smoke_tests(self):
+ "Tests from old fortran based lu test suite"
+ a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+ p, l, u = lu(a)
+ result_lu = np.array([[2., 5., 6.], [0.5, -0.5, 0.], [0.5, 1., 0.]])
+ assert_allclose(p, np.rot90(np.eye(3)))
+ assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
+ assert_allclose(u, np.triu(result_lu))
+
+ a = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
+ p, l, u = lu(a)
+ result_lu = np.array([[2., 5.j, 6.], [0.5, 2-2.5j, 0.], [0.5, 1., 0.]])
+ assert_allclose(p, np.rot90(np.eye(3)))
+ assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
+ assert_allclose(u, np.triu(result_lu))
+
+ b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ p, l, u = lu(b)
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+ assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
+ assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]]),
+ rtol=0., atol=1e-14)
+
+ cb = np.array([[1.j, 2.j, 3.j], [4j, 5j, 6j], [7j, 8j, 9j]])
+ p, l, u = lu(cb)
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+ assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
+ assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]])*1j,
+ rtol=0., atol=1e-14)
+
+ # Rectangular matrices
+ hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
+ p, l, u = lu(hrect)
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+ assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
+ assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9],
+ [0, 0, -0.5, 0]]), rtol=0., atol=1e-14)
+
+ chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])*1.j
+ p, l, u = lu(chrect)
+ assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+ assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
+ assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9, 15/9, 24/9],
+ [0, 0, -0.5, 0]])*1j, rtol=0., atol=1e-14)
+
+ vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
+ p, l, u = lu(vrect)
+ assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
+ assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1],
+ [0.4, 0.25, 0.5]]))
+ assert_allclose(u, np.array([[10, 12, 12],
+ [0, 0.8, 1.8],
+ [0, 0, 1.5]]))
+
+ cvrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])*1j
+ p, l, u = lu(cvrect)
+ assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
+ assert_allclose(l, np.array([[1., 0, 0],
+ [0.1, 1, 0],
+ [0.7, -0.5, 1],
+ [0.4, 0.25, 0.5]]))
+ assert_allclose(u, np.array([[10, 12, 12],
+ [0, 0.8, 1.8],
+ [0, 0, 1.5]])*1j)
+
+ @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
+ [20, 4], [4, 20], [3, 2, 9, 9],
+ [2, 2, 17, 5], [2, 2, 11, 7]])
+ def test_simple_lu_shapes_real_complex(self, shape):
+ a = self.rng.uniform(-10., 10., size=shape)
+ p, l, u = lu(a)
+ assert_allclose(a, p @ l @ u)
+ pl, u = lu(a, permute_l=True)
+ assert_allclose(a, pl @ u)
+
+ b = self.rng.uniform(-10., 10., size=shape)*1j
+ b += self.rng.uniform(-10, 10, size=shape)
+ pl, u = lu(b, permute_l=True)
+ assert_allclose(b, pl @ u)
+
+ @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
+ [20, 4], [4, 20]])
+ def test_simple_lu_shapes_real_complex_2d_indices(self, shape):
+ a = self.rng.uniform(-10., 10., size=shape)
+ p, l, u = lu(a, p_indices=True)
+ assert_allclose(a, l[p, :] @ u)
+
+ def test_1by1_input_output(self):
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+ p, l, u = lu(a, p_indices=True)
+ assert_allclose(p, np.zeros(shape=(4, 5, 1), dtype=int))
+ assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+ assert_allclose(u, a)
+
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+ p, l, u = lu(a)
+ assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+ assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+ assert_allclose(u, a)
+
+ pl, u = lu(a, permute_l=True)
+ assert_allclose(pl, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+ assert_allclose(u, a)
+
+ a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
+ p, l, u = lu(a)
+ assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
+ assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
+ assert_allclose(u, a)
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_empty_edge_cases(self):
+ a = np.empty([0, 0])
+ p, l, u = lu(a)
+ assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float64))
+ assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float64))
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.float64))
+
+ a = np.empty([0, 3], dtype=np.float16)
+ p, l, u = lu(a)
+ assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
+ assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float32))
+ assert_allclose(u, np.empty(shape=(0, 3), dtype=np.float32))
+
+ a = np.empty([3, 0], dtype=np.complex64)
+ p, l, u = lu(a)
+ assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
+ assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+ p, l, u = lu(a, p_indices=True)
+ assert_allclose(p, np.empty(shape=(0,), dtype=int))
+ assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+ pl, u = lu(a, permute_l=True)
+ assert_allclose(pl, np.empty(shape=(3, 0), dtype=np.complex64))
+ assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+
+ a = np.empty([3, 0, 0], dtype=np.complex64)
+ p, l, u = lu(a)
+ assert_allclose(p, np.empty(shape=(3, 0, 0), dtype=np.float32))
+ assert_allclose(l, np.empty(shape=(3, 0, 0), dtype=np.complex64))
+ assert_allclose(u, np.empty(shape=(3, 0, 0), dtype=np.complex64))
+
+ a = np.empty([0, 0, 3])
+ p, l, u = lu(a)
+ assert_allclose(p, np.empty(shape=(0, 0, 0)))
+ assert_allclose(l, np.empty(shape=(0, 0, 0)))
+ assert_allclose(u, np.empty(shape=(0, 0, 3)))
+
+ with assert_raises(ValueError, match='at least two-dimensional'):
+ lu(np.array([]))
+
+ a = np.array([[]])
+ p, l, u = lu(a)
+ assert_allclose(p, np.empty(shape=(0, 0)))
+ assert_allclose(l, np.empty(shape=(1, 0)))
+ assert_allclose(u, np.empty(shape=(0, 0)))
+
+ a = np.array([[[]]])
+ p, l, u = lu(a)
+ assert_allclose(p, np.empty(shape=(1, 0, 0)))
+ assert_allclose(l, np.empty(shape=(1, 1, 0)))
+ assert_allclose(u, np.empty(shape=(1, 0, 0)))
+
+
+class TestLUFactor:
+ def setup_method(self):
+ self.rng = np.random.default_rng(1682281250228846)
+
+ self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+ self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
+ # Those matrices are more robust to detect problems in permutation
+ # matrices than the ones above
+ self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ self.cb = np.array([[1j, 2j, 3j], [4j, 5j, 6j], [7j, 8j, 9j]])
+
+ # Rectangular matrices
+ self.hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
+ self.chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8],
+ [9, 10, 12, 12]]) * 1.j
+
+ self.vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
+ self.cvrect = 1.j * np.array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ [10, 12, 12]])
+
+ # Medium sizes matrices
+ self.med = self.rng.random((30, 40))
+ self.cmed = self.rng.random((30, 40)) + 1.j*self.rng.random((30, 40))
+
+ def _test_common_lu_factor(self, data):
+ l_and_u1, piv1 = lu_factor(data)
+ (getrf,) = get_lapack_funcs(("getrf",), (data,))
+ l_and_u2, piv2, _ = getrf(data, overwrite_a=False)
+ assert_allclose(l_and_u1, l_and_u2)
+ assert_allclose(piv1, piv2)
+
+ # Simple tests.
+ # For lu_factor gives a LinAlgWarning because these matrices are singular
+ def test_hrectangular(self):
+ self._test_common_lu_factor(self.hrect)
+
+ def test_vrectangular(self):
+ self._test_common_lu_factor(self.vrect)
+
+ def test_hrectangular_complex(self):
+ self._test_common_lu_factor(self.chrect)
+
+ def test_vrectangular_complex(self):
+ self._test_common_lu_factor(self.cvrect)
+
+ # Bigger matrices
+ def test_medium1(self):
+ """Check lu decomposition on medium size, rectangular matrix."""
+ self._test_common_lu_factor(self.med)
+
+ def test_medium1_complex(self):
+ """Check lu decomposition on medium size, rectangular matrix."""
+ self._test_common_lu_factor(self.cmed)
+
+ def test_check_finite(self):
+ p, l, u = lu(self.a, check_finite=False)
+ assert_allclose(p @ l @ u, self.a)
+
+ def test_simple_known(self):
+ # Ticket #1458
+ for order in ['C', 'F']:
+ A = np.array([[2, 1], [0, 1.]], order=order)
+ LU, P = lu_factor(A)
+ assert_allclose(LU, np.array([[2, 1], [0, 1]]))
+ assert_array_equal(P, np.array([0, 1]))
+
+ @pytest.mark.parametrize("m", [0, 1, 2])
+ @pytest.mark.parametrize("n", [0, 1, 2])
+ @pytest.mark.parametrize('dtype', DTYPES)
+ def test_shape_dtype(self, m, n, dtype):
+ k = min(m, n)
+
+ a = np.eye(m, n, dtype=dtype)
+ lu, p = lu_factor(a)
+ assert_equal(lu.shape, (m, n))
+ assert_equal(lu.dtype, dtype)
+ assert_equal(p.shape, (k,))
+ assert_equal(p.dtype, np.int64 if HAS_ILP64 else np.int32)
+
+ @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+ def test_empty(self, m, n):
+ a = np.zeros((m, n))
+ lu, p = lu_factor(a)
+ assert_allclose(lu, np.empty((m, n)))
+ assert_allclose(p, np.arange(0))
+
+
+class TestLUSolve:
+ def setup_method(self):
+ self.rng = np.random.default_rng(1682281250228846)
+
+ def test_lu(self):
+ a0 = self.rng.random((10, 10))
+ b = self.rng.random((10,))
+
+ for order in ['C', 'F']:
+ a = np.array(a0, order=order)
+ x1 = solve(a, b)
+ lu_a = lu_factor(a)
+ x2 = lu_solve(lu_a, b)
+ assert_allclose(x1, x2)
+
+ def test_check_finite(self):
+ a = self.rng.random((10, 10))
+ b = self.rng.random((10,))
+ x1 = solve(a, b)
+ lu_a = lu_factor(a, check_finite=False)
+ x2 = lu_solve(lu_a, b, check_finite=False)
+ assert_allclose(x1, x2)
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt, dt_b):
+ lu_and_piv = (np.empty((0, 0), dtype=dt), np.array([]))
+ b = np.asarray([], dtype=dt_b)
+ x = lu_solve(lu_and_piv, b)
+ assert x.shape == (0,)
+
+ m = lu_solve((np.eye(2, dtype=dt), [0, 1]), np.ones(2, dtype=dt_b))
+ assert x.dtype == m.dtype
+
+ b = np.empty((0, 0), dtype=dt_b)
+ x = lu_solve(lu_and_piv, b)
+ assert x.shape == (0, 0)
+ assert x.dtype == m.dtype
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_polar.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..607238842b3cc643d9665e40f29e41b15d8951a1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_polar.py
@@ -0,0 +1,110 @@
+import pytest
+import numpy as np
+from numpy.linalg import norm
+from numpy.testing import (assert_, assert_allclose, assert_equal)
+from scipy.linalg import polar, eigh
+
+
+diag2 = np.array([[2, 0], [0, 3]])
+a13 = np.array([[1, 2, 2]])
+
+precomputed_cases = [
+ [[[0]], 'right', [[1]], [[0]]],
+ [[[0]], 'left', [[1]], [[0]]],
+ [[[9]], 'right', [[1]], [[9]]],
+ [[[9]], 'left', [[1]], [[9]]],
+ [diag2, 'right', np.eye(2), diag2],
+ [diag2, 'left', np.eye(2), diag2],
+ [a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])],
+]
+
+verify_cases = [
+ [[1, 2], [3, 4]],
+ [[1, 2, 3]],
+ [[1], [2], [3]],
+ [[1, 2, 3], [3, 4, 0]],
+ [[1, 2], [3, 4], [5, 5]],
+ [[1, 2], [3, 4+5j]],
+ [[1, 2, 3j]],
+ [[1], [2], [3j]],
+ [[1, 2, 3+2j], [3, 4-1j, -4j]],
+ [[1, 2], [3-2j, 4+0.5j], [5, 5]],
+ [[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]],
+ np.empty((0, 0)),
+ np.empty((0, 2)),
+ np.empty((2, 0)),
+]
+
+
+def check_precomputed_polar(a, side, expected_u, expected_p):
+ # Compare the result of the polar decomposition to a
+ # precomputed result.
+ u, p = polar(a, side=side)
+ assert_allclose(u, expected_u, atol=1e-15)
+ assert_allclose(p, expected_p, atol=1e-15)
+
+
+def verify_polar(a):
+ # Compute the polar decomposition, and then verify that
+ # the result has all the expected properties.
+ product_atol = np.sqrt(np.finfo(float).eps)
+
+ aa = np.asarray(a)
+ m, n = aa.shape
+
+ u, p = polar(a, side='right')
+ assert_equal(u.shape, (m, n))
+ assert_equal(p.shape, (n, n))
+ # a = up
+ assert_allclose(u.dot(p), a, atol=product_atol)
+ if m >= n:
+ assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
+ else:
+ assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
+ # p is Hermitian positive semidefinite.
+ assert_allclose(p.conj().T, p)
+ evals = eigh(p, eigvals_only=True)
+ nonzero_evals = evals[abs(evals) > 1e-14]
+ assert_((nonzero_evals >= 0).all())
+
+ u, p = polar(a, side='left')
+ assert_equal(u.shape, (m, n))
+ assert_equal(p.shape, (m, m))
+ # a = pu
+ assert_allclose(p.dot(u), a, atol=product_atol)
+ if m >= n:
+ assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
+ else:
+ assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
+ # p is Hermitian positive semidefinite.
+ assert_allclose(p.conj().T, p)
+ evals = eigh(p, eigvals_only=True)
+ nonzero_evals = evals[abs(evals) > 1e-14]
+ assert_((nonzero_evals >= 0).all())
+
+
+def test_precomputed_cases():
+ for a, side, expected_u, expected_p in precomputed_cases:
+ check_precomputed_polar(a, side, expected_u, expected_p)
+
+
+def test_verify_cases():
+ for a in verify_cases:
+ verify_polar(a)
+
+@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+@pytest.mark.parametrize('shape', [(0, 0), (0, 2), (2, 0)])
+@pytest.mark.parametrize('side', ['left', 'right'])
+def test_empty(dt, shape, side):
+ a = np.empty(shape, dtype=dt)
+ m, n = shape
+ p_shape = (m, m) if side == 'left' else (n, n)
+
+ u, p = polar(a, side=side)
+ u_n, p_n = polar(np.eye(5, dtype=dt))
+
+ assert_equal(u.dtype, u_n.dtype)
+ assert_equal(p.dtype, p_n.dtype)
+ assert u.shape == shape
+ assert p.shape == p_shape
+ assert np.all(p == 0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_update.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_update.py
new file mode 100644
index 0000000000000000000000000000000000000000..f20266bee494f5a6cbaa9c2282782e24cc7c3e73
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_decomp_update.py
@@ -0,0 +1,1704 @@
+import itertools
+import pytest
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal
+from pytest import raises as assert_raises
+from scipy import linalg
+import scipy.linalg._decomp_update as _decomp_update
+from scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert
+
+def assert_unitary(a, rtol=None, atol=None, assert_sqr=True):
+ if rtol is None:
+ rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
+ if atol is None:
+ atol = 10*np.finfo(a.dtype).eps
+
+ if assert_sqr:
+ assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square')
+ aTa = np.dot(a.T.conj(), a)
+ assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol)
+
+def assert_upper_tri(a, rtol=None, atol=None):
+ if rtol is None:
+ rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
+ if atol is None:
+ atol = 2*np.finfo(a.dtype).eps
+ mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_)
+ assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol)
+
+def check_qr(q, r, a, rtol, atol, assert_sqr=True):
+ assert_unitary(q, rtol, atol, assert_sqr)
+ assert_upper_tri(r, rtol, atol)
+ assert_allclose(q.dot(r), a, rtol=rtol, atol=atol)
+
+def make_strided(arrs):
+ strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)]
+ kmax = len(strides)
+ k = 0
+ ret = []
+ for a in arrs:
+ if a.ndim == 1:
+ s = strides[k % kmax]
+ k += 1
+ base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype)
+ view = base[s[1]::s[0]]
+ view[...] = a
+ elif a.ndim == 2:
+ s = strides[k % kmax]
+ t = strides[(k+1) % kmax]
+ k += 2
+ base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]),
+ a.dtype)
+ view = base[s[1]::s[0], t[1]::t[0]]
+ view[...] = a
+ else:
+ raise ValueError('make_strided only works for ndim = 1 or'
+ ' 2 arrays')
+ ret.append(view)
+ return ret
+
+def negate_strides(arrs):
+ ret = []
+ for a in arrs:
+ b = np.zeros_like(a)
+ if b.ndim == 2:
+ b = b[::-1, ::-1]
+ elif b.ndim == 1:
+ b = b[::-1]
+ else:
+ raise ValueError('negate_strides only works for ndim = 1 or'
+ ' 2 arrays')
+ b[...] = a
+ ret.append(b)
+ return ret
+
+def nonitemsize_strides(arrs):
+ out = []
+ for a in arrs:
+ a_dtype = a.dtype
+ b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')])
+ c = b.getfield(a_dtype)
+ c[...] = a
+ out.append(c)
+ return out
+
+
+def make_nonnative(arrs):
+ return [a.astype(a.dtype.newbyteorder()) for a in arrs]
+
+
+class BaseQRdeltas:
+ def setup_method(self):
+ self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2)
+ self.atol = 10 * np.finfo(self.dtype).eps
+
+ def generate(self, type, mode='full'):
+ rng = np.random.default_rng(29382)
+ shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12),
+ 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type]
+ a = rng.random(shape)
+ if np.iscomplexobj(self.dtype.type(1)):
+ b = rng.random(shape)
+ a = a + 1j * b
+ a = a.astype(self.dtype)
+ q, r = linalg.qr(a, mode=mode)
+ return a, q, r
+
+class BaseQRdelete(BaseQRdeltas):
+ def test_sqr_1_row(self):
+ a, q, r = self.generate('sqr')
+ for row in range(r.shape[0]):
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+ a1 = np.delete(a, row, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_sqr_p_row(self):
+ a, q, r = self.generate('sqr')
+ for ndel in range(2, 6):
+ for row in range(a.shape[0]-ndel):
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+ a1 = np.delete(a, slice(row, row+ndel), 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_sqr_1_col(self):
+ a, q, r = self.generate('sqr')
+ for col in range(r.shape[1]):
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+ a1 = np.delete(a, col, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_sqr_p_col(self):
+ a, q, r = self.generate('sqr')
+ for ndel in range(2, 6):
+ for col in range(r.shape[1]-ndel):
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
+ overwrite_qr=False)
+ a1 = np.delete(a, slice(col, col+ndel), 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_1_row(self):
+ a, q, r = self.generate('tall')
+ for row in range(r.shape[0]):
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+ a1 = np.delete(a, row, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_p_row(self):
+ a, q, r = self.generate('tall')
+ for ndel in range(2, 6):
+ for row in range(a.shape[0]-ndel):
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+ a1 = np.delete(a, slice(row, row+ndel), 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_1_col(self):
+ a, q, r = self.generate('tall')
+ for col in range(r.shape[1]):
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+ a1 = np.delete(a, col, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_p_col(self):
+ a, q, r = self.generate('tall')
+ for ndel in range(2, 6):
+ for col in range(r.shape[1]-ndel):
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
+ overwrite_qr=False)
+ a1 = np.delete(a, slice(col, col+ndel), 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_1_row(self):
+ a, q, r = self.generate('fat')
+ for row in range(r.shape[0]):
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+ a1 = np.delete(a, row, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_p_row(self):
+ a, q, r = self.generate('fat')
+ for ndel in range(2, 6):
+ for row in range(a.shape[0]-ndel):
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+ a1 = np.delete(a, slice(row, row+ndel), 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_1_col(self):
+ a, q, r = self.generate('fat')
+ for col in range(r.shape[1]):
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+ a1 = np.delete(a, col, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_p_col(self):
+ a, q, r = self.generate('fat')
+ for ndel in range(2, 6):
+ for col in range(r.shape[1]-ndel):
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
+ overwrite_qr=False)
+ a1 = np.delete(a, slice(col, col+ndel), 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_economic_1_row(self):
+ # this test always starts and ends with an economic decomp.
+ a, q, r = self.generate('tall', 'economic')
+ for row in range(r.shape[0]):
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+ a1 = np.delete(a, row, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ # for economic row deletes
+ # eco - prow = eco
+ # eco - prow = sqr
+ # eco - prow = fat
+ def base_economic_p_row_xxx(self, ndel):
+ a, q, r = self.generate('tall', 'economic')
+ for row in range(a.shape[0]-ndel):
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+ a1 = np.delete(a, slice(row, row+ndel), 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_economic_p_row_economic(self):
+ # (12, 7) - (3, 7) = (9,7) --> stays economic
+ self.base_economic_p_row_xxx(3)
+
+ def test_economic_p_row_sqr(self):
+ # (12, 7) - (5, 7) = (7, 7) --> becomes square
+ self.base_economic_p_row_xxx(5)
+
+ def test_economic_p_row_fat(self):
+ # (12, 7) - (7,7) = (5, 7) --> becomes fat
+ self.base_economic_p_row_xxx(7)
+
+ def test_economic_1_col(self):
+ a, q, r = self.generate('tall', 'economic')
+ for col in range(r.shape[1]):
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+ a1 = np.delete(a, col, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_economic_p_col(self):
+ a, q, r = self.generate('tall', 'economic')
+ for ndel in range(2, 6):
+ for col in range(r.shape[1]-ndel):
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
+ overwrite_qr=False)
+ a1 = np.delete(a, slice(col, col+ndel), 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_Mx1_1_row(self):
+ a, q, r = self.generate('Mx1')
+ for row in range(r.shape[0]):
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+ a1 = np.delete(a, row, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_p_row(self):
+ a, q, r = self.generate('Mx1')
+ for ndel in range(2, 6):
+ for row in range(a.shape[0]-ndel):
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+ a1 = np.delete(a, slice(row, row+ndel), 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1xN_1_col(self):
+ a, q, r = self.generate('1xN')
+ for col in range(r.shape[1]):
+ q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+ a1 = np.delete(a, col, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1xN_p_col(self):
+ a, q, r = self.generate('1xN')
+ for ndel in range(2, 6):
+ for col in range(r.shape[1]-ndel):
+ q1, r1 = qr_delete(q, r, col, ndel, which='col',
+ overwrite_qr=False)
+ a1 = np.delete(a, slice(col, col+ndel), 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_economic_1_row(self):
+ a, q, r = self.generate('Mx1', 'economic')
+ for row in range(r.shape[0]):
+ q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+ a1 = np.delete(a, row, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_Mx1_economic_p_row(self):
+ a, q, r = self.generate('Mx1', 'economic')
+ for ndel in range(2, 6):
+ for row in range(a.shape[0]-ndel):
+ q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+ a1 = np.delete(a, slice(row, row+ndel), 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_delete_last_1_row(self):
+ # full and eco are the same for 1xN
+ a, q, r = self.generate('1xN')
+ q1, r1 = qr_delete(q, r, 0, 1, 'row')
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+ def test_delete_last_p_row(self):
+ a, q, r = self.generate('tall', 'full')
+ q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+ a, q, r = self.generate('tall', 'economic')
+ q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+ def test_delete_last_1_col(self):
+ a, q, r = self.generate('Mx1', 'economic')
+ q1, r1 = qr_delete(q, r, 0, 1, 'col')
+ assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
+ assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
+
+ a, q, r = self.generate('Mx1', 'full')
+ q1, r1 = qr_delete(q, r, 0, 1, 'col')
+ assert_unitary(q1)
+ assert_(q1.dtype == q.dtype)
+ assert_(q1.shape == q.shape)
+ assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+ def test_delete_last_p_col(self):
+ a, q, r = self.generate('tall', 'full')
+ q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
+ assert_unitary(q1)
+ assert_(q1.dtype == q.dtype)
+ assert_(q1.shape == q.shape)
+ assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+ a, q, r = self.generate('tall', 'economic')
+ q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
+ assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
+ assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
+
+ def test_delete_1x1_row_col(self):
+ a, q, r = self.generate('1x1')
+ q1, r1 = qr_delete(q, r, 0, 1, 'row')
+ assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+ assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+ a, q, r = self.generate('1x1')
+ q1, r1 = qr_delete(q, r, 0, 1, 'col')
+ assert_unitary(q1)
+ assert_(q1.dtype == q.dtype)
+ assert_(q1.shape == q.shape)
+ assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+ # all full qr, row deletes and single column deletes should be able to
+ # handle any non negative strides. (only row and column vector
+ # operations are used.) p column delete require fortran ordered
+ # Q and R and will make a copy as necessary. Economic qr row deletes
+ # require a contiguous q.
+
+ def base_non_simple_strides(self, adjust_strides, ks, p, which,
+ overwriteable):
+ if which == 'row':
+ qind = (slice(p,None), slice(p,None))
+ rind = (slice(p,None), slice(None))
+ else:
+ qind = (slice(None), slice(None))
+ rind = (slice(None), slice(None,-p))
+
+ for type, k in itertools.product(['sqr', 'tall', 'fat'], ks):
+ a, q0, r0, = self.generate(type)
+ qs, rs = adjust_strides((q0, r0))
+ if p == 1:
+ a1 = np.delete(a, k, 0 if which == 'row' else 1)
+ else:
+ s = slice(k,k+p)
+ if k < 0:
+ s = slice(k, k + p +
+ (a.shape[0] if which == 'row' else a.shape[1]))
+ a1 = np.delete(a, s, 0 if which == 'row' else 1)
+
+ # for each variable, q, r we try with it strided and
+ # overwrite=False. Then we try with overwrite=True, and make
+ # sure that q and r are still overwritten.
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ q1, r1 = qr_delete(qs, r, k, p, which, False)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+ q1o, r1o = qr_delete(qs, r, k, p, which, True)
+ check_qr(q1o, r1o, a1, self.rtol, self.atol)
+ if overwriteable:
+ assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol)
+ assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ q2, r2 = qr_delete(q, rs, k, p, which, False)
+ check_qr(q2, r2, a1, self.rtol, self.atol)
+ q2o, r2o = qr_delete(q, rs, k, p, which, True)
+ check_qr(q2o, r2o, a1, self.rtol, self.atol)
+ if overwriteable:
+ assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol)
+ assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ # since some of these were consumed above
+ qs, rs = adjust_strides((q, r))
+ q3, r3 = qr_delete(qs, rs, k, p, which, False)
+ check_qr(q3, r3, a1, self.rtol, self.atol)
+ q3o, r3o = qr_delete(qs, rs, k, p, which, True)
+ check_qr(q3o, r3o, a1, self.rtol, self.atol)
+ if overwriteable:
+ assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol)
+ assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol)
+
+ def test_non_unit_strides_1_row(self):
+ self.base_non_simple_strides(make_strided, [0], 1, 'row', True)
+
+ def test_non_unit_strides_p_row(self):
+ self.base_non_simple_strides(make_strided, [0], 3, 'row', True)
+
+ def test_non_unit_strides_1_col(self):
+ self.base_non_simple_strides(make_strided, [0], 1, 'col', True)
+
+ def test_non_unit_strides_p_col(self):
+ self.base_non_simple_strides(make_strided, [0], 3, 'col', False)
+
+ def test_neg_strides_1_row(self):
+ self.base_non_simple_strides(negate_strides, [0], 1, 'row', False)
+
+ def test_neg_strides_p_row(self):
+ self.base_non_simple_strides(negate_strides, [0], 3, 'row', False)
+
+ def test_neg_strides_1_col(self):
+ self.base_non_simple_strides(negate_strides, [0], 1, 'col', False)
+
+ def test_neg_strides_p_col(self):
+ self.base_non_simple_strides(negate_strides, [0], 3, 'col', False)
+
+ def test_non_itemize_strides_1_row(self):
+ self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False)
+
+ def test_non_itemize_strides_p_row(self):
+ self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False)
+
+ def test_non_itemize_strides_1_col(self):
+ self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False)
+
+ def test_non_itemize_strides_p_col(self):
+ self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False)
+
+ def test_non_native_byte_order_1_row(self):
+ self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False)
+
+ def test_non_native_byte_order_p_row(self):
+ self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False)
+
+ def test_non_native_byte_order_1_col(self):
+ self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False)
+
+ def test_non_native_byte_order_p_col(self):
+ self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False)
+
+ def test_neg_k(self):
+ a, q, r = self.generate('sqr')
+ for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']):
+ q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False)
+ if w == 'row':
+ a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0)
+ else:
+ a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'):
+ assert_sqr = True if mode == 'full' else False
+ if which == 'row':
+ qind = (slice(p,None), slice(p,None))
+ rind = (slice(p,None), slice(None))
+ else:
+ qind = (slice(None), slice(None))
+ rind = (slice(None), slice(None,-p))
+ a, q0, r0 = self.generate('sqr', mode)
+ if p == 1:
+ a1 = np.delete(a, 3, 0 if which == 'row' else 1)
+ else:
+ a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1)
+
+ # don't overwrite
+ q = q0.copy('F')
+ r = r0.copy('F')
+ q1, r1 = qr_delete(q, r, 3, p, which, False)
+ check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr)
+ check_qr(q, r, a, self.rtol, self.atol, assert_sqr)
+
+ if test_F:
+ q = q0.copy('F')
+ r = r0.copy('F')
+ q2, r2 = qr_delete(q, r, 3, p, which, True)
+ check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr)
+ # verify the overwriting
+ assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol)
+ assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol)
+
+ if test_C:
+ q = q0.copy('C')
+ r = r0.copy('C')
+ q3, r3 = qr_delete(q, r, 3, p, which, True)
+ check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr)
+ assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol)
+ assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol)
+
+ def test_overwrite_qr_1_row(self):
+ # any positively strided q and r.
+ self.base_overwrite_qr('row', 1, True, True)
+
+ def test_overwrite_economic_qr_1_row(self):
+ # Any contiguous q and positively strided r.
+ self.base_overwrite_qr('row', 1, True, True, 'economic')
+
+ def test_overwrite_qr_1_col(self):
+ # any positively strided q and r.
+ # full and eco share code paths
+ self.base_overwrite_qr('col', 1, True, True)
+
+ def test_overwrite_qr_p_row(self):
+ # any positively strided q and r.
+ self.base_overwrite_qr('row', 3, True, True)
+
+ def test_overwrite_economic_qr_p_row(self):
+ # any contiguous q and positively strided r
+ self.base_overwrite_qr('row', 3, True, True, 'economic')
+
+ def test_overwrite_qr_p_col(self):
+ # only F ordered q and r can be overwritten for cols
+ # full and eco share code paths
+ self.base_overwrite_qr('col', 3, False, True)
+
+ def test_bad_which(self):
+ a, q, r = self.generate('sqr')
+ assert_raises(ValueError, qr_delete, q, r, 0, which='foo')
+
+ def test_bad_k(self):
+ a, q, r = self.generate('tall')
+ assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1)
+ assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1)
+ assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col')
+ assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col')
+
+ def test_bad_p(self):
+ a, q, r = self.generate('tall')
+ # p must be positive
+ assert_raises(ValueError, qr_delete, q, r, 0, -1)
+ assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col')
+
+ # and nonzero
+ assert_raises(ValueError, qr_delete, q, r, 0, 0)
+ assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col')
+
+ # must have at least k+p rows or cols, depending.
+ assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2)
+ assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col')
+
+ def test_empty_q(self):
+ a, q, r = self.generate('tall')
+ # same code path for 'row' and 'col'
+ assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1)
+
+ def test_empty_r(self):
+ a, q, r = self.generate('tall')
+ # same code path for 'row' and 'col'
+ assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1)
+
+ def test_mismatched_q_and_r(self):
+ a, q, r = self.generate('tall')
+ r = r[1:]
+ assert_raises(ValueError, qr_delete, q, r, 0, 1)
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_unsupported_dtypes(self):
+ dts = ['int8', 'int16', 'int32', 'int64',
+ 'uint8', 'uint16', 'uint32', 'uint64',
+ 'float16', 'longdouble', 'clongdouble',
+ 'bool']
+ a, q0, r0 = self.generate('tall')
+ for dtype in dts:
+ q = q0.real.astype(dtype)
+ with np.errstate(invalid="ignore"):
+ r = r0.real.astype(dtype)
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
+ assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row')
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
+ assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col')
+
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
+ assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row')
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
+ assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col')
+
+ def test_check_finite(self):
+ a0, q0, r0 = self.generate('tall')
+
+ q = q0.copy('F')
+ q[1,1] = np.nan
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
+ assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row')
+ assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
+ assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col')
+
+ r = r0.copy('F')
+ r[1,1] = np.nan
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
+ assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row')
+ assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
+ assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col')
+
+ def test_qr_scalar(self):
+ a, q, r = self.generate('1x1')
+ assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row')
+ assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row')
+ assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col')
+ assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col')
+
+class TestQRdelete_f(BaseQRdelete):
+ dtype = np.dtype('f')
+
+class TestQRdelete_F(BaseQRdelete):
+ dtype = np.dtype('F')
+
+class TestQRdelete_d(BaseQRdelete):
+ dtype = np.dtype('d')
+
+class TestQRdelete_D(BaseQRdelete):
+ dtype = np.dtype('D')
+
+class BaseQRinsert(BaseQRdeltas):
+ def generate(self, type, mode='full', which='row', p=1):
+ a, q, r = super().generate(type, mode)
+
+ assert_(p > 0)
+ rng = np.random.default_rng(1234)
+
+ if which == 'row':
+ if p == 1:
+ u = rng.random(a.shape[1])
+ else:
+ u = rng.random((p, a.shape[1]))
+ elif which == 'col':
+ if p == 1:
+ u = rng.random(a.shape[0])
+ else:
+ u = rng.random((a.shape[0], p))
+ else:
+ raise ValueError('which should be either "row" or "col"')
+
+ if np.iscomplexobj(self.dtype.type(1)):
+ b = rng.random(u.shape)
+ u = u + 1j * b
+
+ u = u.astype(self.dtype)
+ return a, q, r, u
+
+ def test_sqr_1_row(self):
+ a, q, r, u = self.generate('sqr', which='row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_sqr_p_row(self):
+ # sqr + rows --> fat always
+ a, q, r, u = self.generate('sqr', which='row', p=3)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_sqr_1_col(self):
+ a, q, r, u = self.generate('sqr', which='col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_sqr_p_col(self):
+ # sqr + cols --> fat always
+ a, q, r, u = self.generate('sqr', which='col', p=3)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_1_row(self):
+ a, q, r, u = self.generate('tall', which='row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_p_row(self):
+ # tall + rows --> tall always
+ a, q, r, u = self.generate('tall', which='row', p=3)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_1_col(self):
+ a, q, r, u = self.generate('tall', which='col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ # for column adds to tall matrices there are three cases to test
+ # tall + pcol --> tall
+ # tall + pcol --> sqr
+ # tall + pcol --> fat
+ def base_tall_p_col_xxx(self, p):
+ a, q, r, u = self.generate('tall', which='col', p=p)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_p_col_tall(self):
+ # 12x7 + 12x3 = 12x10 --> stays tall
+ self.base_tall_p_col_xxx(3)
+
+ def test_tall_p_col_sqr(self):
+ # 12x7 + 12x5 = 12x12 --> becomes sqr
+ self.base_tall_p_col_xxx(5)
+
+ def test_tall_p_col_fat(self):
+ # 12x7 + 12x7 = 12x14 --> becomes fat
+ self.base_tall_p_col_xxx(7)
+
+ def test_fat_1_row(self):
+ a, q, r, u = self.generate('fat', which='row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ # for row adds to fat matrices there are three cases to test
+ # fat + prow --> fat
+ # fat + prow --> sqr
+ # fat + prow --> tall
+ def base_fat_p_row_xxx(self, p):
+ a, q, r, u = self.generate('fat', which='row', p=p)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, np.full(p, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_p_row_fat(self):
+ # 7x12 + 3x12 = 10x12 --> stays fat
+ self.base_fat_p_row_xxx(3)
+
+ def test_fat_p_row_sqr(self):
+ # 7x12 + 5x12 = 12x12 --> becomes sqr
+ self.base_fat_p_row_xxx(5)
+
+ def test_fat_p_row_tall(self):
+ # 7x12 + 7x12 = 14x12 --> becomes tall
+ self.base_fat_p_row_xxx(7)
+
+ def test_fat_1_col(self):
+ a, q, r, u = self.generate('fat', which='col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_p_col(self):
+ # fat + cols --> fat always
+ a, q, r, u = self.generate('fat', which='col', p=3)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_economic_1_row(self):
+ a, q, r, u = self.generate('tall', 'economic', 'row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_economic_p_row(self):
+ # tall + rows --> tall always
+ a, q, r, u = self.generate('tall', 'economic', 'row', 3)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_economic_1_col(self):
+ a, q, r, u = self.generate('tall', 'economic', which='col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_economic_1_col_bad_update(self):
+ # When the column to be added lies in the span of Q, the update is
+ # not meaningful. This is detected, and a LinAlgError is issued.
+ q = np.eye(5, 3, dtype=self.dtype)
+ r = np.eye(3, dtype=self.dtype)
+ u = np.array([1, 0, 0, 0, 0], self.dtype)
+ assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col')
+
+ # for column adds to economic matrices there are three cases to test
+ # eco + pcol --> eco
+ # eco + pcol --> sqr
+ # eco + pcol --> fat
+ def base_economic_p_col_xxx(self, p):
+ a, q, r, u = self.generate('tall', 'economic', which='col', p=p)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_economic_p_col_eco(self):
+ # 12x7 + 12x3 = 12x10 --> stays eco
+ self.base_economic_p_col_xxx(3)
+
+ def test_economic_p_col_sqr(self):
+ # 12x7 + 12x5 = 12x12 --> becomes sqr
+ self.base_economic_p_col_xxx(5)
+
+ def test_economic_p_col_fat(self):
+ # 12x7 + 12x7 = 12x14 --> becomes fat
+ self.base_economic_p_col_xxx(7)
+
+ def test_Mx1_1_row(self):
+ a, q, r, u = self.generate('Mx1', which='row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_p_row(self):
+ a, q, r, u = self.generate('Mx1', which='row', p=3)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_1_col(self):
+ a, q, r, u = self.generate('Mx1', which='col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_p_col(self):
+ a, q, r, u = self.generate('Mx1', which='col', p=3)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_economic_1_row(self):
+ a, q, r, u = self.generate('Mx1', 'economic', 'row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_Mx1_economic_p_row(self):
+ a, q, r, u = self.generate('Mx1', 'economic', 'row', 3)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_Mx1_economic_1_col(self):
+ a, q, r, u = self.generate('Mx1', 'economic', 'col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_Mx1_economic_p_col(self):
+ a, q, r, u = self.generate('Mx1', 'economic', 'col', 3)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_1xN_1_row(self):
+ a, q, r, u = self.generate('1xN', which='row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1xN_p_row(self):
+ a, q, r, u = self.generate('1xN', which='row', p=3)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1xN_1_col(self):
+ a, q, r, u = self.generate('1xN', which='col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1xN_p_col(self):
+ a, q, r, u = self.generate('1xN', which='col', p=3)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_1_row(self):
+ a, q, r, u = self.generate('1x1', which='row')
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, row, u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_p_row(self):
+ a, q, r, u = self.generate('1x1', which='row', p=3)
+ for row in range(r.shape[0] + 1):
+ q1, r1 = qr_insert(q, r, u, row)
+ a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_1_col(self):
+ a, q, r, u = self.generate('1x1', which='col')
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, col, u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_p_col(self):
+ a, q, r, u = self.generate('1x1', which='col', p=3)
+ for col in range(r.shape[1] + 1):
+ q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+ a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_1_scalar(self):
+ a, q, r, u = self.generate('1x1', which='row')
+ assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row')
+
+ assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col')
+ assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col')
+ assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col')
+
+ def base_non_simple_strides(self, adjust_strides, k, p, which):
+ for type in ['sqr', 'tall', 'fat']:
+ a, q0, r0, u0 = self.generate(type, which=which, p=p)
+ qs, rs, us = adjust_strides((q0, r0, u0))
+ if p == 1:
+ ai = np.insert(a, k, u0, 0 if which == 'row' else 1)
+ else:
+ ai = np.insert(a, np.full(p, k, np.intp),
+ u0 if which == 'row' else u0,
+ 0 if which == 'row' else 1)
+
+ # for each variable, q, r, u we try with it strided and
+ # overwrite=False. Then we try with overwrite=True. Nothing
+ # is checked to see if it can be overwritten, since only
+ # F ordered Q can be overwritten when adding columns.
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False)
+ check_qr(q1, r1, ai, self.rtol, self.atol)
+ q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True)
+ check_qr(q1o, r1o, ai, self.rtol, self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False)
+ check_qr(q2, r2, ai, self.rtol, self.atol)
+ q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True)
+ check_qr(q2o, r2o, ai, self.rtol, self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False)
+ check_qr(q3, r3, ai, self.rtol, self.atol)
+ q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True)
+ check_qr(q3o, r3o, ai, self.rtol, self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ # since some of these were consumed above
+ qs, rs, us = adjust_strides((q, r, u))
+ q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False)
+ check_qr(q5, r5, ai, self.rtol, self.atol)
+ q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True)
+ check_qr(q5o, r5o, ai, self.rtol, self.atol)
+
+ def test_non_unit_strides_1_row(self):
+ self.base_non_simple_strides(make_strided, 0, 1, 'row')
+
+ def test_non_unit_strides_p_row(self):
+ self.base_non_simple_strides(make_strided, 0, 3, 'row')
+
+ def test_non_unit_strides_1_col(self):
+ self.base_non_simple_strides(make_strided, 0, 1, 'col')
+
+ def test_non_unit_strides_p_col(self):
+ self.base_non_simple_strides(make_strided, 0, 3, 'col')
+
+ def test_neg_strides_1_row(self):
+ self.base_non_simple_strides(negate_strides, 0, 1, 'row')
+
+ def test_neg_strides_p_row(self):
+ self.base_non_simple_strides(negate_strides, 0, 3, 'row')
+
+ def test_neg_strides_1_col(self):
+ self.base_non_simple_strides(negate_strides, 0, 1, 'col')
+
+ def test_neg_strides_p_col(self):
+ self.base_non_simple_strides(negate_strides, 0, 3, 'col')
+
+ def test_non_itemsize_strides_1_row(self):
+ self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row')
+
+ def test_non_itemsize_strides_p_row(self):
+ self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row')
+
+ def test_non_itemsize_strides_1_col(self):
+ self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col')
+
+ def test_non_itemsize_strides_p_col(self):
+ self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col')
+
+ def test_non_native_byte_order_1_row(self):
+ self.base_non_simple_strides(make_nonnative, 0, 1, 'row')
+
+ def test_non_native_byte_order_p_row(self):
+ self.base_non_simple_strides(make_nonnative, 0, 3, 'row')
+
+ def test_non_native_byte_order_1_col(self):
+ self.base_non_simple_strides(make_nonnative, 0, 1, 'col')
+
+ def test_non_native_byte_order_p_col(self):
+ self.base_non_simple_strides(make_nonnative, 0, 3, 'col')
+
+ def test_overwrite_qu_rank_1(self):
+ # when inserting rows, the size of both Q and R change, so only
+ # column inserts can overwrite q. Only complex column inserts
+ # with C ordered Q overwrite u. Any contiguous Q is overwritten
+ # when inserting 1 column
+ a, q0, r, u, = self.generate('sqr', which='col', p=1)
+ q = q0.copy('C')
+ u0 = u.copy()
+ # don't overwrite
+ q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
+ a1 = np.insert(a, 0, u0, 1)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+ check_qr(q, r, a, self.rtol, self.atol)
+
+ # try overwriting
+ q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
+ check_qr(q2, r2, a1, self.rtol, self.atol)
+ # verify the overwriting
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+ assert_allclose(u, u0.conj(), self.rtol, self.atol)
+
+ # now try with a fortran ordered Q
+ qF = q0.copy('F')
+ u1 = u0.copy()
+ q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False)
+ check_qr(q3, r3, a1, self.rtol, self.atol)
+ check_qr(qF, r, a, self.rtol, self.atol)
+
+ # try overwriting
+ q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True)
+ check_qr(q4, r4, a1, self.rtol, self.atol)
+ assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol)
+
+ def test_overwrite_qu_rank_p(self):
+ # when inserting rows, the size of both Q and R change, so only
+ # column inserts can potentially overwrite Q. In practice, only
+ # F ordered Q are overwritten with a rank p update.
+ a, q0, r, u, = self.generate('sqr', which='col', p=3)
+ q = q0.copy('F')
+ a1 = np.insert(a, np.zeros(3, np.intp), u, 1)
+
+ # don't overwrite
+ q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+ check_qr(q, r, a, self.rtol, self.atol)
+
+ # try overwriting
+ q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
+ check_qr(q2, r2, a1, self.rtol, self.atol)
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+
+ def test_empty_inputs(self):
+ a, q, r, u = self.generate('sqr', which='row')
+ assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row')
+ assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col')
+ assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col')
+ assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col')
+
+ def test_mismatched_shapes(self):
+ a, q, r, u = self.generate('tall', which='row')
+ assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col')
+ assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col')
+ assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col')
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_unsupported_dtypes(self):
+ dts = ['int8', 'int16', 'int32', 'int64',
+ 'uint8', 'uint16', 'uint32', 'uint64',
+ 'float16', 'longdouble', 'clongdouble',
+ 'bool']
+ a, q0, r0, u0 = self.generate('sqr', which='row')
+ for dtype in dts:
+ q = q0.real.astype(dtype)
+ with np.errstate(invalid="ignore"):
+ r = r0.real.astype(dtype)
+ u = u0.real.astype(dtype)
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
+
+ def test_check_finite(self):
+ a0, q0, r0, u0 = self.generate('sqr', which='row', p=3)
+
+ q = q0.copy('F')
+ q[1,1] = np.nan
+ assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
+ assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col')
+ assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
+
+ r = r0.copy('F')
+ r[1,1] = np.nan
+ assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row')
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
+ assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col')
+ assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
+
+ u = u0.copy('F')
+ u[0,0] = np.nan
+ assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row')
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
+ assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col')
+ assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
+
+class TestQRinsert_f(BaseQRinsert):
+ dtype = np.dtype('f')
+
+class TestQRinsert_F(BaseQRinsert):
+ dtype = np.dtype('F')
+
+class TestQRinsert_d(BaseQRinsert):
+ dtype = np.dtype('d')
+
+class TestQRinsert_D(BaseQRinsert):
+ dtype = np.dtype('D')
+
+class BaseQRupdate(BaseQRdeltas):
+ def generate(self, type, mode='full', p=1):
+ a, q, r = super().generate(type, mode)
+
+ rng = np.random.default_rng(1234)
+ if p == 1:
+ u = rng.random(q.shape[0])
+ v = rng.random(r.shape[1])
+ else:
+ u = rng.random((q.shape[0], p))
+ v = rng.random((r.shape[1], p))
+
+ if np.iscomplexobj(self.dtype.type(1)):
+ b = rng.random(u.shape)
+ u = u + 1j * b
+
+ c = rng.random(v.shape)
+ v = v + 1j * c
+
+ u = u.astype(self.dtype)
+ v = v.astype(self.dtype)
+ return a, q, r, u, v
+
+ def test_sqr_rank_1(self):
+ a, q, r, u, v = self.generate('sqr')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_sqr_rank_p(self):
+ # test ndim = 2, rank 1 updates here too
+ for p in [1, 2, 3, 5]:
+ a, q, r, u, v = self.generate('sqr', p=p)
+ if p == 1:
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_rank_1(self):
+ a, q, r, u, v = self.generate('tall')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_tall_rank_p(self):
+ for p in [1, 2, 3, 5]:
+ a, q, r, u, v = self.generate('tall', p=p)
+ if p == 1:
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_rank_1(self):
+ a, q, r, u, v = self.generate('fat')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_fat_rank_p(self):
+ for p in [1, 2, 3, 5]:
+ a, q, r, u, v = self.generate('fat', p=p)
+ if p == 1:
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_economic_rank_1(self):
+ a, q, r, u, v = self.generate('tall', 'economic')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_economic_rank_p(self):
+ for p in [1, 2, 3, 5]:
+ a, q, r, u, v = self.generate('tall', 'economic', p)
+ if p == 1:
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_Mx1_rank_1(self):
+ a, q, r, u, v = self.generate('Mx1')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_rank_p(self):
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
+ # fundamental limitation, but the code does not support it.
+ a, q, r, u, v = self.generate('Mx1', p=1)
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_Mx1_economic_rank_1(self):
+ a, q, r, u, v = self.generate('Mx1', 'economic')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_Mx1_economic_rank_p(self):
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
+ # fundamental limitation, but the code does not support it.
+ a, q, r, u, v = self.generate('Mx1', 'economic', p=1)
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+ def test_1xN_rank_1(self):
+ a, q, r, u, v = self.generate('1xN')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1xN_rank_p(self):
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
+ # fundamental limitation, but the code does not support it.
+ a, q, r, u, v = self.generate('1xN', p=1)
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_rank_1(self):
+ a, q, r, u, v = self.generate('1x1')
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_rank_p(self):
+ # when M or N == 1, only a rank 1 update is allowed. This isn't
+ # fundamental limitation, but the code does not support it.
+ a, q, r, u, v = self.generate('1x1', p=1)
+ u = u.reshape(u.size, 1)
+ v = v.reshape(v.size, 1)
+ q1, r1 = qr_update(q, r, u, v, False)
+ a1 = a + np.dot(u, v.T.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+
+ def test_1x1_rank_1_scalar(self):
+ a, q, r, u, v = self.generate('1x1')
+ assert_raises(ValueError, qr_update, q[0, 0], r, u, v)
+ assert_raises(ValueError, qr_update, q, r[0, 0], u, v)
+ assert_raises(ValueError, qr_update, q, r, u[0], v)
+ assert_raises(ValueError, qr_update, q, r, u, v[0])
+
+ def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable):
+ assert_sqr = False if mode == 'economic' else True
+ for type in ['sqr', 'tall', 'fat']:
+ a, q0, r0, u0, v0 = self.generate(type, mode, p)
+ qs, rs, us, vs = adjust_strides((q0, r0, u0, v0))
+ if p == 1:
+ aup = a + np.outer(u0, v0.conj())
+ else:
+ aup = a + np.dot(u0, v0.T.conj())
+
+ # for each variable, q, r, u, v we try with it strided and
+ # overwrite=False. Then we try with overwrite=True, and make
+ # sure that if p == 1, r and v are still overwritten.
+ # a strided q and u must always be copied.
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('C')
+ q1, r1 = qr_update(qs, r, u, v, False)
+ check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr)
+ q1o, r1o = qr_update(qs, r, u, v, True)
+ check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr)
+ if overwriteable:
+ assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol)
+ assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('C')
+ q2, r2 = qr_update(q, rs, u, v, False)
+ check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr)
+ q2o, r2o = qr_update(q, rs, u, v, True)
+ check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr)
+ if overwriteable:
+ assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol)
+ assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('C')
+ q3, r3 = qr_update(q, r, us, v, False)
+ check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr)
+ q3o, r3o = qr_update(q, r, us, v, True)
+ check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr)
+ if overwriteable:
+ assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol)
+ assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('C')
+ q4, r4 = qr_update(q, r, u, vs, False)
+ check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr)
+ q4o, r4o = qr_update(q, r, u, vs, True)
+ check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr)
+ if overwriteable:
+ assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol)
+ assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('C')
+ # since some of these were consumed above
+ qs, rs, us, vs = adjust_strides((q, r, u, v))
+ q5, r5 = qr_update(qs, rs, us, vs, False)
+ check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr)
+ q5o, r5o = qr_update(qs, rs, us, vs, True)
+ check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr)
+ if overwriteable:
+ assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol)
+ assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+ def test_non_unit_strides_rank_1(self):
+ self.base_non_simple_strides(make_strided, 'full', 1, True)
+
+ def test_non_unit_strides_economic_rank_1(self):
+ self.base_non_simple_strides(make_strided, 'economic', 1, True)
+
+ def test_non_unit_strides_rank_p(self):
+ self.base_non_simple_strides(make_strided, 'full', 3, False)
+
+ def test_non_unit_strides_economic_rank_p(self):
+ self.base_non_simple_strides(make_strided, 'economic', 3, False)
+
+ def test_neg_strides_rank_1(self):
+ self.base_non_simple_strides(negate_strides, 'full', 1, False)
+
+ def test_neg_strides_economic_rank_1(self):
+ self.base_non_simple_strides(negate_strides, 'economic', 1, False)
+
+ def test_neg_strides_rank_p(self):
+ self.base_non_simple_strides(negate_strides, 'full', 3, False)
+
+ def test_neg_strides_economic_rank_p(self):
+ self.base_non_simple_strides(negate_strides, 'economic', 3, False)
+
+ def test_non_itemsize_strides_rank_1(self):
+ self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False)
+
+ def test_non_itemsize_strides_economic_rank_1(self):
+ self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False)
+
+ def test_non_itemsize_strides_rank_p(self):
+ self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False)
+
+ def test_non_itemsize_strides_economic_rank_p(self):
+ self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False)
+
+ def test_non_native_byte_order_rank_1(self):
+ self.base_non_simple_strides(make_nonnative, 'full', 1, False)
+
+ def test_non_native_byte_order_economic_rank_1(self):
+ self.base_non_simple_strides(make_nonnative, 'economic', 1, False)
+
+ def test_non_native_byte_order_rank_p(self):
+ self.base_non_simple_strides(make_nonnative, 'full', 3, False)
+
+ def test_non_native_byte_order_economic_rank_p(self):
+ self.base_non_simple_strides(make_nonnative, 'economic', 3, False)
+
+ def test_overwrite_qruv_rank_1(self):
+ # Any positive strided q, r, u, and v can be overwritten for a rank 1
+ # update, only checking C and F contiguous.
+ a, q0, r0, u0, v0 = self.generate('sqr')
+ a1 = a + np.outer(u0, v0.conj())
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('F')
+
+ # don't overwrite
+ q1, r1 = qr_update(q, r, u, v, False)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+ check_qr(q, r, a, self.rtol, self.atol)
+
+ q2, r2 = qr_update(q, r, u, v, True)
+ check_qr(q2, r2, a1, self.rtol, self.atol)
+ # verify the overwriting, no good way to check u and v.
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+ assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('C')
+ r = r0.copy('C')
+ u = u0.copy('C')
+ v = v0.copy('C')
+ q3, r3 = qr_update(q, r, u, v, True)
+ check_qr(q3, r3, a1, self.rtol, self.atol)
+ assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
+ assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
+
+ def test_overwrite_qruv_rank_1_economic(self):
+ # updating economic decompositions can overwrite any contiguous r,
+ # and positively strided r and u. V is only ever read.
+ # only checking C and F contiguous.
+ a, q0, r0, u0, v0 = self.generate('tall', 'economic')
+ a1 = a + np.outer(u0, v0.conj())
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('F')
+
+ # don't overwrite
+ q1, r1 = qr_update(q, r, u, v, False)
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+ check_qr(q, r, a, self.rtol, self.atol, False)
+
+ q2, r2 = qr_update(q, r, u, v, True)
+ check_qr(q2, r2, a1, self.rtol, self.atol, False)
+ # verify the overwriting, no good way to check u and v.
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+ assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+ q = q0.copy('C')
+ r = r0.copy('C')
+ u = u0.copy('C')
+ v = v0.copy('C')
+ q3, r3 = qr_update(q, r, u, v, True)
+ check_qr(q3, r3, a1, self.rtol, self.atol, False)
+ assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
+ assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
+
+ def test_overwrite_qruv_rank_p(self):
+ # for rank p updates, q r must be F contiguous, v must be C (v.T --> F)
+ # and u can be C or F, but is only overwritten if Q is C and complex
+ a, q0, r0, u0, v0 = self.generate('sqr', p=3)
+ a1 = a + np.dot(u0, v0.T.conj())
+ q = q0.copy('F')
+ r = r0.copy('F')
+ u = u0.copy('F')
+ v = v0.copy('C')
+
+ # don't overwrite
+ q1, r1 = qr_update(q, r, u, v, False)
+ check_qr(q1, r1, a1, self.rtol, self.atol)
+ check_qr(q, r, a, self.rtol, self.atol)
+
+ q2, r2 = qr_update(q, r, u, v, True)
+ check_qr(q2, r2, a1, self.rtol, self.atol)
+ # verify the overwriting, no good way to check u and v.
+ assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+ assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+ def test_empty_inputs(self):
+ a, q, r, u, v = self.generate('tall')
+ assert_raises(ValueError, qr_update, np.array([]), r, u, v)
+ assert_raises(ValueError, qr_update, q, np.array([]), u, v)
+ assert_raises(ValueError, qr_update, q, r, np.array([]), v)
+ assert_raises(ValueError, qr_update, q, r, u, np.array([]))
+
+ def test_mismatched_shapes(self):
+ a, q, r, u, v = self.generate('tall')
+ assert_raises(ValueError, qr_update, q, r[1:], u, v)
+ assert_raises(ValueError, qr_update, q[:-2], r, u, v)
+ assert_raises(ValueError, qr_update, q, r, u[1:], v)
+ assert_raises(ValueError, qr_update, q, r, u, v[1:])
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_unsupported_dtypes(self):
+ dts = ['int8', 'int16', 'int32', 'int64',
+ 'uint8', 'uint16', 'uint32', 'uint64',
+ 'float16', 'longdouble', 'clongdouble',
+ 'bool']
+ a, q0, r0, u0, v0 = self.generate('tall')
+ for dtype in dts:
+ q = q0.real.astype(dtype)
+ with np.errstate(invalid="ignore"):
+ r = r0.real.astype(dtype)
+ u = u0.real.astype(dtype)
+ v = v0.real.astype(dtype)
+ assert_raises(ValueError, qr_update, q, r0, u0, v0)
+ assert_raises(ValueError, qr_update, q0, r, u0, v0)
+ assert_raises(ValueError, qr_update, q0, r0, u, v0)
+ assert_raises(ValueError, qr_update, q0, r0, u0, v)
+
+ def test_integer_input(self):
+ q = np.arange(16).reshape(4, 4)
+ r = q.copy() # doesn't matter
+ u = q[:, 0].copy()
+ v = r[0, :].copy()
+ assert_raises(ValueError, qr_update, q, r, u, v)
+
+ def test_check_finite(self):
+ a0, q0, r0, u0, v0 = self.generate('tall', p=3)
+
+ q = q0.copy('F')
+ q[1,1] = np.nan
+ assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
+ assert_raises(ValueError, qr_update, q, r0, u0, v0)
+
+ r = r0.copy('F')
+ r[1,1] = np.nan
+ assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
+ assert_raises(ValueError, qr_update, q0, r, u0, v0)
+
+ u = u0.copy('F')
+ u[0,0] = np.nan
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
+ assert_raises(ValueError, qr_update, q0, r0, u, v0)
+
+ v = v0.copy('F')
+ v[0,0] = np.nan
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
+ assert_raises(ValueError, qr_update, q0, r0, u, v)
+
+ def test_economic_check_finite(self):
+ a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3)
+
+ q = q0.copy('F')
+ q[1,1] = np.nan
+ assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
+ assert_raises(ValueError, qr_update, q, r0, u0, v0)
+
+ r = r0.copy('F')
+ r[1,1] = np.nan
+ assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
+ assert_raises(ValueError, qr_update, q0, r, u0, v0)
+
+ u = u0.copy('F')
+ u[0,0] = np.nan
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
+ assert_raises(ValueError, qr_update, q0, r0, u, v0)
+
+ v = v0.copy('F')
+ v[0,0] = np.nan
+ assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
+ assert_raises(ValueError, qr_update, q0, r0, u, v)
+
+ def test_u_exactly_in_span_q(self):
+ q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype)
+ r = np.array([[1, 0], [0, 1]], self.dtype)
+ u = np.array([0, 0, 0, -1], self.dtype)
+ v = np.array([1, 2], self.dtype)
+ q1, r1 = qr_update(q, r, u, v)
+ a1 = np.dot(q, r) + np.outer(u, v.conj())
+ check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+class TestQRupdate_f(BaseQRupdate):
+ dtype = np.dtype('f')
+
+class TestQRupdate_F(BaseQRupdate):
+ dtype = np.dtype('F')
+
+class TestQRupdate_d(BaseQRupdate):
+ dtype = np.dtype('d')
+
+class TestQRupdate_D(BaseQRupdate):
+ dtype = np.dtype('D')
+
+def test_form_qTu():
+ # We want to ensure that all of the code paths through this function are
+ # tested. Most of them should be hit with the rest of test suite, but
+ # explicit tests make clear precisely what is being tested.
+ #
+ # This function expects that Q is either C or F contiguous and square.
+ # Economic mode decompositions (Q is (M, N), M != N) do not go through this
+ # function. U may have any positive strides.
+ #
+ # Some of these test are duplicates, since contiguous 1d arrays are both C
+ # and F.
+
+ q_order = ['F', 'C']
+ q_shape = [(8, 8), ]
+ u_order = ['F', 'C', 'A'] # here A means is not F not C
+ u_shape = [1, 3]
+ dtype = ['f', 'd', 'F', 'D']
+
+ for qo, qs, uo, us, d in \
+ itertools.product(q_order, q_shape, u_order, u_shape, dtype):
+ if us == 1:
+ check_form_qTu(qo, qs, uo, us, 1, d)
+ check_form_qTu(qo, qs, uo, us, 2, d)
+ else:
+ check_form_qTu(qo, qs, uo, us, 2, d)
+
+def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype):
+ rng = np.random.default_rng(47)
+ if u_shape == 1 and u_ndim == 1:
+ u_shape = (q_shape[0],)
+ else:
+ u_shape = (q_shape[0], u_shape)
+ dtype = np.dtype(dtype)
+
+ if dtype.char in 'fd':
+ q = rng.random(q_shape)
+ u = rng.random(u_shape)
+ elif dtype.char in 'FD':
+ q = rng.random(q_shape) + 1j*rng.random(q_shape)
+ u = rng.random(u_shape) + 1j*rng.random(u_shape)
+ else:
+ raise ValueError("form_qTu doesn't support this dtype")
+
+ q = np.require(q, dtype, q_order)
+ if u_order != 'A':
+ u = np.require(u, dtype, u_order)
+ else:
+ u, = make_strided((u.astype(dtype),))
+
+ rtol = 10.0 ** -(np.finfo(dtype).precision-2)
+ atol = 2*np.finfo(dtype).eps
+
+ expected = np.dot(q.T.conj(), u)
+ res = _decomp_update._form_qTu(q, u)
+ assert_allclose(res, expected, rtol=rtol, atol=atol)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_deprecations.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_deprecations.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f69e13b6de9ab56131f16dc11ece804e46fb6f2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_deprecations.py
@@ -0,0 +1,223 @@
+'''Test dtype deprecations.
+'''
+import numpy as np
+import scipy.linalg as linalg
+import pytest
+
+from scipy._lib._array_api import SCIPY_ARRAY_API
+
+#
+# When the deprecation expires
+# 1. Change the test from asserting a DeprecationWarning to assert_raises
+# 2. Remove the `_skip_dict` dictionary: it is only used to tell things which
+# already raise errors from things which now emit DeprecationWarnings
+
+
+# skip these completely
+_skip_names = [
+ # not functions
+ 'LinAlgError', 'LinAlgWarning',
+ # do not touch the low-level `scipy.linalg.{blas,lapack}`
+ 'get_lapack_funcs', 'get_blas_funcs', 'find_best_blas_type',
+ # qr_update skip for now
+ 'qr_update', 'qr_insert', 'qr_delete',
+ # special matrix constructors do not use LAPACK
+ 'block_diag',
+ 'toeplitz', 'circulant', 'hankel', 'hadamard', 'leslie', 'companion',
+ 'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
+ 'fiedler', 'fiedler_companion', 'convolution_matrix',
+ # _sketches does not use LAPACK
+ 'clarkson_woodruff_transform',
+ # these did not accepted weird dtypes already
+ 'expm', 'tanm', 'tanhm', 'sinm', 'cosm', 'sinhm', 'coshm', 'expm_cond',
+ 'solve_continuous_are',
+ 'rsf2csf',
+]
+
+
+# use this for dtype-specific skips
+# (e.g. if something only accepts real arrays, add complex typecodes here.)
+_skip_dict = {
+ # TypeError: Only real arrays currently supported
+ 'eigh_tridiagonal': 'G',
+ 'eigvalsh_tridiagonal': 'G',
+ # TypeError: No matching signature found
+ 'issymmetric': 'eGmM',
+ 'ishermitian': 'eGmM',
+ 'bandwidth': 'egGmM',
+ # already raise
+ 'det': 'gGmM',
+ 'expm': 'gG',
+
+ # datetime specific + float16 specific
+ 'cdf2rdf' : 'mM',
+ 'expm_frechet' : 'mM' + 'e',
+ 'pinv': 'mM',
+ 'signm': 'mM',
+ 'fractional_matrix_power' : 'mM' + 'e',
+ 'khatri_rao' : 'mM',
+ 'logm' : 'mM' + 'e',
+ 'orthogonal_procrustes' : 'mM' + 'e',
+ 'solve_circulant' : 'mM',
+ 'solve_continuous_lyapunov': 'M',
+ 'solve_discrete_lyapunov': 'mM' + 'e',
+ 'solve_lyapunov' : 'M',
+ 'solve_sylvester' : 'mM',
+ 'solve_discrete_are': 'mM',
+ 'matmul_toeplitz': 'mM',
+ 'solve_toeplitz': 'mM',
+}
+
+
+# these raise if SCIPY_ARRAY_API env var is defined
+_array_api_skip_dict = {
+ 'cho_factor' : 'mM',
+ 'cho_solve' : 'mM',
+ 'cho_solve_banded' : 'mM',
+ 'cholesky' : 'mM',
+ 'cholesky_banded' : 'mM',
+ 'cossin' : 'mM',
+ 'diagsvd' : 'mM',
+ 'eig_banded' : 'mM',
+ 'eigh' : 'mM',
+ 'eigh_tridiagonal' : 'mM',
+ 'eigvals_banded' : 'mM',
+ 'eigvalsh' : 'mM',
+ 'eigvalsh_tridiagonal' : 'mM',
+ 'funm' : 'mM',
+ 'hessenberg' : 'mM',
+ 'ldl' : 'mM',
+ 'lu_factor' : 'mM',
+ 'lu_solve' : 'mM',
+ 'matrix_balance' : 'mM',
+ 'null_space' : 'mM',
+ 'ordqz' : 'mM',
+ 'orth' : 'mM',
+ 'pinvh' : 'mM',
+ 'polar' : 'mM',
+ 'qr' : 'mM',
+ 'qr_multiply' : 'mM',
+ 'qz' : 'mM',
+ 'rq' : 'mM',
+ 'schur' : 'mM',
+ 'solve_banded' : 'mM',
+ 'solve_continuous_lyapunov' : 'mM',
+ 'solve_lyapunov' : 'mM',
+ 'solve_triangular' : 'mM',
+ 'solveh_banded' : 'mM',
+ 'subspace_angles' : 'mM',
+}
+
+
+if SCIPY_ARRAY_API:
+ #_skip_dict.update(**_array_api_skip_dict)
+ for key, val in _array_api_skip_dict.items():
+ if key in _skip_dict:
+ _skip_dict[key] += val
+ else:
+ _skip_dict[key] = val
+
+
+# loop over all names
+_names = linalg.__all__
+_objs = {name: getattr(linalg, name)
+ for name in _names
+ if name not in _skip_names
+}
+_objs = {name: obj for name,obj in _objs.items() if callable(obj)}
+
+
+# Some gymnastics to prepare a set of arguments which all functions can accept
+_two_arg_names = set([
+ 'cdf2rdf', 'rsf2csf', 'solve', 'solve_triangular', 'lstsq', 'khatri_rao',
+ 'subspace_angles', 'qz', 'ordqz', 'orthogonal_procrustes', 'solve_circulant',
+ 'solve_discrete_lyapunov', 'solve_continuous_lyapunov', 'solve_lyapunov',
+ 'expm_frechet',
+ 'matmul_toeplitz', 'solve_toeplitz', 'lu_solve',
+ 'eigh_tridiagonal', 'eigvalsh_tridiagonal',
+ 'solveh_banded', 'solve_banded', 'solveh_banded', 'qr_multiply',
+])
+
+_three_arg_names = set(['solve_sylvester'])
+
+_four_arg_names = set(['solve_continuous_are', 'solve_discrete_are'])
+
+_arr_and_int_names = set([
+ 'clarkson_woodruff_transform', 'convolution_matrix', 'fractional_matrix_power',
+])
+
+_arr_and_two_int_names = set(['diagsvd', 'cossin'])
+
+
+def _patch_args(func_name, args):
+ '''Make sure func(*args) does not raise because *args is wrong.'''
+ if func_name == 'cdf2rdf':
+ args = (args[0][0], args[1]) # cdf2rd(1d, 2d)
+ elif func_name == 'funm':
+ args = (args[0], lambda x: x)
+ elif func_name == 'lu_solve':
+ a = args[0]
+ piv = np.arange(a.shape[0])
+ args = ((a, piv), args[1])
+ elif func_name in ('eigh_tridiagonal', 'eigvalsh_tridiagonal'):
+ d, e = args
+ args = (d, e[:, :-1])
+ elif func_name == 'cossin':
+ a = args[0]
+ args = (a, a.shape[0]//2, a.shape[1]//2)
+ elif func_name == 'solve_banded':
+ from scipy.linalg._basic import _to_banded
+ args = ((1, 2), _to_banded(1, 2, args[0]), args[0])
+ elif func_name == 'solveh_banded':
+ from scipy.linalg._basic import _to_banded
+ args = (_to_banded(0, 2, args[0])[:, :-1], args[0][0, :-1])
+ elif func_name == 'cholesky_banded':
+ from scipy.linalg._basic import _to_banded
+ args = (_to_banded(0, 2, args[0])[:, :-1],)
+ elif func_name == 'solve_toeplitz':
+ c = args[0][1]
+ args = (c, np.ones_like(c))
+ return args
+
+
+@pytest.mark.skip_xp_backends(np_only=True)
+@pytest.mark.filterwarnings(
+ 'ignore:attempting to conjugate non-numeric dtype:DeprecationWarning'
+)
+@pytest.mark.filterwarnings('ignore:overflow encountered in dot:RuntimeWarning')
+@pytest.mark.filterwarnings('ignore:invalid value encountered in dot:RuntimeWarning')
+@pytest.mark.filterwarnings('ignore:logm result may be inaccurate:RuntimeWarning')
+@pytest.mark.filterwarnings('ignore:overflow encountered in multiply:RuntimeWarning')
+@pytest.mark.parametrize('func_name', _objs.keys())
+@pytest.mark.parametrize('tcode', 'e' + 'mMgG')
+def test_deprecations(func_name, tcode):
+ func = _objs[func_name]
+
+ if tcode in _skip_dict.get(func_name, ''):
+ return
+
+ a = np.arange(16).reshape(4, 4) + 8*np.eye(4)
+ a = a.T @ a
+ a = a.astype(tcode)
+
+ if func_name in _two_arg_names:
+ b = a.copy()
+ args = (a, b)
+ elif func_name in _three_arg_names:
+ args = (a, a, a)
+ elif func_name in _four_arg_names:
+ args = (a, a, a, a)
+ elif func_name in _arr_and_int_names:
+ args = (a, a.shape[0])
+ elif func_name in _arr_and_two_int_names:
+ args = (a, a.shape[0], a.shape[1])
+ elif func_name in ['cho_solve', 'cho_solve_banded']:
+ args = ((a, True), a)
+ else:
+ args = (a,)
+
+ args = _patch_args(func_name, args)
+
+ with pytest.warns(DeprecationWarning):
+ func(*args)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_extending.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..b994067f668e17f4eee2e1758409b1f275c901c9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_extending.py
@@ -0,0 +1,55 @@
+import os
+import platform
+import sysconfig
+
+import numpy as np
+import pytest
+
+from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython
+from scipy.linalg.blas import get_blas_funcs
+from scipy.linalg.lapack import get_lapack_funcs
+import scipy.linalg.cython_blas as cython_blas
+
+
+@pytest.mark.parallel_threads_limit(4) # 0.35 GiB per thread RAM usage
+@pytest.mark.fail_slow(120)
+# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
+@pytest.mark.skipif(IS_EDITABLE,
+ reason='Editable install cannot find .pxd headers.')
+@pytest.mark.skipif((platform.system() == 'Windows' and
+ sysconfig.get_config_var('Py_GIL_DISABLED')),
+ reason='gh-22039')
+@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
+ reason="Can't start subprocess")
+@pytest.mark.skipif(cython is None, reason="requires cython")
+def test_cython(tmp_path):
+ srcdir = os.path.dirname(os.path.dirname(__file__))
+ extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
+ # actually test the cython c-extensions
+ a = np.ones(8) * 3
+ b = np.ones(9)
+ c = np.ones(8) * 4
+ x = np.ones(9)
+ dgtsv = get_lapack_funcs('gtsv', dtype=np.float64, ilp64="preferred")
+ _, _, _, x, _ = dgtsv(a, b, c, x)
+ a = np.ones(8) * 3
+ b = np.ones(9)
+ c = np.ones(8) * 4
+ x_c = np.ones(9)
+ extensions.tridiag(a, b, c, x_c)
+ a = np.ones(8) * 3
+ b = np.ones(9)
+ c = np.ones(8) * 4
+ x_cpp = np.ones(9)
+ extensions_cpp.tridiag(a, b, c, x_cpp)
+ np.testing.assert_array_equal(x, x_cpp)
+ cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64)
+ cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64)
+ cdotu = get_blas_funcs('dotu', dtype=np.complex64, ilp64="preferred")
+ np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy))
+ np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy))
+
+ # Verify blas_int size consistency between installed and JIT-compiled modules
+ expected_size = cython_blas._blas_int_size()
+ assert extensions.get_blas_int_size() == expected_size
+ assert extensions_cpp.get_blas_int_size() == expected_size
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_fblas.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_fblas.py
new file mode 100644
index 0000000000000000000000000000000000000000..72f69345e56632c999d200a5ed94165139c28bc1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_fblas.py
@@ -0,0 +1,610 @@
+# Test interfaces to fortran blas.
+#
+# The tests are more of interface than they are of the underlying blas.
+# Only very small matrices checked -- N=3 or so.
+#
+# !! Complex calculations really aren't checked that carefully.
+# !! Only real valued complex numbers are used in tests.
+from itertools import product
+import sys
+
+import numpy as np
+import pytest
+from numpy import float32, float64, complex64, complex128, arange, array, \
+ zeros, shape, transpose, newaxis, common_type, conjugate
+
+from numpy.testing import (
+ assert_array_equal, assert_allclose, assert_array_almost_equal, assert_
+)
+
+import scipy
+
+blas_config = scipy.show_config(mode='dicts')['Build Dependencies']['blas']
+if blas_config['cython blas ilp64']:
+ pytestmark = pytest.skip(allow_module_level=True,
+ reason="LP64 _fblas wasn't built")
+
+from scipy.linalg import _fblas as fblas # noqa: E402
+
+
+# decimal accuracy to require between Python and LAPACK/BLAS calculations
+accuracy = 5
+
+# Since numpy.dot likely uses the same blas, use this routine
+# to check.
+
+
+def matrixmultiply(a, b):
+ if len(b.shape) == 1:
+ b_is_vector = True
+ b = b[:, newaxis]
+ else:
+ b_is_vector = False
+ assert_(a.shape[1] == b.shape[0])
+ c = zeros((a.shape[0], b.shape[1]), common_type(a, b))
+ for i in range(a.shape[0]):
+ for j in range(b.shape[1]):
+ s = 0
+ for k in range(a.shape[1]):
+ s += a[i, k] * b[k, j]
+ c[i, j] = s
+ if b_is_vector:
+ c = c.reshape((a.shape[0],))
+ return c
+
+##################################################
+# Test blas ?axpy
+
+
+class BaseAxpy:
+ ''' Mixin class for axpy tests '''
+
+ def test_default_a(self):
+ x = arange(3., dtype=self.dtype)
+ y = arange(3., dtype=x.dtype)
+ real_y = x*1.+y
+ y = self.blas_func(x, y)
+ assert_array_equal(real_y, y)
+
+ def test_simple(self):
+ x = arange(3., dtype=self.dtype)
+ y = arange(3., dtype=x.dtype)
+ real_y = x*3.+y
+ y = self.blas_func(x, y, a=3.)
+ assert_array_equal(real_y, y)
+
+ def test_x_stride(self):
+ x = arange(6., dtype=self.dtype)
+ y = zeros(3, x.dtype)
+ y = arange(3., dtype=x.dtype)
+ real_y = x[::2]*3.+y
+ y = self.blas_func(x, y, a=3., n=3, incx=2)
+ assert_array_equal(real_y, y)
+
+ def test_y_stride(self):
+ x = arange(3., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ real_y = x*3.+y[::2]
+ y = self.blas_func(x, y, a=3., n=3, incy=2)
+ assert_array_equal(real_y, y[::2])
+
+ def test_x_and_y_stride(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ real_y = x[::4]*3.+y[::2]
+ y = self.blas_func(x, y, a=3., n=3, incx=4, incy=2)
+ assert_array_equal(real_y, y[::2])
+
+ def test_x_bad_size(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ with pytest.raises(Exception, match='failed for 1st keyword'):
+ self.blas_func(x, y, n=4, incx=5)
+
+ def test_y_bad_size(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ with pytest.raises(Exception, match='failed for 1st keyword'):
+ self.blas_func(x, y, n=3, incy=5)
+
+
+try:
+ class TestSaxpy(BaseAxpy):
+ blas_func = fblas.saxpy
+ dtype = float32
+except AttributeError:
+ class TestSaxpy:
+ pass
+
+
+class TestDaxpy(BaseAxpy):
+ blas_func = fblas.daxpy
+ dtype = float64
+
+
+try:
+ class TestCaxpy(BaseAxpy):
+ blas_func = fblas.caxpy
+ dtype = complex64
+except AttributeError:
+ class TestCaxpy:
+ pass
+
+
+class TestZaxpy(BaseAxpy):
+ blas_func = fblas.zaxpy
+ dtype = complex128
+
+
+##################################################
+# Test blas ?scal
+
+class BaseScal:
+ ''' Mixin class for scal testing '''
+
+ def test_simple(self):
+ x = arange(3., dtype=self.dtype)
+ real_x = x*3.
+ x = self.blas_func(3., x)
+ assert_array_equal(real_x, x)
+
+ def test_x_stride(self):
+ x = arange(6., dtype=self.dtype)
+ real_x = x.copy()
+ real_x[::2] = x[::2]*array(3., self.dtype)
+ x = self.blas_func(3., x, n=3, incx=2)
+ assert_array_equal(real_x, x)
+
+ def test_x_bad_size(self):
+ x = arange(12., dtype=self.dtype)
+ with pytest.raises(Exception, match='failed for 1st keyword'):
+ self.blas_func(2., x, n=4, incx=5)
+
+
+try:
+ class TestSscal(BaseScal):
+ blas_func = fblas.sscal
+ dtype = float32
+except AttributeError:
+ class TestSscal:
+ pass
+
+
+class TestDscal(BaseScal):
+ blas_func = fblas.dscal
+ dtype = float64
+
+
+try:
+ class TestCscal(BaseScal):
+ blas_func = fblas.cscal
+ dtype = complex64
+except AttributeError:
+ class TestCscal:
+ pass
+
+
+class TestZscal(BaseScal):
+ blas_func = fblas.zscal
+ dtype = complex128
+
+
+##################################################
+# Test blas ?copy
+
+class BaseCopy:
+ ''' Mixin class for copy testing '''
+
+ def test_simple(self):
+ x = arange(3., dtype=self.dtype)
+ y = zeros(shape(x), x.dtype)
+ y = self.blas_func(x, y)
+ assert_array_equal(x, y)
+
+ def test_x_stride(self):
+ x = arange(6., dtype=self.dtype)
+ y = zeros(3, x.dtype)
+ y = self.blas_func(x, y, n=3, incx=2)
+ assert_array_equal(x[::2], y)
+
+ def test_y_stride(self):
+ x = arange(3., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ y = self.blas_func(x, y, n=3, incy=2)
+ assert_array_equal(x, y[::2])
+
+ def test_x_and_y_stride(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ y = self.blas_func(x, y, n=3, incx=4, incy=2)
+ assert_array_equal(x[::4], y[::2])
+
+ def test_x_bad_size(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ with pytest.raises(Exception, match='failed for 1st keyword'):
+ self.blas_func(x, y, n=4, incx=5)
+
+ def test_y_bad_size(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ with pytest.raises(Exception, match='failed for 1st keyword'):
+ self.blas_func(x, y, n=3, incy=5)
+
+ # def test_y_bad_type(self):
+ ## Hmmm. Should this work? What should be the output.
+ # x = arange(3.,dtype=self.dtype)
+ # y = zeros(shape(x))
+ # self.blas_func(x,y)
+ # assert_array_equal(x,y)
+
+
+try:
+ class TestScopy(BaseCopy):
+ blas_func = fblas.scopy
+ dtype = float32
+except AttributeError:
+ class TestScopy:
+ pass
+
+
+class TestDcopy(BaseCopy):
+ blas_func = fblas.dcopy
+ dtype = float64
+
+
+try:
+ class TestCcopy(BaseCopy):
+ blas_func = fblas.ccopy
+ dtype = complex64
+except AttributeError:
+ class TestCcopy:
+ pass
+
+
+class TestZcopy(BaseCopy):
+ blas_func = fblas.zcopy
+ dtype = complex128
+
+
+##################################################
+# Test blas ?swap
+
+class BaseSwap:
+ ''' Mixin class for swap tests '''
+
+ def test_simple(self):
+ x = arange(3., dtype=self.dtype)
+ y = zeros(shape(x), x.dtype)
+ desired_x = y.copy()
+ desired_y = x.copy()
+ x, y = self.blas_func(x, y)
+ assert_array_equal(desired_x, x)
+ assert_array_equal(desired_y, y)
+
+ def test_x_stride(self):
+ x = arange(6., dtype=self.dtype)
+ y = zeros(3, x.dtype)
+ desired_x = y.copy()
+ desired_y = x.copy()[::2]
+ x, y = self.blas_func(x, y, n=3, incx=2)
+ assert_array_equal(desired_x, x[::2])
+ assert_array_equal(desired_y, y)
+
+ def test_y_stride(self):
+ x = arange(3., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ desired_x = y.copy()[::2]
+ desired_y = x.copy()
+ x, y = self.blas_func(x, y, n=3, incy=2)
+ assert_array_equal(desired_x, x)
+ assert_array_equal(desired_y, y[::2])
+
+ def test_x_and_y_stride(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ desired_x = y.copy()[::2]
+ desired_y = x.copy()[::4]
+ x, y = self.blas_func(x, y, n=3, incx=4, incy=2)
+ assert_array_equal(desired_x, x[::4])
+ assert_array_equal(desired_y, y[::2])
+
+ def test_x_bad_size(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ with pytest.raises(Exception, match='failed for 1st keyword'):
+ self.blas_func(x, y, n=4, incx=5)
+
+ def test_y_bad_size(self):
+ x = arange(12., dtype=self.dtype)
+ y = zeros(6, x.dtype)
+ with pytest.raises(Exception, match='failed for 1st keyword'):
+ self.blas_func(x, y, n=3, incy=5)
+
+
+try:
+ class TestSswap(BaseSwap):
+ blas_func = fblas.sswap
+ dtype = float32
+except AttributeError:
+ class TestSswap:
+ pass
+
+
+class TestDswap(BaseSwap):
+ blas_func = fblas.dswap
+ dtype = float64
+
+
+try:
+ class TestCswap(BaseSwap):
+ blas_func = fblas.cswap
+ dtype = complex64
+except AttributeError:
+ class TestCswap:
+ pass
+
+
+class TestZswap(BaseSwap):
+ blas_func = fblas.zswap
+ dtype = complex128
+
+##################################################
+# Test blas ?gemv
+# This will be a mess to test all cases.
+
+
+class BaseGemv:
+ ''' Mixin class for gemv tests '''
+
+ def get_data(self, x_stride=1, y_stride=1):
+ rng = np.random.default_rng(1234)
+ mult = array(1, dtype=self.dtype)
+ if self.dtype in [complex64, complex128]:
+ mult = array(1+1j, dtype=self.dtype)
+ alpha = array(1., dtype=self.dtype) * mult
+ beta = array(1., dtype=self.dtype) * mult
+ a = rng.normal(0., 1., (3, 3)).astype(self.dtype) * mult
+ x = arange(shape(a)[0]*x_stride, dtype=self.dtype) * mult
+ y = arange(shape(a)[1]*y_stride, dtype=self.dtype) * mult
+ return alpha, beta, a, x, y
+
+ def test_simple(self):
+ alpha, beta, a, x, y = self.get_data()
+ desired_y = alpha*matrixmultiply(a, x)+beta*y
+ y = self.blas_func(alpha, a, x, beta, y)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_default_beta_y(self):
+ alpha, beta, a, x, y = self.get_data()
+ desired_y = matrixmultiply(a, x)
+ y = self.blas_func(1, a, x)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_simple_transpose(self):
+ alpha, beta, a, x, y = self.get_data()
+ desired_y = alpha*matrixmultiply(transpose(a), x)+beta*y
+ y = self.blas_func(alpha, a, x, beta, y, trans=1)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_simple_transpose_conj(self):
+ alpha, beta, a, x, y = self.get_data()
+ desired_y = alpha*matrixmultiply(transpose(conjugate(a)), x)+beta*y
+ y = self.blas_func(alpha, a, x, beta, y, trans=2)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_x_stride(self):
+ alpha, beta, a, x, y = self.get_data(x_stride=2)
+ desired_y = alpha*matrixmultiply(a, x[::2])+beta*y
+ y = self.blas_func(alpha, a, x, beta, y, incx=2)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_x_stride_transpose(self):
+ alpha, beta, a, x, y = self.get_data(x_stride=2)
+ desired_y = alpha*matrixmultiply(transpose(a), x[::2])+beta*y
+ y = self.blas_func(alpha, a, x, beta, y, trans=1, incx=2)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_x_stride_assert(self):
+ # What is the use of this test?
+ alpha, beta, a, x, y = self.get_data(x_stride=2)
+ with pytest.raises(Exception, match='failed for 3rd argument'):
+ y = self.blas_func(1, a, x, 1, y, trans=0, incx=3)
+ with pytest.raises(Exception, match='failed for 3rd argument'):
+ y = self.blas_func(1, a, x, 1, y, trans=1, incx=3)
+
+ def test_y_stride(self):
+ alpha, beta, a, x, y = self.get_data(y_stride=2)
+ desired_y = y.copy()
+ desired_y[::2] = alpha*matrixmultiply(a, x)+beta*y[::2]
+ y = self.blas_func(alpha, a, x, beta, y, incy=2)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_y_stride_transpose(self):
+ alpha, beta, a, x, y = self.get_data(y_stride=2)
+ desired_y = y.copy()
+ desired_y[::2] = alpha*matrixmultiply(transpose(a), x)+beta*y[::2]
+ y = self.blas_func(alpha, a, x, beta, y, trans=1, incy=2)
+ assert_array_almost_equal(desired_y, y)
+
+ def test_y_stride_assert(self):
+ # What is the use of this test?
+ alpha, beta, a, x, y = self.get_data(y_stride=2)
+ with pytest.raises(Exception, match='failed for 2nd keyword'):
+ y = self.blas_func(1, a, x, 1, y, trans=0, incy=3)
+ with pytest.raises(Exception, match='failed for 2nd keyword'):
+ y = self.blas_func(1, a, x, 1, y, trans=1, incy=3)
+
+
+try:
+ class TestSgemv(BaseGemv):
+ blas_func = fblas.sgemv
+ dtype = float32
+
+ @pytest.mark.skipif(sys.platform != 'darwin', reason="MacOS specific test")
+ def test_sgemv_on_osx(self):
+ def aligned_array(shape, align, dtype, order='C'):
+ # Make array shape `shape` with aligned at `align` bytes
+ d = dtype()
+ # Make array of correct size with `align` extra bytes
+ N = np.prod(shape)
+ tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8)
+ address = tmp.__array_interface__["data"][0]
+ # Find offset into array giving desired alignment
+ for offset in range(align):
+ if (address + offset) % align == 0:
+ break
+ tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype)
+ return tmp.reshape(shape, order=order)
+
+ def as_aligned(arr, align, dtype, order='C'):
+ # Copy `arr` into an aligned array with same shape
+ aligned = aligned_array(arr.shape, align, dtype, order)
+ aligned[:] = arr[:]
+ return aligned
+
+ def assert_dot_close(A, X, desired):
+ assert_allclose(self.blas_func(1.0, A, X), desired,
+ rtol=1e-5, atol=1e-7)
+
+ testdata = product((15, 32), (10000,), (200, 89), ('C', 'F'))
+ rng = np.random.default_rng(1234)
+ for align, m, n, a_order in testdata:
+ A_d = rng.random((m, n))
+ X_d = rng.random(n)
+ desired = np.dot(A_d, X_d)
+ # Calculation with aligned single precision
+ A_f = as_aligned(A_d, align, np.float32, order=a_order)
+ X_f = as_aligned(X_d, align, np.float32, order=a_order)
+ assert_dot_close(A_f, X_f, desired)
+
+except AttributeError:
+ class TestSgemv:
+ pass
+
+
+class TestDgemv(BaseGemv):
+ blas_func = fblas.dgemv
+ dtype = float64
+
+
+try:
+ class TestCgemv(BaseGemv):
+ blas_func = fblas.cgemv
+ dtype = complex64
+except AttributeError:
+ class TestCgemv:
+ pass
+
+
+class TestZgemv(BaseGemv):
+ blas_func = fblas.zgemv
+ dtype = complex128
+
+
+"""
+##################################################
+### Test blas ?ger
+### This will be a mess to test all cases.
+
+class BaseGer:
+ def get_data(self,x_stride=1,y_stride=1):
+ rng = np.random.default_rng(1234)
+ alpha = array(1., dtype = self.dtype)
+ a = rng.normal(0.,1.,(3,3)).astype(self.dtype)
+ x = arange(shape(a)[0]*x_stride,dtype=self.dtype)
+ y = arange(shape(a)[1]*y_stride,dtype=self.dtype)
+ return alpha,a,x,y
+ def test_simple(self):
+ alpha,a,x,y = self.get_data()
+ # transpose takes care of Fortran vs. C(and Python) memory layout
+ desired_a = alpha*transpose(x[:,newaxis]*y) + a
+ self.blas_func(x,y,a)
+ assert_array_almost_equal(desired_a,a)
+ def test_x_stride(self):
+ alpha,a,x,y = self.get_data(x_stride=2)
+ desired_a = alpha*transpose(x[::2,newaxis]*y) + a
+ self.blas_func(x,y,a,incx=2)
+ assert_array_almost_equal(desired_a,a)
+ def test_x_stride_assert(self):
+ alpha,a,x,y = self.get_data(x_stride=2)
+ with pytest.raises(ValueError, match='foo'):
+ self.blas_func(x,y,a,incx=3)
+ def test_y_stride(self):
+ alpha,a,x,y = self.get_data(y_stride=2)
+ desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a
+ self.blas_func(x,y,a,incy=2)
+ assert_array_almost_equal(desired_a,a)
+
+ def test_y_stride_assert(self):
+ alpha,a,x,y = self.get_data(y_stride=2)
+ with pytest.raises(ValueError, match='foo'):
+ self.blas_func(a,x,y,incy=3)
+
+class TestSger(BaseGer):
+ blas_func = fblas.sger
+ dtype = float32
+class TestDger(BaseGer):
+ blas_func = fblas.dger
+ dtype = float64
+"""
+##################################################
+# Test blas ?gerc
+# This will be a mess to test all cases.
+
+"""
+class BaseGerComplex(BaseGer):
+ def get_data(self,x_stride=1,y_stride=1):
+ rng = np.random.default_rng(1234)
+ alpha = array(1+1j, dtype = self.dtype)
+ a = rng.normal(0.,1.,(3,3)).astype(self.dtype)
+ a = a + rng.normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype)
+ x = rng.normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype)
+ x = x + x * array(1j, dtype = self.dtype)
+ y = rng.normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype)
+ y = y + y * array(1j, dtype = self.dtype)
+ return alpha,a,x,y
+ def test_simple(self):
+ alpha,a,x,y = self.get_data()
+ # transpose takes care of Fortran vs. C(and Python) memory layout
+ a = a * array(0.,dtype = self.dtype)
+ #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a
+ desired_a = alpha*transpose(x[:,newaxis]*y) + a
+ #self.blas_func(x,y,a,alpha = alpha)
+ fblas.cgeru(x,y,a,alpha = alpha)
+ assert_array_almost_equal(desired_a,a)
+
+ #def test_x_stride(self):
+ # alpha,a,x,y = self.get_data(x_stride=2)
+ # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a
+ # self.blas_func(x,y,a,incx=2)
+ # assert_array_almost_equal(desired_a,a)
+ #def test_y_stride(self):
+ # alpha,a,x,y = self.get_data(y_stride=2)
+ # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a
+ # self.blas_func(x,y,a,incy=2)
+ # assert_array_almost_equal(desired_a,a)
+
+class TestCgeru(BaseGerComplex):
+ blas_func = fblas.cgeru
+ dtype = complex64
+ def transform(self,x):
+ return x
+class TestZgeru(BaseGerComplex):
+ blas_func = fblas.zgeru
+ dtype = complex128
+ def transform(self,x):
+ return x
+
+class TestCgerc(BaseGerComplex):
+ blas_func = fblas.cgerc
+ dtype = complex64
+ def transform(self,x):
+ return conjugate(x)
+
+class TestZgerc(BaseGerComplex):
+ blas_func = fblas.zgerc
+ dtype = complex128
+ def transform(self,x):
+ return conjugate(x)
+"""
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_interpolative.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc250b475afb8087a09021a5bc7d803c137761e5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_interpolative.py
@@ -0,0 +1,232 @@
+# ******************************************************************************
+# Copyright (C) 2013 Kenneth L. Ho
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer. Redistributions in binary
+# form must reproduce the above copyright notice, this list of conditions and
+# the following disclaimer in the documentation and/or other materials
+# provided with the distribution.
+#
+# None of the names of the copyright holders may be used to endorse or
+# promote products derived from this software without specific prior written
+# permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+# ******************************************************************************
+
+import scipy.linalg.interpolative as pymatrixid
+import numpy as np
+from scipy.linalg import hilbert, svdvals, norm
+from scipy.sparse.linalg import aslinearoperator
+from scipy.linalg.interpolative import interp_decomp
+
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+ assert_array_equal)
+import pytest
+from pytest import raises as assert_raises
+
+
+@pytest.fixture()
+def eps():
+ yield 1e-12
+
+
+@pytest.fixture()
+def rng():
+ rng = np.random.default_rng(1718313768084012)
+ yield rng
+
+
+@pytest.fixture(params=[np.float64, np.complex128])
+def A(request):
+ # construct Hilbert matrix
+ # set parameters
+ n = 300
+ yield hilbert(n).astype(request.param)
+
+
+@pytest.fixture()
+def L(A):
+ yield aslinearoperator(A)
+
+
+@pytest.fixture()
+def rank(A, eps):
+ S = np.linalg.svd(A, compute_uv=False)
+ try:
+ rank = np.nonzero(S < eps)[0][0]
+ except IndexError:
+ rank = A.shape[0]
+ return rank
+
+
+class TestInterpolativeDecomposition:
+
+ @pytest.mark.parametrize(
+ "rand,lin_op",
+ [(False, False), (True, False), (True, True)])
+ def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng):
+ # Test ID routines on a Hilbert matrix.
+ A_or_L = A if not lin_op else L
+
+ k, idx, proj = pymatrixid.interp_decomp(A_or_L, eps, rand=rand, rng=rng)
+ B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+ @pytest.mark.parametrize(
+ "rand,lin_op",
+ [(False, False), (True, False), (True, True)])
+ def test_real_id_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
+ k = rank
+ A_or_L = A if not lin_op else L
+
+ idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
+ B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+ @pytest.mark.parametrize("rand,lin_op", [(False, False)])
+ def test_real_id_skel_and_interp_matrices(
+ self, A, L, eps, rank, rand, lin_op, rng):
+ k = rank
+ A_or_L = A if not lin_op else L
+
+ idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
+ P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+ B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+ assert_allclose(B, A[:, idx[:k]], rtol=eps, atol=1e-08)
+ assert_allclose(B @ P, A, rtol=eps, atol=1e-08)
+
+ @pytest.mark.parametrize(
+ "rand,lin_op",
+ [(False, False), (True, False), (True, True)])
+ def test_svd_fixed_precision(self, A, L, eps, rand, lin_op, rng):
+ A_or_L = A if not lin_op else L
+
+ U, S, V = pymatrixid.svd(A_or_L, eps, rand=rand, rng=rng)
+ B = U * S @ V.T.conj()
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+ @pytest.mark.parametrize(
+ "rand,lin_op",
+ [(False, False), (True, False), (True, True)])
+ def test_svd_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
+ k = rank
+ A_or_L = A if not lin_op else L
+
+ U, S, V = pymatrixid.svd(A_or_L, k, rand=rand, rng=rng)
+ B = U * S @ V.T.conj()
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+ def test_id_to_svd(self, A, eps, rank):
+ k = rank
+
+ idx, proj = pymatrixid.interp_decomp(A, k, rand=False)
+ U, S, V = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj)
+ B = U * S @ V.T.conj()
+ assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+ def test_estimate_spectral_norm(self, A, rng):
+ s = svdvals(A)
+ norm_2_est = pymatrixid.estimate_spectral_norm(A, rng=rng)
+ assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
+
+ def test_estimate_spectral_norm_diff(self, A, rng):
+ B = A.copy()
+ B[:, 0] *= 1.2
+ s = svdvals(A - B)
+ norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B, rng=rng)
+ assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
+
+ def test_rank_estimates_array(self, A, rng):
+ B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
+
+ for M in [A, B]:
+ rank_tol = 1e-9
+ rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
+ rank_est = pymatrixid.estimate_rank(M, rank_tol, rng=rng)
+ assert_(rank_est >= rank_np)
+ assert_(rank_est <= rank_np + 10)
+
+ def test_rank_estimates_lin_op(self, A, rng):
+ B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
+
+ for M in [A, B]:
+ ML = aslinearoperator(M)
+ rank_tol = 1e-9
+ rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
+ rank_est = pymatrixid.estimate_rank(ML, rank_tol, rng=rng)
+ assert_(rank_est >= rank_np - 4)
+ assert_(rank_est <= rank_np + 4)
+
+ def test_badcall(self):
+ A = hilbert(5).astype(np.float32)
+ with assert_raises(ValueError):
+ pymatrixid.interp_decomp(A, 1e-6, rand=False)
+
+ def test_rank_too_large(self):
+ # svd(array, k) should not segfault
+ a = np.ones((4, 3))
+ with assert_raises(ValueError):
+ pymatrixid.svd(a, 4)
+
+ def test_full_rank(self):
+ eps = 1.0e-12
+ rng = np.random.default_rng(1234)
+ # fixed precision
+ A = rng.random((16, 8))
+ k, idx, proj = pymatrixid.interp_decomp(A, eps)
+ assert_equal(k, A.shape[1])
+
+ P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+ B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+ assert_allclose(A, B @ P)
+
+ # fixed rank
+ idx, proj = pymatrixid.interp_decomp(A, k)
+
+ P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+ B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+ assert_allclose(A, B @ P)
+
+ @pytest.mark.parametrize("dtype", [np.float64, np.complex128])
+ @pytest.mark.parametrize("rand", [True, False])
+ @pytest.mark.parametrize("eps", [1, 0.1])
+ def test_bug_9793(self, dtype, rand, eps):
+ A = np.array([[-1, -1, -1, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1],
+ [1, 0, 0, 1, 0, 0],
+ [0, 1, 0, 0, 1, 0],
+ [0, 0, 1, 0, 0, 1]],
+ dtype=dtype, order="C")
+ B = A.copy()
+ interp_decomp(A.T, eps, rand=rand)
+ assert_array_equal(A, B)
+
+ def test_svd_aslinearoperator_shape_check(self):
+ # See gh-issue #22451
+ rng = np.random.default_rng(1744580941832515)
+ x = rng.uniform(size=[7, 5])
+ xl = aslinearoperator(x)
+ u, s, v = pymatrixid.svd(xl, 3)
+ assert_equal(u.shape, (7, 3))
+ assert_equal(s.shape, (3,))
+ assert_equal(v.shape, (5, 3))
+
+ x = rng.uniform(size=[4, 9])
+ xl = aslinearoperator(x)
+ u, s, v = pymatrixid.svd(xl, 2)
+ assert_equal(u.shape, (4, 2))
+ assert_equal(s.shape, (2,))
+ assert_equal(v.shape, (9, 2))
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_lapack.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..180dc22db6600854fdce7fb8fd1460f27d2f87b0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_lapack.py
@@ -0,0 +1,3603 @@
+#
+# Created by: Pearu Peterson, September 2002
+#
+
+from functools import reduce
+import sysconfig
+
+from numpy.testing import (assert_equal, assert_array_almost_equal, assert_,
+ assert_allclose, assert_almost_equal,
+ assert_array_equal)
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import (eye, ones, zeros, zeros_like, triu, tril, tril_indices,
+ triu_indices)
+
+from scipy.linalg import (
+ lapack, inv, svd, cholesky, solve, ldl, norm, block_diag, qr, eigh, qz
+)
+from scipy.linalg._basic import _to_banded
+from scipy.linalg.lapack import _compute_lwork
+from scipy.stats import ortho_group, unitary_group
+from scipy.sparse import diags_array
+
+from scipy.linalg.lapack import get_lapack_funcs
+from scipy.linalg.blas import get_blas_funcs
+
+from scipy.__config__ import CONFIG
+blas_provider = blas_version = None
+blas_provider = CONFIG['Build Dependencies']['blas']['name']
+blas_version = CONFIG['Build Dependencies']['blas']['version']
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+def generate_random_dtype_array(shape, dtype, rng):
+ # generates a random matrix of desired data type of shape
+ if dtype in COMPLEX_DTYPES:
+ return (rng.rand(*shape)
+ + rng.rand(*shape)*1.0j).astype(dtype)
+ return rng.rand(*shape).astype(dtype)
+
+
+def test_lapack_documented():
+ """Test that all entries are in the doc."""
+ if lapack.__doc__ is None: # just in case there is a python -OO
+ pytest.skip('lapack.__doc__ is None')
+ names = set(lapack.__doc__.split())
+ ignore_list = {
+ "absolute_import",
+ "division",
+ "find_best_lapack_type",
+ "flapack",
+ "print_function",
+ "HAS_ILP64",
+ "HAS_LP64",
+ "np",
+ }
+ missing = list()
+ for name in dir(lapack):
+ if (not name.startswith('_') and name not in ignore_list and
+ name not in names):
+ missing.append(name)
+ assert missing == [], 'Name(s) missing from lapack.__doc__ or ignore_list'
+
+
+def test_lp64_ilp64_blas_lapack_both_or_none():
+ from scipy.linalg.blas import HAS_ILP64 as blas_has_ilp64
+ from scipy.linalg.lapack import HAS_ILP64 as lapack_has_ilp64
+ assert blas_has_ilp64 == lapack_has_ilp64
+
+ from scipy.linalg.blas import HAS_LP64 as blas_has_lp64
+ from scipy.linalg.lapack import HAS_LP64 as lapack_has_lp64
+ assert blas_has_lp64 == lapack_has_lp64
+
+
+class TestFlapackSimple:
+
+ def test_gebal(self):
+ a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+ a1 = [[1, 0, 0, 3e-4],
+ [4, 0, 0, 2e-3],
+ [7, 1, 0, 0],
+ [0, 1, 0, 0]]
+ for dtype in DTYPES:
+ f = get_lapack_funcs('gebal', dtype=dtype)
+ if f is None:
+ continue
+ ba, lo, hi, pivscale, info = f(a)
+ assert_(not info, repr(info))
+ assert_array_almost_equal(ba, a)
+ assert_equal((lo, hi), (0, len(a[0])-1))
+ assert_array_almost_equal(pivscale, np.ones(len(a)))
+
+ ba, lo, hi, pivscale, info = f(a1, permute=1, scale=1)
+ assert_(not info, repr(info))
+ # print(a1)
+ # print(ba, lo, hi, pivscale)
+
+ def test_gehrd(self):
+ a = [[-149, -50, -154],
+ [537, 180, 546],
+ [-27, -9, -25]]
+ for dtype in [np.float64]:
+ f = get_lapack_funcs('gehrd', dtype=dtype)
+ if f is None:
+ continue
+ ht, tau, info = f(a)
+ assert_(not info, repr(info))
+
+ def test_trsyl(self):
+ a = np.array([[1, 2], [0, 4]])
+ b = np.array([[5, 6], [0, 8]])
+ c = np.array([[9, 10], [11, 12]])
+ trans = 'T'
+
+ # Test single and double implementations, including most
+ # of the options
+ for dtype in 'fdFD':
+ a1, b1, c1 = a.astype(dtype), b.astype(dtype), c.astype(dtype)
+ trsyl, = get_lapack_funcs(('trsyl',), (a1,))
+ if dtype.isupper(): # is complex dtype
+ a1[0] += 1j
+ trans = 'C'
+
+ x, scale, info = trsyl(a1, b1, c1)
+ assert_array_almost_equal(np.dot(a1, x) + np.dot(x, b1),
+ scale * c1)
+
+ x, scale, info = trsyl(a1, b1, c1, trana=trans, tranb=trans)
+ assert_array_almost_equal(
+ np.dot(a1.conjugate().T, x) + np.dot(x, b1.conjugate().T),
+ scale * c1, decimal=4)
+
+ x, scale, info = trsyl(a1, b1, c1, isgn=-1)
+ assert_array_almost_equal(np.dot(a1, x) - np.dot(x, b1),
+ scale * c1, decimal=4)
+
+ def test_lange(self):
+ a = np.array([
+ [-149, -50, -154],
+ [537, 180, 546],
+ [-27, -9, -25]])
+
+ for dtype in 'fdFD':
+ for norm_str in 'Mm1OoIiFfEe':
+ a1 = a.astype(dtype)
+ if dtype.isupper():
+ # is complex dtype
+ a1[0, 0] += 1j
+
+ lange, = get_lapack_funcs(('lange',), (a1,))
+ value = lange(norm_str, a1)
+
+ if norm_str in 'FfEe':
+ if dtype in 'Ff':
+ decimal = 3
+ else:
+ decimal = 7
+ ref = np.sqrt(np.sum(np.square(np.abs(a1))))
+ assert_almost_equal(value, ref, decimal)
+ else:
+ if norm_str in 'Mm':
+ ref = np.max(np.abs(a1))
+ elif norm_str in '1Oo':
+ ref = np.max(np.sum(np.abs(a1), axis=0))
+ elif norm_str in 'Ii':
+ ref = np.max(np.sum(np.abs(a1), axis=1))
+
+ assert_equal(value, ref)
+
+
+class TestLeastSquaresSolvers:
+
+ def test_gels(self):
+ rng = np.random.default_rng(1234)
+ # Test fat/tall matrix argument handling - gh-issue #8329
+ for ind, dtype in enumerate(DTYPES):
+ m = 10
+ n = 20
+ nrhs = 1
+ a1 = rng.random((m, n)).astype(dtype)
+ b1 = rng.random(n).astype(dtype)
+ gls, glslw = get_lapack_funcs(('gels', 'gels_lwork'), dtype=dtype)
+
+ # Request of sizes
+ lwork = _compute_lwork(glslw, m, n, nrhs)
+ _, _, info = gls(a1, b1, lwork=lwork)
+ assert_(info >= 0)
+ _, _, info = gls(a1, b1, trans='TTCC'[ind], lwork=lwork)
+ assert_(info >= 0)
+
+ for dtype in REAL_DTYPES:
+ a1 = np.array([[1.0, 2.0],
+ [4.0, 5.0],
+ [7.0, 8.0]], dtype=dtype)
+ b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+ gels, gels_lwork, geqrf = get_lapack_funcs(
+ ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ lwork = _compute_lwork(gels_lwork, m, n, nrhs)
+
+ lqr, x, info = gels(a1, b1, lwork=lwork)
+ assert_allclose(x[:-1], np.array([-14.333333333333323,
+ 14.999999999999991],
+ dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+ lqr_truth, _, _, _ = geqrf(a1)
+ assert_array_equal(lqr, lqr_truth)
+
+ for dtype in COMPLEX_DTYPES:
+ a1 = np.array([[1.0+4.0j, 2.0],
+ [4.0+0.5j, 5.0-3.0j],
+ [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+ b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+ gels, gels_lwork, geqrf = get_lapack_funcs(
+ ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ lwork = _compute_lwork(gels_lwork, m, n, nrhs)
+
+ lqr, x, info = gels(a1, b1, lwork=lwork)
+ assert_allclose(x[:-1],
+ np.array([1.161753632288328-1.901075709391912j,
+ 1.735882340522193+1.521240901196909j],
+ dtype=dtype), rtol=25*np.finfo(dtype).eps)
+ lqr_truth, _, _, _ = geqrf(a1)
+ assert_array_equal(lqr, lqr_truth)
+
+ def test_gelsd(self):
+ for dtype in REAL_DTYPES:
+ a1 = np.array([[1.0, 2.0],
+ [4.0, 5.0],
+ [7.0, 8.0]], dtype=dtype)
+ b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+ gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
+ (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ work, iwork, info = gelsd_lwork(m, n, nrhs, -1)
+ lwork = int(np.real(work))
+ iwork_size = iwork
+
+ x, s, rank, info = gelsd(a1, b1, lwork, iwork_size,
+ -1, False, False)
+ assert_allclose(x[:-1], np.array([-14.333333333333323,
+ 14.999999999999991],
+ dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+ assert_allclose(s, np.array([12.596017180511966,
+ 0.583396253199685], dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+
+ for dtype in COMPLEX_DTYPES:
+ a1 = np.array([[1.0+4.0j, 2.0],
+ [4.0+0.5j, 5.0-3.0j],
+ [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+ b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+ gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
+ (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ work, rwork, iwork, info = gelsd_lwork(m, n, nrhs, -1)
+ lwork = int(np.real(work))
+ rwork_size = int(rwork)
+ iwork_size = iwork
+
+ x, s, rank, info = gelsd(a1, b1, lwork, rwork_size, iwork_size,
+ -1, False, False)
+ assert_allclose(x[:-1],
+ np.array([1.161753632288328-1.901075709391912j,
+ 1.735882340522193+1.521240901196909j],
+ dtype=dtype), rtol=25*np.finfo(dtype).eps)
+ assert_allclose(s,
+ np.array([13.035514762572043, 4.337666985231382],
+ dtype=dtype), rtol=25*np.finfo(dtype).eps)
+
+ def test_gelss(self):
+
+ for dtype in REAL_DTYPES:
+ a1 = np.array([[1.0, 2.0],
+ [4.0, 5.0],
+ [7.0, 8.0]], dtype=dtype)
+ b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+ gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
+ (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ work, info = gelss_lwork(m, n, nrhs, -1)
+ lwork = int(np.real(work))
+
+ v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
+ assert_allclose(x[:-1], np.array([-14.333333333333323,
+ 14.999999999999991],
+ dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+ assert_allclose(s, np.array([12.596017180511966,
+ 0.583396253199685], dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+
+ for dtype in COMPLEX_DTYPES:
+ a1 = np.array([[1.0+4.0j, 2.0],
+ [4.0+0.5j, 5.0-3.0j],
+ [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+ b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+ gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
+ (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ work, info = gelss_lwork(m, n, nrhs, -1)
+ lwork = int(np.real(work))
+
+ v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
+ assert_allclose(x[:-1],
+ np.array([1.161753632288328-1.901075709391912j,
+ 1.735882340522193+1.521240901196909j],
+ dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+ assert_allclose(s, np.array([13.035514762572043,
+ 4.337666985231382], dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+
+ def test_gelsy(self):
+
+ for dtype in REAL_DTYPES:
+ a1 = np.array([[1.0, 2.0],
+ [4.0, 5.0],
+ [7.0, 8.0]], dtype=dtype)
+ b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+ gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
+ (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
+ lwork = int(np.real(work))
+
+ jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+ v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
+ lwork, False, False)
+ assert_allclose(x[:-1], np.array([-14.333333333333323,
+ 14.999999999999991],
+ dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+
+ for dtype in COMPLEX_DTYPES:
+ a1 = np.array([[1.0+4.0j, 2.0],
+ [4.0+0.5j, 5.0-3.0j],
+ [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+ b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+ gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
+ (a1, b1))
+
+ m, n = a1.shape
+ if len(b1.shape) == 2:
+ nrhs = b1.shape[1]
+ else:
+ nrhs = 1
+
+ # Request of sizes
+ work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
+ lwork = int(np.real(work))
+
+ jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+ v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
+ lwork, False, False)
+ assert_allclose(x[:-1],
+ np.array([1.161753632288328-1.901075709391912j,
+ 1.735882340522193+1.521240901196909j],
+ dtype=dtype),
+ rtol=25*np.finfo(dtype).eps)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('shape', [(3, 4), (5, 2), (2**18, 2**18)])
+def test_geqrf_lwork(dtype, shape):
+ geqrf_lwork = get_lapack_funcs(('geqrf_lwork'), dtype=dtype)
+ m, n = shape
+ lwork, info = geqrf_lwork(m=m, n=n)
+ assert_equal(info, 0)
+
+
+class TestRegression:
+
+ def test_ticket_1645(self):
+ # Check that RQ routines have correct lwork
+ for dtype in DTYPES:
+ a = np.zeros((300, 2), dtype=dtype)
+
+ gerqf, = get_lapack_funcs(['gerqf'], [a])
+ assert_raises(Exception, gerqf, a, lwork=2)
+ rq, tau, work, info = gerqf(a)
+
+ if dtype in REAL_DTYPES:
+ orgrq, = get_lapack_funcs(['orgrq'], [a])
+ assert_raises(Exception, orgrq, rq[-2:], tau, lwork=1)
+ orgrq(rq[-2:], tau, lwork=2)
+ elif dtype in COMPLEX_DTYPES:
+ ungrq, = get_lapack_funcs(['ungrq'], [a])
+ assert_raises(Exception, ungrq, rq[-2:], tau, lwork=1)
+ ungrq(rq[-2:], tau, lwork=2)
+
+
+class TestDpotr:
+ # 'lower' argument of dportf/dpotri
+ @pytest.mark.parametrize("lower", [True, False])
+ @pytest.mark.parametrize("clean", [True, False])
+ def test_gh_2691(self, lower, clean):
+ rng = np.random.default_rng(42)
+ x = rng.normal(size=(3, 3))
+ a = x.dot(x.T)
+
+ dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, ))
+
+ c, _ = dpotrf(a, lower, clean=clean)
+ dpt = dpotri(c, lower)[0]
+
+ if lower:
+ assert_allclose(np.tril(dpt), np.tril(inv(a)))
+ else:
+ assert_allclose(np.triu(dpt), np.triu(inv(a)))
+
+
+class TestDlasd4:
+ def test_sing_val_update(self):
+
+ sigmas = np.array([4., 3., 2., 0])
+ m_vec = np.array([3.12, 5.7, -4.8, -2.2])
+
+ M = np.hstack((np.vstack((np.diag(sigmas[0:-1]),
+ np.zeros((1, len(m_vec) - 1)))),
+ m_vec[:, np.newaxis]))
+ SM = svd(M, full_matrices=False, compute_uv=False, overwrite_a=False,
+ check_finite=False)
+
+ it_len = len(sigmas)
+ sgm = np.concatenate((sigmas[::-1], [sigmas[0] + it_len*norm(m_vec)]))
+ mvc = np.concatenate((m_vec[::-1], (0,)))
+
+ lasd4 = get_lapack_funcs('lasd4', (sigmas,))
+
+ roots = []
+ for i in range(0, it_len):
+ res = lasd4(i, sgm, mvc)
+ roots.append(res[1])
+
+ assert_(
+ (res[3] <= 0),
+ f"LAPACK root finding dlasd4 failed to find the singular value {i}"
+ )
+ roots = np.array(roots)[::-1]
+
+ assert_((not np.any(np.isnan(roots)), "There are NaN roots"))
+ assert_allclose(SM, roots, atol=100*np.finfo(np.float64).eps,
+ rtol=100*np.finfo(np.float64).eps)
+
+
+class TestTbtrs:
+
+ @pytest.mark.parametrize('dtype', DTYPES)
+ def test_nag_example_f07vef_f07vsf(self, dtype):
+ """Test real (f07vef) and complex (f07vsf) examples from NAG
+
+ Examples available from:
+ * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vef.html
+ * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vsf.html
+
+ """
+ if dtype in REAL_DTYPES:
+ ab = np.array([[-4.16, 4.78, 6.32, 0.16],
+ [-2.25, 5.86, -4.82, 0]],
+ dtype=dtype)
+ b = np.array([[-16.64, -4.16],
+ [-13.78, -16.59],
+ [13.10, -4.94],
+ [-14.14, -9.96]],
+ dtype=dtype)
+ x_out = np.array([[4, 1],
+ [-1, -3],
+ [3, 2],
+ [2, -2]],
+ dtype=dtype)
+ elif dtype in COMPLEX_DTYPES:
+ ab = np.array([[-1.94+4.43j, 4.12-4.27j, 0.43-2.66j, 0.44+0.1j],
+ [-3.39+3.44j, -1.84+5.52j, 1.74 - 0.04j, 0],
+ [1.62+3.68j, -2.77-1.93j, 0, 0]],
+ dtype=dtype)
+ b = np.array([[-8.86 - 3.88j, -24.09 - 5.27j],
+ [-15.57 - 23.41j, -57.97 + 8.14j],
+ [-7.63 + 22.78j, 19.09 - 29.51j],
+ [-14.74 - 2.40j, 19.17 + 21.33j]],
+ dtype=dtype)
+ x_out = np.array([[2j, 1 + 5j],
+ [1 - 3j, -7 - 2j],
+ [-4.001887 - 4.988417j, 3.026830 + 4.003182j],
+ [1.996158 - 1.045105j, -6.103357 - 8.986653j]],
+ dtype=dtype)
+ else:
+ raise ValueError(f"Datatype {dtype} not understood.")
+
+ tbtrs = get_lapack_funcs(('tbtrs'), dtype=dtype)
+ x, info = tbtrs(ab=ab, b=b, uplo='L')
+ assert_equal(info, 0)
+ assert_allclose(x, x_out, rtol=0, atol=1e-5)
+
+ @pytest.mark.parametrize('dtype,trans',
+ [(dtype, trans)
+ for dtype in DTYPES for trans in ['N', 'T', 'C']
+ if not (trans == 'C' and dtype in REAL_DTYPES)])
+ @pytest.mark.parametrize('uplo', ['U', 'L'])
+ @pytest.mark.parametrize('diag', ['N', 'U'])
+ def test_random_matrices(self, dtype, trans, uplo, diag):
+ rng = np.random.RandomState(1724)
+
+ # n, nrhs, kd are used to specify A and b.
+ # A is of shape n x n with kd super/sub-diagonals
+ # b is of shape n x nrhs matrix
+ n, nrhs, kd = 4, 3, 2
+ tbtrs = get_lapack_funcs('tbtrs', dtype=dtype)
+
+ is_upper = (uplo == 'U')
+ ku = kd * is_upper
+ kl = kd - ku
+
+ # Construct the diagonal and kd super/sub diagonals of A with
+ # the corresponding offsets.
+ band_offsets = range(ku, -kl - 1, -1)
+ band_widths = [n - abs(x) for x in band_offsets]
+ bands = [generate_random_dtype_array((width,), dtype, rng)
+ for width in band_widths]
+
+ if diag == 'U': # A must be unit triangular
+ bands[ku] = np.ones(n, dtype=dtype)
+
+ # Construct the diagonal banded matrix A from the bands and offsets.
+ a = diags_array(bands, offsets=band_offsets, format='dia')
+
+ # Convert A into banded storage form
+ ab = np.zeros((kd + 1, n), dtype)
+ for row, k in enumerate(band_offsets):
+ ab[row, max(k, 0):min(n+k, n)] = a.diagonal(k)
+
+ # The RHS values.
+ b = generate_random_dtype_array((n, nrhs), dtype, rng)
+
+ x, info = tbtrs(ab=ab, b=b, uplo=uplo, trans=trans, diag=diag)
+ assert_equal(info, 0)
+
+ if trans == 'N':
+ assert_allclose(a @ x, b, rtol=5e-5)
+ elif trans == 'T':
+ assert_allclose(a.T @ x, b, rtol=5e-5)
+ elif trans == 'C':
+ assert_allclose(a.T.conjugate() @ x, b, rtol=5e-5)
+ else:
+ raise ValueError('Invalid trans argument')
+
+ @pytest.mark.parametrize('uplo,trans,diag',
+ [['U', 'N', 'Invalid'],
+ ['U', 'Invalid', 'N'],
+ ['Invalid', 'N', 'N']])
+ def test_invalid_argument_raises_exception(self, uplo, trans, diag):
+ """Test if invalid values of uplo, trans and diag raise exceptions"""
+ # Argument checks occur independently of used datatype.
+ # This mean we must not parameterize all available datatypes.
+ tbtrs = get_lapack_funcs('tbtrs', dtype=np.float64)
+ rng = np.random.default_rng(1234)
+ ab = rng.random((4, 2))
+ b = rng.random((2, 4))
+ assert_raises(Exception, tbtrs, ab, b, uplo, trans, diag)
+
+ def test_zero_element_in_diagonal(self):
+ """Test if a matrix with a zero diagonal element is singular
+
+ If the i-th diagonal of A is zero, ?tbtrs should return `i` in `info`
+ indicating the provided matrix is singular.
+
+ Note that ?tbtrs requires the matrix A to be stored in banded form.
+ In this form the diagonal corresponds to the last row."""
+ ab = np.ones((3, 4), dtype=float)
+ b = np.ones(4, dtype=float)
+ tbtrs = get_lapack_funcs('tbtrs', dtype=float)
+
+ ab[-1, 3] = 0
+ _, info = tbtrs(ab=ab, b=b, uplo='U')
+ assert_equal(info, 4)
+
+ @pytest.mark.parametrize('ldab,n,ldb,nrhs', [
+ (5, 5, 0, 5),
+ (5, 5, 3, 5)
+ ])
+ def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs):
+ """Test ?tbtrs fails correctly if shapes are invalid."""
+ ab = np.ones((ldab, n), dtype=float)
+ b = np.ones((ldb, nrhs), dtype=float)
+ tbtrs = get_lapack_funcs('tbtrs', dtype=float)
+ assert_raises(Exception, tbtrs, ab, b)
+
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('norm', ['I', '1', 'O'])
+@pytest.mark.parametrize('uplo', ['U', 'L'])
+@pytest.mark.parametrize('diag', ['N', 'U'])
+@pytest.mark.parametrize('n', [3, 10])
+def test_trcon(dtype, norm, uplo, diag, n):
+ # Simple way to get deterministic (unlike `hash`) seed based on arguments
+ seed = list(f"{dtype}{norm}{uplo}{diag}{n}".encode())
+ rng = np.random.default_rng(seed)
+
+ A = rng.random(size=(n, n)) + rng.random(size=(n, n))*1j
+ # make the condition numbers more interesting
+ offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n))
+ A += offset
+ A = A.real if np.issubdtype(dtype, np.floating) else A
+ A = np.triu(A) if uplo == 'U' else np.tril(A)
+ if diag == 'U':
+ A /= np.diag(A)[:, np.newaxis]
+ A = A.astype(dtype)
+
+ trcon = get_lapack_funcs('trcon', (A,))
+ res, _ = trcon(A, norm=norm, uplo=uplo, diag=diag)
+
+ if norm == 'I':
+ norm_A = np.linalg.norm(A, ord=np.inf)
+ norm_inv_A = np.linalg.norm(np.linalg.inv(A), ord=np.inf)
+ ref = 1 / (norm_A * norm_inv_A)
+ else:
+ anorm = np.linalg.norm(A, ord=1)
+ gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
+ lu, ipvt, info = getrf(A)
+ ref, _ = gecon(lu, anorm, norm=norm)
+
+ # This is an estimate of reciprocal condition number; we just need order of
+ # magnitude. In testing, we observed that much smaller rtol is OK in almost
+ # all cases... but sometimes it isn't.
+ rtol = 1 # np.finfo(dtype).eps**0.75
+ assert_allclose(res, ref, rtol=rtol)
+
+
+def test_lartg():
+ for dtype in 'fdFD':
+ lartg = get_lapack_funcs('lartg', dtype=dtype)
+
+ f = np.array(3, dtype)
+ g = np.array(4, dtype)
+
+ if np.iscomplexobj(g):
+ g *= 1j
+
+ cs, sn, r = lartg(f, g)
+
+ assert_allclose(cs, 3.0/5.0)
+ assert_allclose(r, 5.0)
+
+ if np.iscomplexobj(g):
+ assert_allclose(sn, -4.0j/5.0)
+ assert_(isinstance(r, complex))
+ assert_(isinstance(cs, float))
+ else:
+ assert_allclose(sn, 4.0/5.0)
+
+
+def test_rot():
+ # srot, drot from blas and crot and zrot from lapack.
+
+ for dtype in 'fdFD':
+ c = 0.6
+ s = 0.8
+
+ u = np.full(4, 3, dtype)
+ v = np.full(4, 4, dtype)
+ atol = 10**-(np.finfo(dtype).precision-1)
+
+ if dtype in 'fd':
+ rot = get_blas_funcs('rot', dtype=dtype)
+ f = 4
+ else:
+ rot = get_lapack_funcs('rot', dtype=dtype)
+ s *= -1j
+ v *= 1j
+ f = 4j
+
+ assert_allclose(rot(u, v, c, s), [[5, 5, 5, 5],
+ [0, 0, 0, 0]], atol=atol)
+ assert_allclose(rot(u, v, c, s, n=2), [[5, 5, 3, 3],
+ [0, 0, f, f]], atol=atol)
+ assert_allclose(rot(u, v, c, s, offx=2, offy=2),
+ [[3, 3, 5, 5], [f, f, 0, 0]], atol=atol)
+ assert_allclose(rot(u, v, c, s, incx=2, offy=2, n=2),
+ [[5, 3, 5, 3], [f, f, 0, 0]], atol=atol)
+ assert_allclose(rot(u, v, c, s, offx=2, incy=2, n=2),
+ [[3, 3, 5, 5], [0, f, 0, f]], atol=atol)
+ assert_allclose(rot(u, v, c, s, offx=2, incx=2, offy=2, incy=2, n=1),
+ [[3, 3, 5, 3], [f, f, 0, f]], atol=atol)
+ assert_allclose(rot(u, v, c, s, incx=-2, incy=-2, n=2),
+ [[5, 3, 5, 3], [0, f, 0, f]], atol=atol)
+
+ a, b = rot(u, v, c, s, overwrite_x=1, overwrite_y=1)
+ assert_(a is u)
+ assert_(b is v)
+ assert_allclose(a, [5, 5, 5, 5], atol=atol)
+ assert_allclose(b, [0, 0, 0, 0], atol=atol)
+
+
+def test_larfg_larf():
+ rng = np.random.default_rng(1234)
+ a0 = rng.random((4, 4))
+ a0 = a0.T.dot(a0)
+
+ a0j = rng.random((4, 4)) + 1j*rng.random((4, 4))
+ a0j = a0j.T.conj().dot(a0j)
+
+ # our test here will be to do one step of reducing a hermetian matrix to
+ # tridiagonal form using householder transforms.
+
+ for dtype in 'fdFD':
+ larfg, larf = get_lapack_funcs(['larfg', 'larf'], dtype=dtype)
+
+ if dtype in 'FD':
+ a = a0j.copy()
+ else:
+ a = a0.copy()
+
+ # generate a householder transform to clear a[2:,0]
+ alpha, x, tau = larfg(a.shape[0]-1, a[1, 0], a[2:, 0])
+
+ # create expected output
+ expected = np.zeros_like(a[:, 0])
+ expected[0] = a[0, 0]
+ expected[1] = alpha
+
+ # assemble householder vector
+ v = np.zeros_like(a[1:, 0])
+ v[0] = 1.0
+ v[1:] = x
+
+ # apply transform from the left
+ a[1:, :] = larf(v, tau.conjugate(), a[1:, :], np.zeros(a.shape[1]))
+
+ # apply transform from the right
+ a[:, 1:] = larf(v, tau, a[:, 1:], np.zeros(a.shape[0]), side='R')
+
+ assert_allclose(a[:, 0], expected, atol=1e-5)
+ assert_allclose(a[0, :], expected, atol=1e-5)
+
+
+def test_sgesdd_lwork_bug_workaround():
+ # Test that SGESDD lwork is sufficiently large for LAPACK.
+ #
+ # This checks that _compute_lwork() correctly works around a bug in
+ # LAPACK versions older than 3.10.1.
+
+ sgesdd_lwork = get_lapack_funcs('gesdd_lwork', dtype=np.float32,
+ ilp64='preferred')
+ n = 9537
+ lwork = _compute_lwork(sgesdd_lwork, n, n,
+ compute_uv=True, full_matrices=True)
+ # If we called the Fortran function SGESDD directly with IWORK=-1, the
+ # LAPACK bug would result in lwork being 272929856, which was too small.
+ # (The result was returned in a single precision float, which does not
+ # have sufficient precision to represent the exact integer value that it
+ # computed internally.) The work-around implemented in _compute_lwork()
+ # will convert that to 272929888. If we are using LAPACK 3.10.1 or later
+ # (such as in OpenBLAS 0.3.21 or later), the work-around will return
+ # 272929920, because it does not know which version of LAPACK is being
+ # used, so it always applies the correction to whatever it is given. We
+ # will accept either 272929888 or 272929920.
+ # Note that the acceptable values are a LAPACK implementation detail.
+ # If a future version of LAPACK changes how SGESDD works, and therefore
+ # changes the required LWORK size, the acceptable values might have to
+ # be updated.
+ assert lwork == 272929888 or lwork == 272929920
+
+
+class TestSytrd:
+ @pytest.mark.parametrize('dtype', REAL_DTYPES)
+ def test_sytrd_with_zero_dim_array(self, dtype):
+ # Assert that a 0x0 matrix raises an error
+ A = np.zeros((0, 0), dtype=dtype)
+ sytrd = get_lapack_funcs('sytrd', (A,))
+ assert_raises(ValueError, sytrd, A)
+
+ @pytest.mark.parametrize('dtype', REAL_DTYPES)
+ @pytest.mark.parametrize('n', (1, 3))
+ def test_sytrd(self, dtype, n):
+ A = np.zeros((n, n), dtype=dtype)
+
+ sytrd, sytrd_lwork = \
+ get_lapack_funcs(('sytrd', 'sytrd_lwork'), (A,))
+
+ # some upper triangular array
+ A[np.triu_indices_from(A)] = \
+ np.arange(1, n*(n+1)//2+1, dtype=dtype)
+
+ # query lwork
+ lwork, info = sytrd_lwork(n)
+ assert_equal(info, 0)
+
+ # check lower=1 behavior (shouldn't do much since the matrix is
+ # upper triangular)
+ data, d, e, tau, info = sytrd(A, lower=1, lwork=lwork)
+ assert_equal(info, 0)
+
+ assert_allclose(data, A, atol=5*np.finfo(dtype).eps, rtol=1.0)
+ assert_allclose(d, np.diag(A))
+ assert_allclose(e, 0.0)
+ assert_allclose(tau, 0.0)
+
+ # and now for the proper test (lower=0 is the default)
+ data, d, e, tau, info = sytrd(A, lwork=lwork)
+ assert_equal(info, 0)
+
+ # assert Q^T*A*Q = tridiag(e, d, e)
+
+ # build tridiagonal matrix
+ T = np.zeros_like(A, dtype=dtype)
+ k = np.arange(A.shape[0])
+ T[k, k] = d
+ k2 = np.arange(A.shape[0]-1)
+ T[k2+1, k2] = e
+ T[k2, k2+1] = e
+
+ # build Q
+ Q = np.eye(n, n, dtype=dtype)
+ for i in range(n-1):
+ v = np.zeros(n, dtype=dtype)
+ v[:i] = data[:i, i+1]
+ v[i] = 1.0
+ H = np.eye(n, n, dtype=dtype) - tau[i] * np.outer(v, v)
+ Q = np.dot(H, Q)
+
+ # Make matrix fully symmetric
+ i_lower = np.tril_indices(n, -1)
+ A[i_lower] = A.T[i_lower]
+
+ QTAQ = np.dot(Q.T, np.dot(A, Q))
+
+ # disable rtol here since some values in QTAQ and T are very close
+ # to 0.
+ assert_allclose(QTAQ, T, atol=5*np.finfo(dtype).eps, rtol=1.0)
+
+
+class TestHetrd:
+ @pytest.mark.parametrize('complex_dtype', COMPLEX_DTYPES)
+ def test_hetrd_with_zero_dim_array(self, complex_dtype):
+ # Assert that a 0x0 matrix raises an error
+ A = np.zeros((0, 0), dtype=complex_dtype)
+ hetrd = get_lapack_funcs('hetrd', (A,))
+ assert_raises(ValueError, hetrd, A)
+
+ @pytest.mark.parametrize('real_dtype,complex_dtype',
+ list(zip(REAL_DTYPES, COMPLEX_DTYPES)))
+ @pytest.mark.parametrize('n', (1, 3))
+ def test_hetrd(self, n, real_dtype, complex_dtype):
+ A = np.zeros((n, n), dtype=complex_dtype)
+ hetrd, hetrd_lwork = \
+ get_lapack_funcs(('hetrd', 'hetrd_lwork'), (A,))
+
+ # some upper triangular array
+ A[np.triu_indices_from(A)] = (
+ np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
+ + 1j * np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
+ )
+ np.fill_diagonal(A, np.real(np.diag(A)))
+
+ # test query lwork
+ for x in [0, 1]:
+ _, info = hetrd_lwork(n, lower=x)
+ assert_equal(info, 0)
+ # lwork returns complex which segfaults hetrd call (gh-10388)
+ # use the safe and recommended option
+ lwork = _compute_lwork(hetrd_lwork, n)
+
+ # check lower=1 behavior (shouldn't do much since the matrix is
+ # upper triangular)
+ data, d, e, tau, info = hetrd(A, lower=1, lwork=lwork)
+ assert_equal(info, 0)
+
+ assert_allclose(data, A, atol=5*np.finfo(real_dtype).eps, rtol=1.0)
+
+ assert_allclose(d, np.real(np.diag(A)))
+ assert_allclose(e, 0.0)
+ assert_allclose(tau, 0.0)
+
+ # and now for the proper test (lower=0 is the default)
+ data, d, e, tau, info = hetrd(A, lwork=lwork)
+ assert_equal(info, 0)
+
+ # assert Q^T*A*Q = tridiag(e, d, e)
+
+ # build tridiagonal matrix
+ T = np.zeros_like(A, dtype=real_dtype)
+ k = np.arange(A.shape[0], dtype=int)
+ T[k, k] = d
+ k2 = np.arange(A.shape[0]-1, dtype=int)
+ T[k2+1, k2] = e
+ T[k2, k2+1] = e
+
+ # build Q
+ Q = np.eye(n, n, dtype=complex_dtype)
+ for i in range(n-1):
+ v = np.zeros(n, dtype=complex_dtype)
+ v[:i] = data[:i, i+1]
+ v[i] = 1.0
+ H = np.eye(n, n, dtype=complex_dtype) \
+ - tau[i] * np.outer(v, np.conj(v))
+ Q = np.dot(H, Q)
+
+ # Make matrix fully Hermitian
+ i_lower = np.tril_indices(n, -1)
+ A[i_lower] = np.conj(A.T[i_lower])
+
+ QHAQ = np.dot(np.conj(Q.T), np.dot(A, Q))
+
+ # disable rtol here since some values in QTAQ and T are very close
+ # to 0.
+ assert_allclose(
+ QHAQ, T, atol=10*np.finfo(real_dtype).eps, rtol=1.0
+ )
+
+
+def test_gglse():
+ # Example data taken from NAG manual
+ for ind, dtype in enumerate(DTYPES):
+ # DTYPES = gglse
+ func, func_lwork = get_lapack_funcs(('gglse', 'gglse_lwork'),
+ dtype=dtype)
+ lwork = _compute_lwork(func_lwork, m=6, n=4, p=2)
+ # For gglse
+ if ind < 2:
+ a = np.array([[-0.57, -1.28, -0.39, 0.25],
+ [-1.93, 1.08, -0.31, -2.14],
+ [2.30, 0.24, 0.40, -0.35],
+ [-1.93, 0.64, -0.66, 0.08],
+ [0.15, 0.30, 0.15, -2.13],
+ [-0.02, 1.03, -1.43, 0.50]], dtype=dtype)
+ c = np.array([-1.50, -2.14, 1.23, -0.54, -1.68, 0.82], dtype=dtype)
+ d = np.array([0., 0.], dtype=dtype)
+ # For gglse
+ else:
+ a = np.array([[0.96-0.81j, -0.03+0.96j, -0.91+2.06j, -0.05+0.41j],
+ [-0.98+1.98j, -1.20+0.19j, -0.66+0.42j, -0.81+0.56j],
+ [0.62-0.46j, 1.01+0.02j, 0.63-0.17j, -1.11+0.60j],
+ [0.37+0.38j, 0.19-0.54j, -0.98-0.36j, 0.22-0.20j],
+ [0.83+0.51j, 0.20+0.01j, -0.17-0.46j, 1.47+1.59j],
+ [1.08-0.28j, 0.20-0.12j, -0.07+1.23j, 0.26+0.26j]])
+ c = np.array([[-2.54+0.09j],
+ [1.65-2.26j],
+ [-2.11-3.96j],
+ [1.82+3.30j],
+ [-6.41+3.77j],
+ [2.07+0.66j]])
+ d = np.zeros(2, dtype=dtype)
+
+ b = np.array([[1., 0., -1., 0.], [0., 1., 0., -1.]], dtype=dtype)
+
+ _, _, _, result, _ = func(a, b, c, d, lwork=lwork)
+ if ind < 2:
+ expected = np.array([0.48904455,
+ 0.99754786,
+ 0.48904455,
+ 0.99754786])
+ else:
+ expected = np.array([1.08742917-1.96205783j,
+ -0.74093902+3.72973919j,
+ 1.08742917-1.96205759j,
+ -0.74093896+3.72973895j])
+ assert_array_almost_equal(result, expected, decimal=4)
+
+
+def test_sycon_hecon():
+ rng = np.random.default_rng(1234)
+ for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+ # DTYPES + COMPLEX DTYPES = sycon + hecon
+ n = 10
+ # For sycon
+ if ind < 4:
+ func_lwork = get_lapack_funcs('sytrf_lwork', dtype=dtype)
+ funcon, functrf = get_lapack_funcs(('sycon', 'sytrf'), dtype=dtype)
+ A = (rng.random((n, n))).astype(dtype)
+ # For hecon
+ else:
+ func_lwork = get_lapack_funcs('hetrf_lwork', dtype=dtype)
+ funcon, functrf = get_lapack_funcs(('hecon', 'hetrf'), dtype=dtype)
+ A = (rng.random((n, n)) + rng.random((n, n))*1j).astype(dtype)
+
+ # Since sycon only refers to upper/lower part, conj() is safe here.
+ A = (A + A.conj().T)/2 + 2*np.eye(n, dtype=dtype)
+
+ anorm = norm(A, 1)
+ lwork = _compute_lwork(func_lwork, n)
+ ldu, ipiv, _ = functrf(A, lwork=lwork, lower=1)
+ rcond, _ = funcon(a=ldu, ipiv=ipiv, anorm=anorm, lower=1)
+ # The error is at most 1-fold
+ assert_(abs(1/rcond - np.linalg.cond(A, p=1))*rcond < 1)
+
+
+def test_sygst():
+ rng = np.random.default_rng(1234)
+ for ind, dtype in enumerate(REAL_DTYPES):
+ # DTYPES = sygst
+ n = 10
+
+ potrf, sygst, syevd, sygvd = get_lapack_funcs(('potrf', 'sygst',
+ 'syevd', 'sygvd'),
+ dtype=dtype)
+
+ A = rng.random((n, n)).astype(dtype)
+ A = (A + A.T)/2
+ # B must be positive definite
+ B = rng.random((n, n)).astype(dtype)
+ B = (B + B.T)/2 + 2 * np.eye(n, dtype=dtype)
+
+ # Perform eig (sygvd)
+ eig_gvd, _, info = sygvd(A, B)
+ assert_(info == 0)
+
+ # Convert to std problem potrf
+ b, info = potrf(B)
+ assert_(info == 0)
+ a, info = sygst(A, b)
+ assert_(info == 0)
+
+ eig, _, info = syevd(a)
+ assert_(info == 0)
+ assert_allclose(eig, eig_gvd, rtol=1.2e-4)
+
+
+def test_hegst():
+ rng = np.random.default_rng(1234)
+ for ind, dtype in enumerate(COMPLEX_DTYPES):
+ # DTYPES = hegst
+ n = 10
+
+ potrf, hegst, heevd, hegvd = get_lapack_funcs(('potrf', 'hegst',
+ 'heevd', 'hegvd'),
+ dtype=dtype)
+
+ A = rng.random((n, n)).astype(dtype) + 1j * rng.random((n, n)).astype(dtype)
+ A = (A + A.conj().T)/2
+ # B must be positive definite
+ B = rng.random((n, n)).astype(dtype) + 1j * rng.random((n, n)).astype(dtype)
+ B = (B + B.conj().T)/2 + 2 * np.eye(n, dtype=dtype)
+
+ # Perform eig (hegvd)
+ eig_gvd, _, info = hegvd(A, B)
+ assert_(info == 0)
+
+ # Convert to std problem potrf
+ b, info = potrf(B)
+ assert_(info == 0)
+ a, info = hegst(A, b)
+ assert_(info == 0)
+
+ eig, _, info = heevd(a)
+ assert_(info == 0)
+ assert_allclose(eig, eig_gvd, rtol=1e-4)
+
+
+def test_tzrzf():
+ """
+ This test performs an RZ decomposition in which an m x n upper trapezoidal
+ array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular
+ and Z is unitary.
+ """
+ rng = np.random.RandomState(1234)
+ m, n = 10, 15
+ for ind, dtype in enumerate(DTYPES):
+ tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
+ dtype=dtype)
+ lwork = _compute_lwork(tzrzf_lw, m, n)
+
+ if ind < 2:
+ A = triu(rng.rand(m, n).astype(dtype))
+ else:
+ A = triu((rng.rand(m, n) + rng.rand(m, n)*1j).astype(dtype))
+
+ # assert wrong shape arg, f2py returns generic error
+ assert_raises(Exception, tzrzf, A.T)
+ rz, tau, info = tzrzf(A, lwork=lwork)
+ # Check success
+ assert_(info == 0)
+
+ # Get Z manually for comparison
+ R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype)))
+ V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:]))
+ Id = np.eye(n, dtype=dtype)
+ ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)]
+ Z = reduce(np.dot, ref)
+ assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype),
+ atol=10*np.spacing(dtype(1.0).real), rtol=0.)
+
+
+def test_tfsm():
+ """
+ Test for solving a linear system with the coefficient matrix is a
+ triangular array stored in Full Packed (RFP) format.
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+ if ind > 1:
+ A = triu(rng.rand(n, n) + rng.rand(n, n)*1j + eye(n)).astype(dtype)
+ trans = 'C'
+ else:
+ A = triu(rng.rand(n, n) + eye(n)).astype(dtype)
+ trans = 'T'
+
+ trttf, tfttr, tfsm = get_lapack_funcs(('trttf', 'tfttr', 'tfsm'),
+ dtype=dtype)
+
+ Afp, _ = trttf(A)
+ B = rng.rand(n, 2).astype(dtype)
+ soln = tfsm(-1, Afp, B)
+ assert_array_almost_equal(soln, solve(-A, B),
+ decimal=4 if ind % 2 == 0 else 6)
+
+ soln = tfsm(-1, Afp, B, trans=trans)
+ assert_array_almost_equal(soln, solve(-A.conj().T, B),
+ decimal=4 if ind % 2 == 0 else 6)
+
+ # Make A, unit diagonal
+ A[np.arange(n), np.arange(n)] = dtype(1.)
+ soln = tfsm(-1, Afp, B, trans=trans, diag='U')
+ assert_array_almost_equal(soln, solve(-A.conj().T, B),
+ decimal=4 if ind % 2 == 0 else 6)
+
+ # Change side
+ B2 = rng.rand(3, n).astype(dtype)
+ soln = tfsm(-1, Afp, B2, trans=trans, diag='U', side='R')
+ assert_array_almost_equal(soln, solve(-A, B2.T).conj().T,
+ decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_ormrz_unmrz():
+ """
+ This test performs a matrix multiplication with an arbitrary m x n matrix C
+ and a unitary matrix Q without explicitly forming the array. The array data
+ is encoded in the rectangular part of A which is obtained from ?TZRZF. Q
+ size is inferred by m, n, side keywords.
+ """
+ rng = np.random.RandomState(1234)
+ qm, qn, cn = 10, 15, 15
+ for ind, dtype in enumerate(DTYPES):
+ tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
+ dtype=dtype)
+ lwork_rz = _compute_lwork(tzrzf_lw, qm, qn)
+
+ if ind < 2:
+ A = triu(rng.random((qm, qn)).astype(dtype))
+ C = rng.random((cn, cn)).astype(dtype)
+ orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'),
+ dtype=dtype)
+ else:
+ A = triu((rng.random((qm, qn)) + rng.random((qm, qn))*1j).astype(dtype))
+ C = (rng.random((cn, cn)) + rng.random((cn, cn))*1j).astype(dtype)
+ orun_mrz, orun_mrz_lw = get_lapack_funcs(('unmrz', 'unmrz_lwork'),
+ dtype=dtype)
+
+ lwork_mrz = _compute_lwork(orun_mrz_lw, cn, cn)
+ rz, tau, info = tzrzf(A, lwork=lwork_rz)
+
+ # Get Q manually for comparison
+ V = np.hstack((np.eye(qm, dtype=dtype), rz[:, qm:]))
+ Id = np.eye(qn, dtype=dtype)
+ ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(qm)]
+ Q = reduce(np.dot, ref)
+
+ # Now that we have Q, we can test whether lapack results agree with
+ # each case of CQ, CQ^H, QC, and QC^H
+ trans = 'T' if ind < 2 else 'C'
+ tol = 10*np.spacing(dtype(1.0).real)
+
+ cq, info = orun_mrz(rz, tau, C, lwork=lwork_mrz)
+ assert_(info == 0)
+ assert_allclose(cq - Q.dot(C), zeros_like(C), atol=tol, rtol=0.)
+
+ cq, info = orun_mrz(rz, tau, C, trans=trans, lwork=lwork_mrz)
+ assert_(info == 0)
+ assert_allclose(cq - Q.conj().T.dot(C), zeros_like(C), atol=tol,
+ rtol=0.)
+
+ cq, info = orun_mrz(rz, tau, C, side='R', lwork=lwork_mrz)
+ assert_(info == 0)
+ assert_allclose(cq - C.dot(Q), zeros_like(C), atol=tol, rtol=0.)
+
+ cq, info = orun_mrz(rz, tau, C, side='R', trans=trans, lwork=lwork_mrz)
+ assert_(info == 0)
+ assert_allclose(cq - C.dot(Q.conj().T), zeros_like(C), atol=tol,
+ rtol=0.)
+
+
+def test_tfttr_trttf():
+ """
+ Test conversion routines between the Rectangular Full Packed (RFP) format
+ and Standard Triangular Array (TR)
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+ if ind > 1:
+ A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ transr = 'C'
+ else:
+ A_full = (rng.rand(n, n)).astype(dtype)
+ transr = 'T'
+
+ trttf, tfttr = get_lapack_funcs(('trttf', 'tfttr'), dtype=dtype)
+ A_tf_U, info = trttf(A_full)
+ assert_(info == 0)
+ A_tf_L, info = trttf(A_full, uplo='L')
+ assert_(info == 0)
+ A_tf_U_T, info = trttf(A_full, transr=transr, uplo='U')
+ assert_(info == 0)
+ A_tf_L_T, info = trttf(A_full, transr=transr, uplo='L')
+ assert_(info == 0)
+
+ # Create the RFP array manually (n is even!)
+ A_tf_U_m = zeros((n+1, n//2), dtype=dtype)
+ A_tf_U_m[:-1, :] = triu(A_full)[:, n//2:]
+ A_tf_U_m[n//2+1:, :] += triu(A_full)[:n//2, :n//2].conj().T
+
+ A_tf_L_m = zeros((n+1, n//2), dtype=dtype)
+ A_tf_L_m[1:, :] = tril(A_full)[:, :n//2]
+ A_tf_L_m[:n//2, :] += tril(A_full)[n//2:, n//2:].conj().T
+
+ assert_array_almost_equal(A_tf_U, A_tf_U_m.reshape(-1, order='F'))
+ assert_array_almost_equal(A_tf_U_T,
+ A_tf_U_m.conj().T.reshape(-1, order='F'))
+
+ assert_array_almost_equal(A_tf_L, A_tf_L_m.reshape(-1, order='F'))
+ assert_array_almost_equal(A_tf_L_T,
+ A_tf_L_m.conj().T.reshape(-1, order='F'))
+
+ # Get the original array from RFP
+ A_tr_U, info = tfttr(n, A_tf_U)
+ assert_(info == 0)
+ A_tr_L, info = tfttr(n, A_tf_L, uplo='L')
+ assert_(info == 0)
+ A_tr_U_T, info = tfttr(n, A_tf_U_T, transr=transr, uplo='U')
+ assert_(info == 0)
+ A_tr_L_T, info = tfttr(n, A_tf_L_T, transr=transr, uplo='L')
+ assert_(info == 0)
+
+ assert_array_almost_equal(A_tr_U, triu(A_full))
+ assert_array_almost_equal(A_tr_U_T, triu(A_full))
+ assert_array_almost_equal(A_tr_L, tril(A_full))
+ assert_array_almost_equal(A_tr_L_T, tril(A_full))
+
+
+def test_tpttr_trttp():
+ """
+ Test conversion routines between the Rectangular Full Packed (RFP) format
+ and Standard Triangular Array (TR)
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+ if ind > 1:
+ A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ else:
+ A_full = (rng.rand(n, n)).astype(dtype)
+
+ trttp, tpttr = get_lapack_funcs(('trttp', 'tpttr'), dtype=dtype)
+ A_tp_U, info = trttp(A_full)
+ assert_(info == 0)
+ A_tp_L, info = trttp(A_full, uplo='L')
+ assert_(info == 0)
+
+ # Create the TP array manually
+ inds = tril_indices(n)
+ A_tp_U_m = zeros(n*(n+1)//2, dtype=dtype)
+ A_tp_U_m[:] = (triu(A_full).T)[inds]
+
+ inds = triu_indices(n)
+ A_tp_L_m = zeros(n*(n+1)//2, dtype=dtype)
+ A_tp_L_m[:] = (tril(A_full).T)[inds]
+
+ assert_array_almost_equal(A_tp_U, A_tp_U_m)
+ assert_array_almost_equal(A_tp_L, A_tp_L_m)
+
+ # Get the original array from TP
+ A_tr_U, info = tpttr(n, A_tp_U)
+ assert_(info == 0)
+ A_tr_L, info = tpttr(n, A_tp_L, uplo='L')
+ assert_(info == 0)
+
+ assert_array_almost_equal(A_tr_U, triu(A_full))
+ assert_array_almost_equal(A_tr_L, tril(A_full))
+
+
+def test_pftrf():
+ """
+ Test Cholesky factorization of a positive definite Rectangular Full
+ Packed (RFP) format array
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+ if ind > 1:
+ A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ A = A + A.conj().T + n*eye(n)
+ else:
+ A = (rng.rand(n, n)).astype(dtype)
+ A = A + A.T + n*eye(n)
+
+ pftrf, trttf, tfttr = get_lapack_funcs(('pftrf', 'trttf', 'tfttr'),
+ dtype=dtype)
+
+ # Get the original array from TP
+ Afp, info = trttf(A)
+ Achol_rfp, info = pftrf(n, Afp)
+ assert_(info == 0)
+ A_chol_r, _ = tfttr(n, Achol_rfp)
+ Achol = cholesky(A)
+ assert_array_almost_equal(A_chol_r, Achol)
+
+
+def test_pftri():
+ """
+ Test Cholesky factorization of a positive definite Rectangular Full
+ Packed (RFP) format array to find its inverse
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+ if ind > 1:
+ A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ A = A + A.conj().T + n*eye(n)
+ else:
+ A = (rng.rand(n, n)).astype(dtype)
+ A = A + A.T + n*eye(n)
+
+ pftri, pftrf, trttf, tfttr = get_lapack_funcs(('pftri',
+ 'pftrf',
+ 'trttf',
+ 'tfttr'),
+ dtype=dtype)
+
+ # Get the original array from TP
+ Afp, info = trttf(A)
+ A_chol_rfp, info = pftrf(n, Afp)
+ A_inv_rfp, info = pftri(n, A_chol_rfp)
+ assert_(info == 0)
+ A_inv_r, _ = tfttr(n, A_inv_rfp)
+ Ainv = inv(A)
+ assert_array_almost_equal(A_inv_r, triu(Ainv),
+ decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_pftrs():
+ """
+ Test Cholesky factorization of a positive definite Rectangular Full
+ Packed (RFP) format array and solve a linear system
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+ if ind > 1:
+ A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ A = A + A.conj().T + n*eye(n)
+ else:
+ A = (rng.rand(n, n)).astype(dtype)
+ A = A + A.T + n*eye(n)
+
+ B = ones((n, 3), dtype=dtype)
+ Bf1 = ones((n+2, 3), dtype=dtype)
+ Bf2 = ones((n-2, 3), dtype=dtype)
+ pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs',
+ 'pftrf',
+ 'trttf',
+ 'tfttr'),
+ dtype=dtype)
+
+ # Get the original array from TP
+ Afp, info = trttf(A)
+ A_chol_rfp, info = pftrf(n, Afp)
+ # larger B arrays shouldn't segfault
+ soln, info = pftrs(n, A_chol_rfp, Bf1)
+ assert_(info == 0)
+ assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2)
+ soln, info = pftrs(n, A_chol_rfp, B)
+ assert_(info == 0)
+ assert_array_almost_equal(solve(A, B), soln,
+ decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_sfrk_hfrk():
+ """
+ Test for performing a symmetric rank-k operation for matrix in RFP format.
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+ if ind > 1:
+ A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ A = A + A.conj().T + n*eye(n)
+ else:
+ A = (rng.rand(n, n)).astype(dtype)
+ A = A + A.T + n*eye(n)
+
+ prefix = 's'if ind < 2 else 'h'
+ trttf, tfttr, shfrk = get_lapack_funcs(('trttf', 'tfttr', f'{prefix}frk'),
+ dtype=dtype)
+
+ Afp, _ = trttf(A)
+ C = rng.rand(n, 2).astype(dtype)
+ Afp_out = shfrk(n, 2, -1, C, 2, Afp)
+ A_out, _ = tfttr(n, Afp_out)
+ assert_array_almost_equal(A_out, triu(-C.dot(C.conj().T) + 2*A),
+ decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_syconv():
+ """
+ Test for going back and forth between the returned format of he/sytrf to
+ L and D factors/permutations.
+ """
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 10
+
+ if ind > 1:
+ A = (rng.randint(-30, 30, (n, n)) +
+ rng.randint(-30, 30, (n, n))*1j).astype(dtype)
+
+ A = A + A.conj().T
+ else:
+ A = rng.randint(-30, 30, (n, n)).astype(dtype)
+ A = A + A.T + n*eye(n)
+
+ tol = 100*np.spacing(dtype(1.0).real)
+ syconv, trf, trf_lwork = get_lapack_funcs(('syconv', 'sytrf',
+ 'sytrf_lwork'), dtype=dtype)
+ lw = _compute_lwork(trf_lwork, n, lower=1)
+ L, D, perm = ldl(A, lower=1, hermitian=False)
+ lw = _compute_lwork(trf_lwork, n, lower=1)
+ ldu, ipiv, info = trf(A, lower=1, lwork=lw)
+ a, e, info = syconv(ldu, ipiv, lower=1)
+ assert_allclose(tril(a, -1,), tril(L[perm, :], -1), atol=tol, rtol=0.)
+
+ # Test also upper
+ U, D, perm = ldl(A, lower=0, hermitian=False)
+ ldu, ipiv, info = trf(A, lower=0)
+ a, e, info = syconv(ldu, ipiv, lower=0)
+ assert_allclose(triu(a, 1), triu(U[perm, :], 1), atol=tol, rtol=0.)
+
+
+class TestBlockedQR:
+ """
+ Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt
+ and tpmqr.
+ """
+
+ def test_geqrt_gemqrt(self):
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+
+ if ind > 1:
+ A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ else:
+ A = (rng.rand(n, n)).astype(dtype)
+
+ tol = 100*np.spacing(dtype(1.0).real)
+ geqrt, gemqrt = get_lapack_funcs(('geqrt', 'gemqrt'), dtype=dtype)
+
+ a, t, info = geqrt(n, A)
+ assert info == 0
+
+ # Extract elementary reflectors from lower triangle, adding the
+ # main diagonal of ones.
+ v = np.tril(a, -1) + np.eye(n, dtype=dtype)
+ # Generate the block Householder transform I - VTV^H
+ Q = np.eye(n, dtype=dtype) - v @ t @ v.T.conj()
+ R = np.triu(a)
+
+ # Test columns of Q are orthogonal
+ assert_allclose(Q.T.conj() @ Q, np.eye(n, dtype=dtype), atol=tol,
+ rtol=0.)
+ assert_allclose(Q @ R, A, atol=tol, rtol=0.)
+
+ if ind > 1:
+ C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ transpose = 'C'
+ else:
+ C = (rng.rand(n, n)).astype(dtype)
+ transpose = 'T'
+
+ for side in ('L', 'R'):
+ for trans in ('N', transpose):
+ c, info = gemqrt(a, t, C, side=side, trans=trans)
+ assert info == 0
+
+ if trans == transpose:
+ q = Q.T.conj()
+ else:
+ q = Q
+
+ if side == 'L':
+ qC = q @ C
+ else:
+ qC = C @ q
+
+ assert_allclose(c, qC, atol=tol, rtol=0.)
+
+ # Test default arguments
+ if (side, trans) == ('L', 'N'):
+ c_default, info = gemqrt(a, t, C)
+ assert info == 0
+ assert_equal(c_default, c)
+
+ # Test invalid side/trans
+ assert_raises(Exception, gemqrt, a, t, C, side='A')
+ assert_raises(Exception, gemqrt, a, t, C, trans='A')
+
+ def test_tpqrt_tpmqrt(self):
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ n = 20
+
+ if ind > 1:
+ A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ B = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ else:
+ A = (rng.rand(n, n)).astype(dtype)
+ B = (rng.rand(n, n)).astype(dtype)
+
+ tol = 100*np.spacing(dtype(1.0).real)
+ tpqrt, tpmqrt = get_lapack_funcs(('tpqrt', 'tpmqrt'), dtype=dtype)
+
+ # Test for the range of pentagonal B, from square to upper
+ # triangular
+ for l in (0, n // 2, n):
+ a, b, t, info = tpqrt(l, n, A, B)
+ assert info == 0
+
+ # Check that lower triangular part of A has not been modified
+ assert_equal(np.tril(a, -1), np.tril(A, -1))
+ # Check that elements not part of the pentagonal portion of B
+ # have not been modified.
+ assert_equal(np.tril(b, l - n - 1), np.tril(B, l - n - 1))
+
+ # Extract pentagonal portion of B
+ B_pent, b_pent = np.triu(B, l - n), np.triu(b, l - n)
+
+ # Generate elementary reflectors
+ v = np.concatenate((np.eye(n, dtype=dtype), b_pent))
+ # Generate the block Householder transform I - VTV^H
+ Q = np.eye(2 * n, dtype=dtype) - v @ t @ v.T.conj()
+ R = np.concatenate((np.triu(a), np.zeros_like(a)))
+
+ # Test columns of Q are orthogonal
+ assert_allclose(Q.T.conj() @ Q, np.eye(2 * n, dtype=dtype),
+ atol=tol, rtol=0.)
+ assert_allclose(Q @ R, np.concatenate((np.triu(A), B_pent)),
+ atol=tol, rtol=0.)
+
+ if ind > 1:
+ C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ D = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+ transpose = 'C'
+ else:
+ C = (rng.rand(n, n)).astype(dtype)
+ D = (rng.rand(n, n)).astype(dtype)
+ transpose = 'T'
+
+ for side in ('L', 'R'):
+ for trans in ('N', transpose):
+ c, d, info = tpmqrt(l, b, t, C, D, side=side,
+ trans=trans)
+ assert info == 0
+
+ if trans == transpose:
+ q = Q.T.conj()
+ else:
+ q = Q
+
+ if side == 'L':
+ cd = np.concatenate((c, d), axis=0)
+ CD = np.concatenate((C, D), axis=0)
+ qCD = q @ CD
+ else:
+ cd = np.concatenate((c, d), axis=1)
+ CD = np.concatenate((C, D), axis=1)
+ qCD = CD @ q
+
+ assert_allclose(cd, qCD, atol=tol, rtol=0.)
+
+ if (side, trans) == ('L', 'N'):
+ c_default, d_default, info = tpmqrt(l, b, t, C, D)
+ assert info == 0
+ assert_equal(c_default, c)
+ assert_equal(d_default, d)
+
+ # Test invalid side/trans
+ assert_raises(Exception, tpmqrt, l, b, t, C, D, side='A')
+ assert_raises(Exception, tpmqrt, l, b, t, C, D, trans='A')
+
+
+def test_pstrf():
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ # DTYPES = pstrf
+ n = 10
+ r = 2
+ pstrf = get_lapack_funcs('pstrf', dtype=dtype)
+
+ # Create positive semidefinite A
+ if ind > 1:
+ A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
+ A = A @ A.conj().T
+ else:
+ A = rng.rand(n, n-r).astype(dtype)
+ A = A @ A.T
+
+ c, piv, r_c, info = pstrf(A)
+ U = triu(c)
+ U[r_c - n:, r_c - n:] = 0.
+
+ assert_equal(info, 1)
+ # python-dbg 3.5.2 runs cause trouble with the following assertion.
+ # assert_equal(r_c, n - r)
+ single_atol = 1000 * np.finfo(np.float32).eps
+ double_atol = 1000 * np.finfo(np.float64).eps
+ atol = single_atol if ind in [0, 2] else double_atol
+ assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
+
+ c, piv, r_c, info = pstrf(A, lower=1)
+ L = tril(c)
+ L[r_c - n:, r_c - n:] = 0.
+
+ assert_equal(info, 1)
+ # assert_equal(r_c, n - r)
+ single_atol = 1000 * np.finfo(np.float32).eps
+ double_atol = 1000 * np.finfo(np.float64).eps
+ atol = single_atol if ind in [0, 2] else double_atol
+ assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
+
+
+def test_pstf2():
+ rng = np.random.RandomState(1234)
+ for ind, dtype in enumerate(DTYPES):
+ # DTYPES = pstf2
+ n = 10
+ r = 2
+ pstf2 = get_lapack_funcs('pstf2', dtype=dtype)
+
+ # Create positive semidefinite A
+ if ind > 1:
+ A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
+ A = A @ A.conj().T
+ else:
+ A = rng.rand(n, n-r).astype(dtype)
+ A = A @ A.T
+
+ c, piv, r_c, info = pstf2(A)
+ U = triu(c)
+ U[r_c - n:, r_c - n:] = 0.
+
+ assert_equal(info, 1)
+ # python-dbg 3.5.2 runs cause trouble with the commented assertions.
+ # assert_equal(r_c, n - r)
+ single_atol = 1000 * np.finfo(np.float32).eps
+ double_atol = 1000 * np.finfo(np.float64).eps
+ atol = single_atol if ind in [0, 2] else double_atol
+ assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
+
+ c, piv, r_c, info = pstf2(A, lower=1)
+ L = tril(c)
+ L[r_c - n:, r_c - n:] = 0.
+
+ assert_equal(info, 1)
+ # assert_equal(r_c, n - r)
+ single_atol = 1000 * np.finfo(np.float32).eps
+ double_atol = 1000 * np.finfo(np.float64).eps
+ atol = single_atol if ind in [0, 2] else double_atol
+ assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
+
+
+def test_geequ():
+ desired_real = np.array([[0.6250, 1.0000, 0.0393, -0.4269],
+ [1.0000, -0.5619, -1.0000, -1.0000],
+ [0.5874, -1.0000, -0.0596, -0.5341],
+ [-1.0000, -0.5946, -0.0294, 0.9957]])
+
+ desired_cplx = np.array([[-0.2816+0.5359*1j,
+ 0.0812+0.9188*1j,
+ -0.7439-0.2561*1j],
+ [-0.3562-0.2954*1j,
+ 0.9566-0.0434*1j,
+ -0.0174+0.1555*1j],
+ [0.8607+0.1393*1j,
+ -0.2759+0.7241*1j,
+ -0.1642-0.1365*1j]])
+
+ for ind, dtype in enumerate(DTYPES):
+ if ind < 2:
+ # Use examples from the NAG documentation
+ A = np.array([[1.80e+10, 2.88e+10, 2.05e+00, -8.90e+09],
+ [5.25e+00, -2.95e+00, -9.50e-09, -3.80e+00],
+ [1.58e+00, -2.69e+00, -2.90e-10, -1.04e+00],
+ [-1.11e+00, -6.60e-01, -5.90e-11, 8.00e-01]])
+ A = A.astype(dtype)
+ else:
+ A = np.array([[-1.34e+00, 0.28e+10, -6.39e+00],
+ [-1.70e+00, 3.31e+10, -0.15e+00],
+ [2.41e-10, -0.56e+00, -0.83e-10]], dtype=dtype)
+ A += np.array([[2.55e+00, 3.17e+10, -2.20e+00],
+ [-1.41e+00, -0.15e+10, 1.34e+00],
+ [0.39e-10, 1.47e+00, -0.69e-10]])*1j
+
+ A = A.astype(dtype)
+
+ geequ = get_lapack_funcs('geequ', dtype=dtype)
+ r, c, rowcnd, colcnd, amax, info = geequ(A)
+
+ if ind < 2:
+ assert_allclose(desired_real.astype(dtype), r[:, None]*A*c,
+ rtol=0, atol=1e-4)
+ else:
+ assert_allclose(desired_cplx.astype(dtype), r[:, None]*A*c,
+ rtol=0, atol=1e-4)
+
+
+def test_syequb():
+ desired_log2s = np.array([0, 0, 0, 0, 0, 0, -1, -1, -2, -3])
+
+ for ind, dtype in enumerate(DTYPES):
+ A = np.eye(10, dtype=dtype)
+ alpha = dtype(1. if ind < 2 else 1.j)
+ d = np.array([alpha * 2.**x for x in range(-5, 5)], dtype=dtype)
+ A += np.rot90(np.diag(d))
+
+ syequb = get_lapack_funcs('syequb', dtype=dtype)
+ s, scond, amax, info = syequb(A)
+
+ assert_equal(np.log2(s).astype(int), desired_log2s)
+
+
+@pytest.mark.skipif(True,
+ reason="Failing on some OpenBLAS version, see gh-12276")
+def test_heequb():
+ # zheequb has a bug for versions =< LAPACK 3.9.0
+ # See Reference-LAPACK gh-61 and gh-408
+ # Hence the zheequb test is customized accordingly to avoid
+ # work scaling.
+ A = np.diag([2]*5 + [1002]*5) + np.diag(np.ones(9), k=1)*1j
+ s, scond, amax, info = lapack.zheequb(A)
+ assert_equal(info, 0)
+ assert_allclose(np.log2(s), [0., -1.]*2 + [0.] + [-4]*5)
+
+ A = np.diag(2**np.abs(np.arange(-5, 6)) + 0j)
+ A[5, 5] = 1024
+ A[5, 0] = 16j
+ s, scond, amax, info = lapack.cheequb(A.astype(np.complex64), lower=1)
+ assert_equal(info, 0)
+ assert_allclose(np.log2(s), [-2, -1, -1, 0, 0, -5, 0, -1, -1, -2, -2])
+
+
+def test_getc2_gesc2():
+ rng = np.random.RandomState(42)
+ n = 10
+ desired_real = rng.rand(n)
+ desired_cplx = rng.rand(n) + rng.rand(n)*1j
+
+ for ind, dtype in enumerate(DTYPES):
+ if ind < 2:
+ A = rng.rand(n, n)
+ A = A.astype(dtype)
+ b = A @ desired_real
+ b = b.astype(dtype)
+ else:
+ A = rng.rand(n, n) + rng.rand(n, n)*1j
+ A = A.astype(dtype)
+ b = A @ desired_cplx
+ b = b.astype(dtype)
+
+ getc2 = get_lapack_funcs('getc2', dtype=dtype)
+ gesc2 = get_lapack_funcs('gesc2', dtype=dtype)
+ lu, ipiv, jpiv, info = getc2(A, overwrite_a=0)
+ x, scale = gesc2(lu, b, ipiv, jpiv, overwrite_rhs=0)
+
+ if ind < 2:
+ assert_array_almost_equal(desired_real.astype(dtype),
+ x/scale, decimal=4)
+ else:
+ assert_array_almost_equal(desired_cplx.astype(dtype),
+ x/scale, decimal=4)
+
+
+@pytest.mark.parametrize('size', [(6, 5), (5, 5)])
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+@pytest.mark.parametrize('joba', list(range(6))) # 'C', 'E', 'F', 'G', 'A', 'R'
+@pytest.mark.parametrize('jobu', list(range(4))) # 'U', 'F', 'W', 'N'
+@pytest.mark.parametrize('jobv', list(range(4))) # 'V', 'J', 'W', 'N'
+@pytest.mark.parametrize('jobr', [0, 1])
+@pytest.mark.parametrize('jobp', [0, 1])
+def test_gejsv_general(size, dtype, joba, jobu, jobv, jobr, jobp, jobt=0):
+ """Test the lapack routine ?gejsv.
+
+ This function tests that a singular value decomposition can be performed
+ on the random M-by-N matrix A. The test performs the SVD using ?gejsv
+ then performs the following checks:
+
+ * ?gejsv exist successfully (info == 0)
+ * The returned singular values are correct
+ * `A` can be reconstructed from `u`, `SIGMA`, `v`
+ * Ensure that u.T @ u is the identity matrix
+ * Ensure that v.T @ v is the identity matrix
+ * The reported matrix rank
+ * The reported number of singular values
+ * If denormalized floats are required
+
+ Notes
+ -----
+ joba specifies several choices effecting the calculation's accuracy
+ Although all arguments are tested, the tests only check that the correct
+ solution is returned - NOT that the prescribed actions are performed
+ internally.
+
+ jobt is, as of v3.9.0, still experimental and removed to cut down number of
+ test cases. However keyword itself is tested externally.
+ """
+ rng = np.random.RandomState(42)
+
+ # Define some constants for later use:
+ m, n = size
+ atol = 100 * np.finfo(dtype).eps
+ A = generate_random_dtype_array(size, dtype, rng)
+ gejsv = get_lapack_funcs('gejsv', dtype=dtype)
+
+ # Set up checks for invalid job? combinations
+ # if an invalid combination occurs we set the appropriate
+ # exit status.
+ lsvec = jobu < 2 # Calculate left singular vectors
+ rsvec = jobv < 2 # Calculate right singular vectors
+ l2tran = (jobt == 1) and (m == n)
+ is_complex = np.iscomplexobj(A)
+
+ invalid_real_jobv = (jobv == 1) and (not lsvec) and (not is_complex)
+ invalid_cplx_jobu = (jobu == 2) and not (rsvec and l2tran) and is_complex
+ invalid_cplx_jobv = (jobv == 2) and not (lsvec and l2tran) and is_complex
+
+ # Set the exit status to the expected value.
+ # Here we only check for invalid combinations, not individual
+ # parameters.
+ if invalid_cplx_jobu:
+ exit_status = -2
+ elif invalid_real_jobv or invalid_cplx_jobv:
+ exit_status = -3
+ else:
+ exit_status = 0
+
+ if (jobu > 1) and (jobv == 1):
+ assert_raises(Exception, gejsv, A, joba, jobu, jobv, jobr, jobt, jobp)
+ else:
+ sva, u, v, work, iwork, info = gejsv(A,
+ joba=joba,
+ jobu=jobu,
+ jobv=jobv,
+ jobr=jobr,
+ jobt=jobt,
+ jobp=jobp)
+
+ # Check that ?gejsv exited successfully/as expected
+ assert_equal(info, exit_status)
+
+ # If exit_status is non-zero the combination of jobs is invalid.
+ # We test this above but no calculations are performed.
+ if not exit_status:
+
+ # Check the returned singular values
+ sigma = (work[0] / work[1]) * sva[:n]
+ assert_allclose(sigma, svd(A, compute_uv=False), atol=atol)
+
+ if jobu == 1:
+ # If JOBU = 'F', then u contains the M-by-M matrix of
+ # the left singular vectors, including an ONB of the orthogonal
+ # complement of the Range(A)
+ # However, to recalculate A we are concerned about the
+ # first n singular values and so can ignore the latter.
+ # TODO: Add a test for ONB?
+ u = u[:, :n]
+
+ if lsvec and rsvec:
+ assert_allclose(u @ np.diag(sigma) @ v.conj().T, A, atol=atol)
+ if lsvec:
+ assert_allclose(u.conj().T @ u, np.identity(n), atol=atol)
+ if rsvec:
+ assert_allclose(v.conj().T @ v, np.identity(n), atol=atol)
+
+ assert_equal(iwork[0], np.linalg.matrix_rank(A))
+ assert_equal(iwork[1], np.count_nonzero(sigma))
+ # iwork[2] is non-zero if requested accuracy is not warranted for
+ # the data. This should never occur for these tests.
+ assert_equal(iwork[2], 0)
+
+
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+def test_gejsv_edge_arguments(dtype):
+ """Test edge arguments return expected status"""
+ gejsv = get_lapack_funcs('gejsv', dtype=dtype)
+
+ # scalar A
+ sva, u, v, work, iwork, info = gejsv(1.)
+ assert_equal(info, 0)
+ assert_equal(u.shape, (1, 1))
+ assert_equal(v.shape, (1, 1))
+ assert_equal(sva, np.array([1.], dtype=dtype))
+
+ # 1d A
+ A = np.ones((1,), dtype=dtype)
+ sva, u, v, work, iwork, info = gejsv(A)
+ assert_equal(info, 0)
+ assert_equal(u.shape, (1, 1))
+ assert_equal(v.shape, (1, 1))
+ assert_equal(sva, np.array([1.], dtype=dtype))
+
+ # 2d empty A
+ A = np.ones((1, 0), dtype=dtype)
+ sva, u, v, work, iwork, info = gejsv(A)
+ assert_equal(info, 0)
+ assert_equal(u.shape, (1, 0))
+ assert_equal(v.shape, (1, 0))
+ assert_equal(sva, np.array([], dtype=dtype))
+
+ # make sure "overwrite_a" is respected - user reported in gh-13191
+ A = np.sin(np.arange(100).reshape(10, 10)).astype(dtype)
+ A = np.asfortranarray(A + A.T) # make it symmetric and column major
+ Ac = A.copy('A')
+ _ = gejsv(A)
+ assert_allclose(A, Ac)
+
+
+@pytest.mark.parametrize(('kwargs'),
+ ({'joba': 9},
+ {'jobu': 9},
+ {'jobv': 9},
+ {'jobr': 9},
+ {'jobt': 9},
+ {'jobp': 9})
+ )
+def test_gejsv_invalid_job_arguments(kwargs):
+ """Test invalid job arguments raise an Exception"""
+ A = np.ones((2, 2), dtype=float)
+ gejsv = get_lapack_funcs('gejsv', dtype=float)
+ assert_raises(Exception, gejsv, A, **kwargs)
+
+
+@pytest.mark.parametrize("A,sva_expect,u_expect,v_expect",
+ [(np.array([[2.27, -1.54, 1.15, -1.94],
+ [0.28, -1.67, 0.94, -0.78],
+ [-0.48, -3.09, 0.99, -0.21],
+ [1.07, 1.22, 0.79, 0.63],
+ [-2.35, 2.93, -1.45, 2.30],
+ [0.62, -7.39, 1.03, -2.57]]),
+ np.array([9.9966, 3.6831, 1.3569, 0.5000]),
+ np.array([[0.2774, -0.6003, -0.1277, 0.1323],
+ [0.2020, -0.0301, 0.2805, 0.7034],
+ [0.2918, 0.3348, 0.6453, 0.1906],
+ [-0.0938, -0.3699, 0.6781, -0.5399],
+ [-0.4213, 0.5266, 0.0413, -0.0575],
+ [0.7816, 0.3353, -0.1645, -0.3957]]),
+ np.array([[0.1921, -0.8030, 0.0041, -0.5642],
+ [-0.8794, -0.3926, -0.0752, 0.2587],
+ [0.2140, -0.2980, 0.7827, 0.5027],
+ [-0.3795, 0.3351, 0.6178, -0.6017]]))])
+def test_gejsv_NAG(A, sva_expect, u_expect, v_expect):
+ """
+ This test implements the example found in the NAG manual, f08khf.
+ An example was not found for the complex case.
+ """
+ # NAG manual provides accuracy up to 4 decimals
+ atol = 1e-4
+ gejsv = get_lapack_funcs('gejsv', dtype=A.dtype)
+
+ sva, u, v, work, iwork, info = gejsv(A)
+
+ assert_allclose(sva_expect, sva, atol=atol)
+ assert_allclose(u_expect, u, atol=atol)
+ assert_allclose(v_expect, v, atol=atol)
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+def test_gttrf_gttrs(dtype):
+ # The test uses ?gttrf and ?gttrs to solve a random system for each dtype,
+ # tests that the output of ?gttrf define LU matrices, that input
+ # parameters are unmodified, transposal options function correctly, that
+ # incompatible matrix shapes raise an error, and singular matrices return
+ # non zero info.
+
+ rng = np.random.RandomState(42)
+ n = 10
+ atol = 100 * np.finfo(dtype).eps
+
+ # create the matrix in accordance with the data type
+ du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+ d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+ dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+
+ diag_cpy = [dl.copy(), d.copy(), du.copy()]
+
+ A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
+ x = rng.random(n)
+ b = A @ x
+
+ gttrf, gttrs = get_lapack_funcs(('gttrf', 'gttrs'), dtype=dtype)
+
+ _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
+ # test to assure that the inputs of ?gttrf are unmodified
+ assert_array_equal(dl, diag_cpy[0])
+ assert_array_equal(d, diag_cpy[1])
+ assert_array_equal(du, diag_cpy[2])
+
+ # generate L and U factors from ?gttrf return values
+ # L/U are lower/upper triangular by construction (initially and at end)
+ U = np.diag(_d, 0) + np.diag(_du, 1) + np.diag(du2, 2)
+ L = np.eye(n, dtype=dtype)
+
+ for i, m in enumerate(_dl):
+ # L is given in a factored form.
+ # See
+ # www.hpcavf.uclan.ac.uk/softwaredoc/sgi_scsl_html/sgi_html/ch03.html
+ piv = ipiv[i] - 1
+ # right multiply by permutation matrix
+ L[:, [i, piv]] = L[:, [piv, i]]
+ # right multiply by Li, rank-one modification of identity
+ L[:, i] += L[:, i+1]*m
+
+ # one last permutation
+ i, piv = -1, ipiv[-1] - 1
+ # right multiply by final permutation matrix
+ L[:, [i, piv]] = L[:, [piv, i]]
+
+ # check that the outputs of ?gttrf define an LU decomposition of A
+ assert_allclose(A, L @ U, atol=atol)
+
+ b_cpy = b.copy()
+ x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
+ # test that the inputs of ?gttrs are unmodified
+ assert_array_equal(b, b_cpy)
+ # test that the result of ?gttrs matches the expected input
+ assert_allclose(x, x_gttrs, atol=atol)
+
+ # test that ?gttrf and ?gttrs work with transposal options
+ if dtype in REAL_DTYPES:
+ trans = "T"
+ b_trans = A.T @ x
+ else:
+ trans = "C"
+ b_trans = A.conj().T @ x
+
+ x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b_trans, trans=trans)
+ assert_allclose(x, x_gttrs, atol=atol)
+
+ # test that ValueError is raised with incompatible matrix shapes
+ with assert_raises(ValueError):
+ gttrf(dl[:-1], d, du)
+ with assert_raises(ValueError):
+ gttrf(dl, d[:-1], du)
+ with assert_raises(ValueError):
+ gttrf(dl, d, du[:-1])
+
+ # test that matrix of size n=2 raises exception
+ with assert_raises(ValueError):
+ gttrf(dl[0], d[:1], du[0])
+
+ # test that singular (row of all zeroes) matrix fails via info
+ du[0] = 0
+ d[0] = 0
+ __dl, __d, __du, _du2, _ipiv, _info = gttrf(dl, d, du)
+ np.testing.assert_(__d[info - 1] == 0, (f"?gttrf: _d[info-1] is {__d[info - 1]},"
+ " not the illegal value :0."))
+
+
+@pytest.mark.parametrize("du, d, dl, du_exp, d_exp, du2_exp, ipiv_exp, b, x",
+ [(np.array([2.1, -1.0, 1.9, 8.0]),
+ np.array([3.0, 2.3, -5.0, -.9, 7.1]),
+ np.array([3.4, 3.6, 7.0, -6.0]),
+ np.array([2.3, -5, -.9, 7.1]),
+ np.array([3.4, 3.6, 7, -6, -1.015373]),
+ np.array([-1, 1.9, 8]),
+ np.array([2, 3, 4, 5, 5]),
+ np.array([[2.7, 6.6],
+ [-0.5, 10.8],
+ [2.6, -3.2],
+ [0.6, -11.2],
+ [2.7, 19.1]
+ ]),
+ np.array([[-4, 5],
+ [7, -4],
+ [3, -3],
+ [-4, -2],
+ [-3, 1]])),
+ (
+ np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
+ np.array([-1.3 + 1.3j, -1.3 + 1.3j,
+ -1.3 + 3.3j, - .3 + 4.3j,
+ -3.3 + 1.3j]),
+ np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
+ # du exp
+ np.array([-1.3 + 1.3j, -1.3 + 3.3j,
+ -0.3 + 4.3j, -3.3 + 1.3j]),
+ np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j,
+ -1.3399 + 0.2875j]),
+ np.array([2 + 1j, -1 + 1j, 1 - 1j]),
+ np.array([2, 3, 4, 5, 5]),
+ np.array([[2.4 - 5j, 2.7 + 6.9j],
+ [3.4 + 18.2j, - 6.9 - 5.3j],
+ [-14.7 + 9.7j, - 6 - .6j],
+ [31.9 - 7.7j, -3.9 + 9.3j],
+ [-1 + 1.6j, -3 + 12.2j]]),
+ np.array([[1 + 1j, 2 - 1j],
+ [3 - 1j, 1 + 2j],
+ [4 + 5j, -1 + 1j],
+ [-1 - 2j, 2 + 1j],
+ [1 - 1j, 2 - 2j]])
+ )])
+def test_gttrf_gttrs_NAG_f07cdf_f07cef_f07crf_f07csf(du, d, dl, du_exp, d_exp,
+ du2_exp, ipiv_exp, b, x):
+ # test to assure that wrapper is consistent with NAG Library Manual Mark 26
+ # example problems: f07cdf and f07cef (real)
+ # examples: f07crf and f07csf (complex)
+ # (Links may expire, so search for "NAG Library Manual Mark 26" online)
+
+ gttrf, gttrs = get_lapack_funcs(('gttrf', "gttrs"), (du[0], du[0]))
+
+ _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
+ assert_allclose(du2, du2_exp)
+ assert_allclose(_du, du_exp)
+ assert_allclose(_d, d_exp, atol=1e-4) # NAG examples provide 4 decimals.
+ assert_allclose(ipiv, ipiv_exp)
+
+ x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
+
+ assert_allclose(x_gttrs, x)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('norm', ['1', 'I', 'O'])
+@pytest.mark.parametrize('n', [3, 10])
+def test_gtcon(dtype, norm, n):
+ rng = np.random.default_rng(23498324)
+
+ d = rng.random(n) + rng.random(n)*1j
+ dl = rng.random(n - 1) + rng.random(n - 1)*1j
+ du = rng.random(n - 1) + rng.random(n - 1)*1j
+ A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
+ if np.issubdtype(dtype, np.floating):
+ A, d, dl, du = A.real, d.real, dl.real, du.real
+ A, d, dl, du = A.astype(dtype), d.astype(dtype), dl.astype(dtype), du.astype(dtype)
+
+ anorm = np.linalg.norm(A, ord=np.inf if norm == 'I' else 1)
+
+ gttrf, gtcon = get_lapack_funcs(('gttrf', 'gtcon'), (A,))
+ dl, d, du, du2, ipiv, info = gttrf(dl, d, du)
+ res, _ = gtcon(dl, d, du, du2, ipiv, anorm, norm=norm)
+
+ gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
+ lu, ipvt, info = getrf(A)
+ ref, _ = gecon(lu, anorm, norm=norm)
+
+ rtol = np.finfo(dtype).eps**0.75
+ assert_allclose(res, ref, rtol=rtol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('shape', [(3, 7), (7, 3), (2**18, 2**18)])
+def test_geqrfp_lwork(dtype, shape):
+ geqrfp_lwork = get_lapack_funcs(('geqrfp_lwork'), dtype=dtype)
+ m, n = shape
+ lwork, info = geqrfp_lwork(m=m, n=n)
+ assert_equal(info, 0)
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+ list(zip(REAL_DTYPES + REAL_DTYPES, DTYPES)))
+def test_pttrf_pttrs(ddtype, dtype):
+ rng = np.random.RandomState(42)
+ # set test tolerance appropriate for dtype
+ atol = 100*np.finfo(dtype).eps
+ # n is the length diagonal of A
+ n = 10
+ # create diagonals according to size and dtype
+
+ # diagonal d should always be real.
+ # add 4 to d so it will be dominant for all dtypes
+ d = generate_random_dtype_array((n,), ddtype, rng) + 4
+ # diagonal e may be real or complex.
+ e = generate_random_dtype_array((n-1,), dtype, rng)
+
+ # assemble diagonals together into matrix
+ A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+ # store a copy of diagonals to later verify
+ diag_cpy = [d.copy(), e.copy()]
+
+ pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+
+ _d, _e, info = pttrf(d, e)
+ # test to assure that the inputs of ?pttrf are unmodified
+ assert_array_equal(d, diag_cpy[0])
+ assert_array_equal(e, diag_cpy[1])
+ assert_equal(info, 0, err_msg=f"pttrf: info = {info}, should be 0")
+
+ # test that the factors from pttrf can be recombined to make A
+ L = np.diag(_e, -1) + np.diag(np.ones(n))
+ D = np.diag(_d)
+
+ assert_allclose(A, L@D@L.conjugate().T, atol=atol)
+
+ # generate random solution x
+ x = generate_random_dtype_array((n,), dtype, rng)
+ # determine accompanying b to get soln x
+ b = A@x
+
+ # determine _x from pttrs
+ pttrs = get_lapack_funcs('pttrs', dtype=dtype)
+ _x, info = pttrs(_d, _e.conj(), b)
+ assert_equal(info, 0, err_msg=f"pttrs: info = {info}, should be 0")
+
+ # test that _x from pttrs matches the expected x
+ assert_allclose(x, _x, atol=atol)
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+ list(zip(REAL_DTYPES + REAL_DTYPES, DTYPES)))
+def test_pttrf_pttrs_errors_incompatible_shape(ddtype, dtype):
+ n = 10
+ rng = np.random.RandomState(1234)
+ pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+ d = generate_random_dtype_array((n,), ddtype, rng) + 2
+ e = generate_random_dtype_array((n-1,), dtype, rng)
+ # test that ValueError is raised with incompatible matrix shapes
+ assert_raises(ValueError, pttrf, d[:-1], e)
+ assert_raises(ValueError, pttrf, d, e[:-1])
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+ list(zip(REAL_DTYPES + REAL_DTYPES, DTYPES)))
+def test_pttrf_pttrs_errors_singular_nonSPD(ddtype, dtype):
+ n = 10
+ rng = np.random.RandomState(42)
+ pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+ d = generate_random_dtype_array((n,), ddtype, rng) + 2
+ e = generate_random_dtype_array((n-1,), dtype, rng)
+ # test that singular (row of all zeroes) matrix fails via info
+ d[0] = 0
+ e[0] = 0
+ _d, _e, info = pttrf(d, e)
+ assert_equal(_d[info - 1], 0,
+ f"?pttrf: _d[info-1] is {_d[info - 1]}, not the illegal value :0.")
+
+ # test with non-spd matrix
+ d = generate_random_dtype_array((n,), ddtype, rng)
+ _d, _e, info = pttrf(d, e)
+ assert_(info != 0, "?pttrf should fail with non-spd matrix, but didn't")
+
+
+@pytest.mark.parametrize(("d, e, d_expect, e_expect, b, x_expect"), [
+ (np.array([4, 10, 29, 25, 5]),
+ np.array([-2, -6, 15, 8]),
+ np.array([4, 9, 25, 16, 1]),
+ np.array([-.5, -.6667, .6, .5]),
+ np.array([[6, 10], [9, 4], [2, 9], [14, 65],
+ [7, 23]]),
+ np.array([[2.5, 2], [2, -1], [1, -3], [-1, 6],
+ [3, -5]])
+ ), (
+ np.array([16, 41, 46, 21]),
+ np.array([16 + 16j, 18 - 9j, 1 - 4j]),
+ np.array([16, 9, 1, 4]),
+ np.array([1+1j, 2-1j, 1-4j]),
+ np.array([[64+16j, -16-32j], [93+62j, 61-66j],
+ [78-80j, 71-74j], [14-27j, 35+15j]]),
+ np.array([[2+1j, -3-2j], [1+1j, 1+1j], [1-2j, 1-2j],
+ [1-1j, 2+1j]])
+ )])
+def test_pttrf_pttrs_NAG(d, e, d_expect, e_expect, b, x_expect):
+ # test to assure that wrapper is consistent with NAG Manual Mark 26
+ # example problems: f07jdf and f07jef (real)
+ # examples: f07jrf and f07csf (complex)
+ # NAG examples provide 4 decimals.
+ # (Links expire, so please search for "NAG Library Manual Mark 26" online)
+
+ atol = 1e-4
+ pttrf = get_lapack_funcs('pttrf', dtype=e[0])
+ _d, _e, info = pttrf(d, e)
+ assert_allclose(_d, d_expect, atol=atol)
+ assert_allclose(_e, e_expect, atol=atol)
+
+ pttrs = get_lapack_funcs('pttrs', dtype=e[0])
+ _x, info = pttrs(_d, _e.conj(), b)
+ assert_allclose(_x, x_expect, atol=atol)
+
+ # also test option `lower`
+ if e.dtype in COMPLEX_DTYPES:
+ _x, info = pttrs(_d, _e, b, lower=1)
+ assert_allclose(_x, x_expect, atol=atol)
+
+
+def pteqr_get_d_e_A_z(dtype, realtype, n, compute_z):
+ # used by ?pteqr tests to build parameters
+ # returns tuple of (d, e, A, z)
+ rng = np.random.RandomState(42)
+ if compute_z == 1:
+ # build Hermitian A from Q**T * tri * Q = A by creating Q and tri
+ A_eig = generate_random_dtype_array((n, n), dtype, rng)
+ A_eig = A_eig + np.diag(np.zeros(n) + 4*n)
+ A_eig = (A_eig + A_eig.conj().T) / 2
+ # obtain right eigenvectors (orthogonal)
+ vr = eigh(A_eig)[1]
+ # create tridiagonal matrix
+ d = generate_random_dtype_array((n,), realtype, rng) + 4
+ e = generate_random_dtype_array((n-1,), realtype, rng)
+ tri = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+ # Build A using these factors that sytrd would: (Q**T * tri * Q = A)
+ A = vr @ tri @ vr.conj().T
+ # vr is orthogonal
+ z = vr
+
+ else:
+ # d and e are always real per lapack docs.
+ d = generate_random_dtype_array((n,), realtype, rng)
+ e = generate_random_dtype_array((n-1,), realtype, rng)
+
+ # make SPD
+ d = d + 4
+ A = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+ z = np.diag(d) + np.diag(e, -1) + np.diag(e, 1)
+ return (d, e, A, z)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+ list(zip(DTYPES, REAL_DTYPES + REAL_DTYPES)))
+@pytest.mark.parametrize("compute_z", list(range(3)))
+def test_pteqr(dtype, realtype, compute_z):
+ '''
+ Tests the ?pteqr lapack routine for all dtypes and compute_z parameters.
+ It generates random SPD matrix diagonals d and e, and then confirms
+ correct eigenvalues with scipy.linalg.eig. With applicable compute_z=2 it
+ tests that z can reform A.
+ '''
+ atol = 1000*np.finfo(dtype).eps
+ pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+
+ n = 10
+
+ d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+
+ d_pteqr, e_pteqr, z_pteqr, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
+ assert_equal(info, 0, f"info = {info}, should be 0.")
+
+ # compare the routine's eigenvalues with scipy.linalg.eig's.
+ assert_allclose(np.sort(eigh(A)[0]), np.sort(d_pteqr), atol=atol)
+
+ if compute_z:
+ # verify z_pteqr as orthogonal
+ assert_allclose(z_pteqr @ np.conj(z_pteqr).T, np.identity(n),
+ atol=atol)
+ # verify that z_pteqr recombines to A
+ assert_allclose(z_pteqr @ np.diag(d_pteqr) @ np.conj(z_pteqr).T,
+ A, atol=atol)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+ list(zip(DTYPES, REAL_DTYPES + REAL_DTYPES)))
+@pytest.mark.parametrize("compute_z", list(range(3)))
+def test_pteqr_error_non_spd(dtype, realtype, compute_z):
+ pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+
+ n = 10
+ d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+
+ # test with non-spd matrix
+ d_pteqr, e_pteqr, z_pteqr, info = pteqr(d - 4, e, z=z, compute_z=compute_z)
+ assert info > 0
+
+
+@pytest.mark.parametrize("dtype,realtype",
+ list(zip(DTYPES, REAL_DTYPES + REAL_DTYPES)))
+@pytest.mark.parametrize("compute_z", list(range(3)))
+def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z):
+ pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+ n = 10
+ d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+ # test with incorrect/incompatible array sizes
+ assert_raises(ValueError, pteqr, d[:-1], e, z=z, compute_z=compute_z)
+ assert_raises(ValueError, pteqr, d, e[:-1], z=z, compute_z=compute_z)
+ if compute_z:
+ assert_raises(ValueError, pteqr, d, e, z=z[:-1], compute_z=compute_z)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+ list(zip(DTYPES, REAL_DTYPES + REAL_DTYPES)))
+@pytest.mark.parametrize("compute_z", list(range(3)))
+def test_pteqr_error_singular(dtype, realtype, compute_z):
+ pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+ n = 10
+ d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+ # test with singular matrix
+ d[0] = 0
+ e[0] = 0
+ d_pteqr, e_pteqr, z_pteqr, info = pteqr(d, e, z=z, compute_z=compute_z)
+ assert info > 0
+
+
+@pytest.mark.parametrize("compute_z,d,e,d_expect,z_expect",
+ [(2, # "I"
+ np.array([4.16, 5.25, 1.09, .62]),
+ np.array([3.17, -.97, .55]),
+ np.array([8.0023, 1.9926, 1.0014, 0.1237]),
+ np.array([[0.6326, 0.6245, -0.4191, 0.1847],
+ [0.7668, -0.4270, 0.4176, -0.2352],
+ [-0.1082, 0.6071, 0.4594, -0.6393],
+ [-0.0081, 0.2432, 0.6625, 0.7084]])),
+ ])
+def test_pteqr_NAG_f08jgf(compute_z, d, e, d_expect, z_expect):
+ '''
+ Implements real (f08jgf) example from NAG Manual Mark 26.
+ Tests for correct outputs.
+ '''
+ # the NAG manual has 4 decimals accuracy
+ atol = 1e-4
+ pteqr = get_lapack_funcs(('pteqr'), dtype=d.dtype)
+
+ z = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+ _d, _e, _z, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
+ assert_allclose(_d, d_expect, atol=atol)
+ assert_allclose(np.abs(_z), np.abs(z_expect), atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('matrix_size', [(3, 4), (7, 6), (6, 6)])
+def test_geqrfp(dtype, matrix_size):
+ # Tests for all dytpes, tall, wide, and square matrices.
+ # Using the routine with random matrix A, Q and R are obtained and then
+ # tested such that R is upper triangular and non-negative on the diagonal,
+ # and Q is an orthogonal matrix. Verifies that A=Q@R. It also
+ # tests against a matrix that for which the linalg.qr method returns
+ # negative diagonals, and for error messaging.
+
+ # set test tolerance appropriate for dtype
+ rng = np.random.RandomState(42)
+ rtol = 250*np.finfo(dtype).eps
+ atol = 100*np.finfo(dtype).eps
+ # get appropriate ?geqrfp for dtype
+ geqrfp = get_lapack_funcs(('geqrfp'), dtype=dtype)
+ gqr = get_lapack_funcs(("orgqr"), dtype=dtype)
+
+ m, n = matrix_size
+
+ # create random matrix of dimensions m x n
+ A = generate_random_dtype_array((m, n), dtype=dtype, rng=rng)
+ # create qr matrix using geqrfp
+ qr_A, tau, info = geqrfp(A)
+
+ # obtain r from the upper triangular area
+ r = np.triu(qr_A)
+
+ # obtain q from the orgqr lapack routine
+ # based on linalg.qr's extraction strategy of q with orgqr
+
+ if m > n:
+ # this adds an extra column to the end of qr_A
+ # let qqr be an empty m x m matrix
+ qqr = np.zeros((m, m), dtype=dtype)
+ # set first n columns of qqr to qr_A
+ qqr[:, :n] = qr_A
+ # determine q from this qqr
+ # note that m is a sufficient for lwork based on LAPACK documentation
+ q = gqr(qqr, tau=tau, lwork=m)[0]
+ else:
+ q = gqr(qr_A[:, :m], tau=tau, lwork=m)[0]
+
+ # test that q and r still make A
+ assert_allclose(q@r, A, rtol=rtol)
+ # ensure that q is orthogonal (that q @ transposed q is the identity)
+ assert_allclose(np.eye(q.shape[0]), q@(q.conj().T), rtol=rtol,
+ atol=atol)
+ # ensure r is upper tri by comparing original r to r as upper triangular
+ assert_allclose(r, np.triu(r), rtol=rtol)
+ # make sure diagonals of r are positive for this random solution
+ assert_(np.all(np.diag(r) > np.zeros(len(np.diag(r)))))
+ # ensure that info is zero for this success
+ assert_(info == 0)
+
+ # test that this routine gives r diagonals that are positive for a
+ # matrix that returns negatives in the diagonal with scipy.linalg.rq
+ A_negative = generate_random_dtype_array((n, m), dtype=dtype, rng=rng) * -1
+ r_rq_neg, q_rq_neg = qr(A_negative)
+ rq_A_neg, tau_neg, info_neg = geqrfp(A_negative)
+ # assert that any of the entries on the diagonal from linalg.qr
+ # are negative and that all of geqrfp are positive.
+ assert_(np.any(np.diag(r_rq_neg) < 0) and
+ np.all(np.diag(r) > 0))
+
+
+def test_geqrfp_errors_with_empty_array():
+ # check that empty array raises good error message
+ A_empty = np.array([])
+ geqrfp = get_lapack_funcs('geqrfp', dtype=A_empty.dtype)
+ assert_raises(Exception, geqrfp, A_empty)
+
+
+@pytest.mark.parametrize("driver", ['ev', 'evd', 'evr', 'evx'])
+@pytest.mark.parametrize("pfx", ['sy', 'he'])
+def test_standard_eigh_lworks(pfx, driver):
+ n = 1200 # Some sufficiently big arbitrary number
+ dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
+ sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
+ dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
+ try:
+ _compute_lwork(sc_dlw, n, lower=1)
+ _compute_lwork(dz_dlw, n, lower=1)
+ except Exception as e:
+ pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
+
+
+@pytest.mark.parametrize("driver", ['gv', 'gvx'])
+@pytest.mark.parametrize("pfx", ['sy', 'he'])
+def test_generalized_eigh_lworks(pfx, driver):
+ n = 1200 # Some sufficiently big arbitrary number
+ dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
+ sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
+ dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
+ # Shouldn't raise any exceptions
+ try:
+ _compute_lwork(sc_dlw, n, uplo="L")
+ _compute_lwork(dz_dlw, n, uplo="L")
+ except Exception as e:
+ pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
+
+
+@pytest.mark.parametrize("dtype_", DTYPES)
+@pytest.mark.parametrize("m", [1, 10, 100, 1000])
+def test_orcsd_uncsd_lwork(dtype_, m):
+ rng = np.random.default_rng(1234)
+ p = rng.integers(0, m)
+ q = m - p
+ pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
+ dlw = pfx + 'csd_lwork'
+ lw = get_lapack_funcs(dlw, dtype=dtype_)
+ lwval = _compute_lwork(lw, m, p, q)
+ lwval = lwval if pfx == 'un' else (lwval,)
+ assert all([x > 0 for x in lwval])
+
+
+@pytest.mark.parametrize("dtype_", DTYPES)
+def test_orcsd_uncsd(dtype_):
+ m, p, q = 250, 80, 170
+
+ pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
+ X = ortho_group.rvs(m) if pfx == 'or' else unitary_group.rvs(m)
+
+ drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), dtype=dtype_)
+ lwval = _compute_lwork(dlw, m, p, q)
+ lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork',
+ 'lrwork'], lwval))
+
+ cs11, cs12, cs21, cs22, theta, u1, u2, v1t, v2t, info =\
+ drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals)
+
+ assert info == 0
+
+ U = block_diag(u1, u2)
+ VH = block_diag(v1t, v2t)
+ r = min(min(p, q), min(m-p, m-q))
+ n11 = min(p, q) - r
+ n12 = min(p, m-q) - r
+ n21 = min(m-p, q) - r
+ n22 = min(m-p, m-q) - r
+
+ S = np.zeros((m, m), dtype=dtype_)
+ one = dtype_(1.)
+ for i in range(n11):
+ S[i, i] = one
+ for i in range(n22):
+ S[p+i, q+i] = one
+ for i in range(n12):
+ S[i+n11+r, i+n11+r+n21+n22+r] = -one
+ for i in range(n21):
+ S[p+n22+r+i, n11+r+i] = one
+
+ for i in range(r):
+ S[i+n11, i+n11] = np.cos(theta[i])
+ S[p+n22+i, i+r+n21+n22] = np.cos(theta[i])
+
+ S[i+n11, i+n11+n21+n22+r] = -np.sin(theta[i])
+ S[p+n22+i, i+n11] = np.sin(theta[i])
+
+ Xc = U @ S @ VH
+ assert_allclose(X, Xc, rtol=0., atol=1e4*np.finfo(dtype_).eps)
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("trans_bool", [False, True])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx(dtype, trans_bool, fact):
+ """
+ These tests uses ?gtsvx to solve a random Ax=b system for each dtype.
+ It tests that the outputs define an LU matrix, that inputs are unmodified,
+ transposal options, incompatible shapes, singular matrices, and
+ singular factorizations. It parametrizes DTYPES and the 'fact' value along
+ with the fact related inputs.
+ """
+ rng = np.random.RandomState(42)
+ # set test tolerance appropriate for dtype
+ atol = 100 * np.finfo(dtype).eps
+ # obtain routine
+ gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+ # Generate random tridiagonal matrix A
+ n = 10
+ dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+ d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+ du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+ A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+ # generate random solution x
+ x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+ # create b from x for equation Ax=b
+ trans = ("T" if dtype in REAL_DTYPES else "C") if trans_bool else "N"
+ b = (A.conj().T if trans_bool else A) @ x
+
+ # store a copy of the inputs to check they haven't been modified later
+ inputs_cpy = [dl.copy(), d.copy(), du.copy(), b.copy()]
+
+ # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+ dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+ gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+ gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+ assert_(info == 0, f"?gtsvx info = {info}, should be zero")
+
+ # assure that inputs are unmodified
+ assert_array_equal(dl, inputs_cpy[0])
+ assert_array_equal(d, inputs_cpy[1])
+ assert_array_equal(du, inputs_cpy[2])
+ assert_array_equal(b, inputs_cpy[3])
+
+ # test that x_soln matches the expected x
+ assert_allclose(x, x_soln, atol=atol)
+
+ # assert that the outputs are of correct type or shape
+ # rcond should be a scalar
+ assert_(hasattr(rcond, "__len__") is not True,
+ f"rcond should be scalar but is {rcond}")
+ # ferr should be length of # of cols in x
+ assert_(ferr.shape[0] == b.shape[1], (f"ferr.shape is {ferr.shape[0]} but should"
+ f" be {b.shape[1]}"))
+ # berr should be length of # of cols in x
+ assert_(berr.shape[0] == b.shape[1], (f"berr.shape is {berr.shape[0]} but should"
+ f" be {b.shape[1]}"))
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("trans_bool", [0, 1])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx_error_singular(dtype, trans_bool, fact):
+ rng = np.random.RandomState(42)
+ # obtain routine
+ gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+ # Generate random tridiagonal matrix A
+ n = 10
+ dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+ d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+ du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+ A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+ # generate random solution x
+ x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+ # create b from x for equation Ax=b
+ trans = "T" if dtype in REAL_DTYPES else "C"
+ b = (A.conj().T if trans_bool else A) @ x
+
+ # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+ dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+ gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+ gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+ # test with singular matrix
+ # no need to test inputs with fact "F" since ?gttrf already does.
+ if fact == "N":
+ # Construct a singular example manually
+ d[-1] = 0
+ dl[-1] = 0
+ # solve using routine
+ gtsvx_out = gtsvx(dl, d, du, b)
+ dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+ # test for the singular matrix.
+ assert info > 0, "info should be > 0 for singular matrix"
+
+ elif fact == 'F':
+ # assuming that a singular factorization is input
+ df_[-1] = 0
+ duf_[-1] = 0
+ du2f_[-1] = 0
+
+ gtsvx_out = gtsvx(dl, d, du, b, fact=fact, dlf=dlf_, df=df_, duf=duf_,
+ du2=du2f_, ipiv=ipiv_)
+ dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+ # info should not be zero and should provide index of illegal value
+ assert info > 0, "info should be > 0 for singular matrix"
+
+
+@pytest.mark.parametrize("dtype", DTYPES*2)
+@pytest.mark.parametrize("trans_bool", [False, True])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx_error_incompatible_size(dtype, trans_bool, fact):
+ rng = np.random.RandomState(42)
+ # obtain routine
+ gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+ # Generate random tridiagonal matrix A
+ n = 10
+ dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+ d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+ du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+ A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+ # generate random solution x
+ x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+ # create b from x for equation Ax=b
+ trans = "T" if dtype in REAL_DTYPES else "C"
+ b = (A.conj().T if trans_bool else A) @ x
+
+ # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+ dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+ gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+ if fact == "N":
+ assert_raises(ValueError, gtsvx, dl[:-1], d, du, b,
+ fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ assert_raises(ValueError, gtsvx, dl, d[:-1], du, b,
+ fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ assert_raises(ValueError, gtsvx, dl, d, du[:-1], b,
+ fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ assert_raises(Exception, gtsvx, dl, d, du, b[:-1],
+ fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ else:
+ assert_raises(ValueError, gtsvx, dl, d, du, b,
+ fact=fact, trans=trans, dlf=dlf_[:-1], df=df_,
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ assert_raises(ValueError, gtsvx, dl, d, du, b,
+ fact=fact, trans=trans, dlf=dlf_, df=df_[:-1],
+ duf=duf_, du2=du2f_, ipiv=ipiv_)
+ assert_raises(ValueError, gtsvx, dl, d, du, b,
+ fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_[:-1], du2=du2f_, ipiv=ipiv_)
+ assert_raises(ValueError, gtsvx, dl, d, du, b,
+ fact=fact, trans=trans, dlf=dlf_, df=df_,
+ duf=duf_, du2=du2f_[:-1], ipiv=ipiv_)
+
+
+@pytest.mark.parametrize("du,d,dl,b,x",
+ [(np.array([2.1, -1.0, 1.9, 8.0]),
+ np.array([3.0, 2.3, -5.0, -0.9, 7.1]),
+ np.array([3.4, 3.6, 7.0, -6.0]),
+ np.array([[2.7, 6.6], [-.5, 10.8], [2.6, -3.2],
+ [.6, -11.2], [2.7, 19.1]]),
+ np.array([[-4, 5], [7, -4], [3, -3], [-4, -2],
+ [-3, 1]])),
+ (np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
+ np.array([-1.3 + 1.3j, -1.3 + 1.3j, -1.3 + 3.3j,
+ -.3 + 4.3j, -3.3 + 1.3j]),
+ np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
+ np.array([[2.4 - 5j, 2.7 + 6.9j],
+ [3.4 + 18.2j, -6.9 - 5.3j],
+ [-14.7 + 9.7j, -6 - .6j],
+ [31.9 - 7.7j, -3.9 + 9.3j],
+ [-1 + 1.6j, -3 + 12.2j]]),
+ np.array([[1 + 1j, 2 - 1j], [3 - 1j, 1 + 2j],
+ [4 + 5j, -1 + 1j], [-1 - 2j, 2 + 1j],
+ [1 - 1j, 2 - 2j]]))])
+def test_gtsvx_NAG(du, d, dl, b, x):
+ # Test to ensure wrapper is consistent with NAG Manual Mark 26
+ # example problems: real (f07cbf) and complex (f07cpf)
+ gtsvx = get_lapack_funcs('gtsvx', dtype=d.dtype)
+
+ gtsvx_out = gtsvx(dl, d, du, b)
+ dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+
+ assert_array_almost_equal(x, x_soln)
+
+
+@pytest.mark.parametrize("dtype,realtype", list(zip(DTYPES, REAL_DTYPES
+ + REAL_DTYPES)))
+@pytest.mark.parametrize("fact,df_de_lambda",
+ [("F",
+ lambda d, e: get_lapack_funcs('pttrf',
+ dtype=e.dtype)(d, e)),
+ ("N", lambda d, e: (None, None, None))])
+def test_ptsvx(dtype, realtype, fact, df_de_lambda):
+ '''
+ This tests the ?ptsvx lapack routine wrapper to solve a random system
+ Ax = b for all dtypes and input variations. Tests for: unmodified
+ input parameters, fact options, incompatible matrix shapes raise an error,
+ and singular matrices return info of illegal value.
+ '''
+ rng = np.random.RandomState(42)
+ # set test tolerance appropriate for dtype
+ atol = 100 * np.finfo(dtype).eps
+ ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+ n = 5
+ # create diagonals according to size and dtype
+ d = generate_random_dtype_array((n,), realtype, rng) + 4
+ e = generate_random_dtype_array((n-1,), dtype, rng)
+ A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+ x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+ b = A @ x_soln
+
+ # use lambda to determine what df, ef are
+ df, ef, info = df_de_lambda(d, e)
+
+ # create copy to later test that they are unmodified
+ diag_cpy = [d.copy(), e.copy(), b.copy()]
+
+ # solve using routine
+ df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
+ df=df, ef=ef)
+ # d, e, and b should be unmodified
+ assert_array_equal(d, diag_cpy[0])
+ assert_array_equal(e, diag_cpy[1])
+ assert_array_equal(b, diag_cpy[2])
+ assert_(info == 0, f"info should be 0 but is {info}.")
+ assert_array_almost_equal(x_soln, x)
+
+ # test that the factors from ptsvx can be recombined to make A
+ L = np.diag(ef, -1) + np.diag(np.ones(n))
+ D = np.diag(df)
+ assert_allclose(A, L@D@(np.conj(L).T), atol=atol)
+
+ # assert that the outputs are of correct type or shape
+ # rcond should be a scalar
+ assert not hasattr(rcond, "__len__"), \
+ f"rcond should be scalar but is {rcond}"
+ # ferr should be length of # of cols in x
+ assert_(ferr.shape == (2,), (f"ferr.shape is {ferr.shape} but should be "
+ "({x_soln.shape[1]},)"))
+ # berr should be length of # of cols in x
+ assert_(berr.shape == (2,), (f"berr.shape is {berr.shape} but should be "
+ "({x_soln.shape[1]},)"))
+
+
+@pytest.mark.parametrize("dtype,realtype", list(zip(DTYPES, REAL_DTYPES
+ + REAL_DTYPES)))
+@pytest.mark.parametrize("fact,df_de_lambda",
+ [("F",
+ lambda d, e: get_lapack_funcs('pttrf',
+ dtype=e.dtype)(d, e)),
+ ("N", lambda d, e: (None, None, None))])
+def test_ptsvx_error_raise_errors(dtype, realtype, fact, df_de_lambda):
+ rng = np.random.RandomState(42)
+ ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+ n = 5
+ # create diagonals according to size and dtype
+ d = generate_random_dtype_array((n,), realtype, rng) + 4
+ e = generate_random_dtype_array((n-1,), dtype, rng)
+ A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+ x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+ b = A @ x_soln
+
+ # use lambda to determine what df, ef are
+ df, ef, info = df_de_lambda(d, e)
+
+ # test with malformatted array sizes
+ assert_raises(ValueError, ptsvx, d[:-1], e, b, fact=fact, df=df, ef=ef)
+ assert_raises(ValueError, ptsvx, d, e[:-1], b, fact=fact, df=df, ef=ef)
+ assert_raises(Exception, ptsvx, d, e, b[:-1], fact=fact, df=df, ef=ef)
+
+
+@pytest.mark.parametrize("dtype,realtype", list(zip(DTYPES, REAL_DTYPES
+ + REAL_DTYPES)))
+@pytest.mark.parametrize("fact,df_de_lambda",
+ [("F",
+ lambda d, e: get_lapack_funcs('pttrf',
+ dtype=e.dtype)(d, e)),
+ ("N", lambda d, e: (None, None, None))])
+def test_ptsvx_non_SPD_singular(dtype, realtype, fact, df_de_lambda):
+ rng = np.random.RandomState(42)
+ ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+ n = 5
+ # create diagonals according to size and dtype
+ d = generate_random_dtype_array((n,), realtype, rng) + 4
+ e = generate_random_dtype_array((n-1,), dtype, rng)
+ A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+ x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+ b = A @ x_soln
+
+ # use lambda to determine what df, ef are
+ df, ef, info = df_de_lambda(d, e)
+
+ if fact == "N":
+ d[3] = 0
+ # obtain new df, ef
+ df, ef, info = df_de_lambda(d, e)
+ # solve using routine
+ df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
+ # test for the singular matrix.
+ assert info > 0 and info <= n
+
+ # non SPD matrix
+ d = generate_random_dtype_array((n,), realtype, rng)
+ df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
+ assert info > 0 and info <= n
+ else:
+ # assuming that someone is using a singular factorization
+ df, ef, info = df_de_lambda(d, e)
+ df[0] = 0
+ ef[0] = 0
+ df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
+ df=df, ef=ef)
+ assert info > 0
+
+
+@pytest.mark.parametrize('d,e,b,x',
+ [(np.array([4, 10, 29, 25, 5]),
+ np.array([-2, -6, 15, 8]),
+ np.array([[6, 10], [9, 4], [2, 9], [14, 65],
+ [7, 23]]),
+ np.array([[2.5, 2], [2, -1], [1, -3],
+ [-1, 6], [3, -5]])),
+ (np.array([16, 41, 46, 21]),
+ np.array([16 + 16j, 18 - 9j, 1 - 4j]),
+ np.array([[64 + 16j, -16 - 32j],
+ [93 + 62j, 61 - 66j],
+ [78 - 80j, 71 - 74j],
+ [14 - 27j, 35 + 15j]]),
+ np.array([[2 + 1j, -3 - 2j],
+ [1 + 1j, 1 + 1j],
+ [1 - 2j, 1 - 2j],
+ [1 - 1j, 2 + 1j]]))])
+def test_ptsvx_NAG(d, e, b, x):
+ # test to assure that wrapper is consistent with NAG Manual Mark 26
+ # example problems: f07jbf, f07jpf
+ # (Links expire, so please search for "NAG Library Manual Mark 26" online)
+
+ # obtain routine with correct type based on e.dtype
+ ptsvx = get_lapack_funcs('ptsvx', dtype=e.dtype)
+ # solve using routine
+ df, ef, x_ptsvx, rcond, ferr, berr, info = ptsvx(d, e, b)
+ # determine ptsvx's solution and x are the same.
+ assert_array_almost_equal(x, x_ptsvx)
+
+
+@pytest.mark.parametrize('lower', [False, True])
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_pptrs_pptri_pptrf_ppsv_ppcon(dtype, lower):
+ rng = np.random.RandomState(1234)
+ atol = np.finfo(dtype).eps*100
+ # Manual conversion to/from packed format is feasible here.
+ n, nrhs = 10, 4
+ a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+ b = generate_random_dtype_array([n, nrhs], dtype=dtype, rng=rng)
+
+ a = a.conj().T + a + np.eye(n, dtype=dtype) * dtype(5.)
+ if lower:
+ inds = ([x for y in range(n) for x in range(y, n)],
+ [y for y in range(n) for x in range(y, n)])
+ else:
+ inds = ([x for y in range(1, n+1) for x in range(y)],
+ [y-1 for y in range(1, n+1) for x in range(y)])
+ ap = a[inds]
+ ppsv, pptrf, pptrs, pptri, ppcon = get_lapack_funcs(
+ ('ppsv', 'pptrf', 'pptrs', 'pptri', 'ppcon'),
+ dtype=dtype,
+ ilp64="preferred")
+
+ ul, info = pptrf(n, ap, lower=lower)
+ assert_equal(info, 0)
+ aul = cholesky(a, lower=lower)[inds]
+ assert_allclose(ul, aul, rtol=0, atol=atol)
+
+ uli, info = pptri(n, ul, lower=lower)
+ assert_equal(info, 0)
+ auli = inv(a)[inds]
+ assert_allclose(uli, auli, rtol=0, atol=atol)
+
+ x, info = pptrs(n, ul, b, lower=lower)
+ assert_equal(info, 0)
+ bx = solve(a, b)
+ assert_allclose(x, bx, rtol=0, atol=atol)
+
+ xv, info = ppsv(n, ap, b, lower=lower)
+ assert_equal(info, 0)
+ assert_allclose(xv, bx, rtol=0, atol=atol)
+
+ anorm = np.linalg.norm(a, 1)
+ rcond, info = ppcon(n, ap, anorm=anorm, lower=lower)
+ assert_equal(info, 0)
+ assert_(abs(1/rcond - np.linalg.cond(a, p=1))*rcond < 1)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gees_trexc(dtype):
+ rng = np.random.RandomState(1234)
+ atol = np.finfo(dtype).eps*100
+
+ n = 10
+ a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+ gees, trexc = get_lapack_funcs(('gees', 'trexc'), dtype=dtype)
+
+ result = gees(lambda x: None, a, overwrite_a=False)
+ assert_equal(result[-1], 0)
+
+ t = result[0]
+ z = result[-3]
+
+ d2 = t[6, 6]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+ result = trexc(t, z, 7, 1)
+ assert_equal(result[-1], 0)
+
+ t = result[0]
+ z = result[-2]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+ assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+ "t, expect, ifst, ilst",
+ [(np.array([[0.80, -0.11, 0.01, 0.03],
+ [0.00, -0.10, 0.25, 0.35],
+ [0.00, -0.65, -0.10, 0.20],
+ [0.00, 0.00, 0.00, -0.10]]),
+ np.array([[-0.1000, -0.6463, 0.0874, 0.2010],
+ [0.2514, -0.1000, 0.0927, 0.3505],
+ [0.0000, 0.0000, 0.8000, -0.0117],
+ [0.0000, 0.0000, 0.0000, -0.1000]]),
+ 2, 1),
+ (np.array([[-6.00 - 7.00j, 0.36 - 0.36j, -0.19 + 0.48j, 0.88 - 0.25j],
+ [0.00 + 0.00j, -5.00 + 2.00j, -0.03 - 0.72j, -0.23 + 0.13j],
+ [0.00 + 0.00j, 0.00 + 0.00j, 8.00 - 1.00j, 0.94 + 0.53j],
+ [0.00 + 0.00j, 0.00 + 0.00j, 0.00 + 0.00j, 3.00 - 4.00j]]),
+ np.array([[-5.0000 + 2.0000j, -0.1574 + 0.7143j,
+ 0.1781 - 0.1913j, 0.3950 + 0.3861j],
+ [0.0000 + 0.0000j, 8.0000 - 1.0000j,
+ 1.0742 + 0.1447j, 0.2515 - 0.3397j],
+ [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+ 3.0000 - 4.0000j, 0.2264 + 0.8962j],
+ [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+ 0.0000 + 0.0000j, -6.0000 - 7.0000j]]),
+ 1, 4)])
+def test_trexc_NAG(t, ifst, ilst, expect):
+ """
+ This test implements the example found in the NAG manual,
+ f08qfc, f08qtc, f08qgc, f08quc.
+ """
+ # NAG manual provides accuracy up to 4 decimals
+ atol = 1e-4
+ trexc = get_lapack_funcs('trexc', dtype=t.dtype)
+
+ result = trexc(t, t, ifst, ilst, wantq=0)
+ assert_equal(result[-1], 0)
+
+ t = result[0]
+ assert_allclose(expect, t, atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gges_tgexc(dtype):
+ rng = np.random.RandomState(1234)
+ atol = np.finfo(dtype).eps*100
+
+ n = 10
+ a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+ b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+ gges, tgexc = get_lapack_funcs(('gges', 'tgexc'), dtype=dtype)
+
+ result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
+ assert_equal(result[-1], 0)
+
+ s = result[0]
+ t = result[1]
+ q = result[-4]
+ z = result[-3]
+
+ d1 = s[0, 0] / t[0, 0]
+ d2 = s[6, 6] / t[6, 6]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+ assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+ result = tgexc(s, t, q, z, 7, 1)
+ assert_equal(result[-1], 0)
+
+ s = result[0]
+ t = result[1]
+ q = result[2]
+ z = result[3]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+ assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+ assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
+ assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gees_trsen(dtype):
+ rng = np.random.RandomState(1234)
+ atol = np.finfo(dtype).eps*100
+
+ n = 10
+ a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+ gees, trsen, trsen_lwork = get_lapack_funcs(
+ ('gees', 'trsen', 'trsen_lwork'), dtype=dtype)
+
+ result = gees(lambda x: None, a, overwrite_a=False)
+ assert_equal(result[-1], 0)
+
+ t = result[0]
+ z = result[-3]
+
+ d2 = t[6, 6]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+ select = np.zeros(n)
+ select[6] = 1
+
+ lwork = _compute_lwork(trsen_lwork, select, t)
+
+ if dtype in COMPLEX_DTYPES:
+ result = trsen(select, t, z, lwork=lwork)
+ else:
+ result = trsen(select, t, z, lwork=lwork, liwork=lwork[1])
+ assert_equal(result[-1], 0)
+
+ t = result[0]
+ z = result[1]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+ assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+ "t, q, expect, select, expect_s, expect_sep",
+ [(np.array([[0.7995, -0.1144, 0.0060, 0.0336],
+ [0.0000, -0.0994, 0.2478, 0.3474],
+ [0.0000, -0.6483, -0.0994, 0.2026],
+ [0.0000, 0.0000, 0.0000, -0.1007]]),
+ np.array([[0.6551, 0.1037, 0.3450, 0.6641],
+ [0.5236, -0.5807, -0.6141, -0.1068],
+ [-0.5362, -0.3073, -0.2935, 0.7293],
+ [0.0956, 0.7467, -0.6463, 0.1249]]),
+ np.array([[0.3500, 0.4500, -0.1400, -0.1700],
+ [0.0900, 0.0700, -0.5399, 0.3500],
+ [-0.4400, -0.3300, -0.0300, 0.1700],
+ [0.2500, -0.3200, -0.1300, 0.1100]]),
+ np.array([1, 0, 0, 1]),
+ 1.75e+00, 3.22e+00),
+ (np.array([[-6.0004 - 6.9999j, 0.3637 - 0.3656j,
+ -0.1880 + 0.4787j, 0.8785 - 0.2539j],
+ [0.0000 + 0.0000j, -5.0000 + 2.0060j,
+ -0.0307 - 0.7217j, -0.2290 + 0.1313j],
+ [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+ 7.9982 - 0.9964j, 0.9357 + 0.5359j],
+ [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+ 0.0000 + 0.0000j, 3.0023 - 3.9998j]]),
+ np.array([[-0.8347 - 0.1364j, -0.0628 + 0.3806j,
+ 0.2765 - 0.0846j, 0.0633 - 0.2199j],
+ [0.0664 - 0.2968j, 0.2365 + 0.5240j,
+ -0.5877 - 0.4208j, 0.0835 + 0.2183j],
+ [-0.0362 - 0.3215j, 0.3143 - 0.5473j,
+ 0.0576 - 0.5736j, 0.0057 - 0.4058j],
+ [0.0086 + 0.2958j, -0.3416 - 0.0757j,
+ -0.1900 - 0.1600j, 0.8327 - 0.1868j]]),
+ np.array([[-3.9702 - 5.0406j, -4.1108 + 3.7002j,
+ -0.3403 + 1.0098j, 1.2899 - 0.8590j],
+ [0.3397 - 1.5006j, 1.5201 - 0.4301j,
+ 1.8797 - 5.3804j, 3.3606 + 0.6498j],
+ [3.3101 - 3.8506j, 2.4996 + 3.4504j,
+ 0.8802 - 1.0802j, 0.6401 - 1.4800j],
+ [-1.0999 + 0.8199j, 1.8103 - 1.5905j,
+ 3.2502 + 1.3297j, 1.5701 - 3.4397j]]),
+ np.array([1, 0, 0, 1]),
+ 1.02e+00, 1.82e-01)])
+def test_trsen_NAG(t, q, select, expect, expect_s, expect_sep):
+ """
+ This test implements the example found in the NAG manual,
+ f08qgc, f08quc.
+ """
+ # NAG manual provides accuracy up to 4 and 2 decimals
+ atol = 1e-4
+ atol2 = 1e-2
+ trsen, trsen_lwork = get_lapack_funcs(
+ ('trsen', 'trsen_lwork'), dtype=t.dtype)
+
+ lwork = _compute_lwork(trsen_lwork, select, t)
+
+ if t.dtype in COMPLEX_DTYPES:
+ result = trsen(select, t, q, lwork=lwork)
+ else:
+ result = trsen(select, t, q, lwork=lwork, liwork=lwork[1])
+ assert_equal(result[-1], 0)
+
+ t = result[0]
+ q = result[1]
+ if t.dtype in COMPLEX_DTYPES:
+ s = result[4]
+ sep = result[5]
+ else:
+ s = result[5]
+ sep = result[6]
+
+ assert_allclose(expect, q @ t @ q.conj().T, atol=atol)
+ assert_allclose(expect_s, 1 / s, atol=atol2)
+ assert_allclose(expect_sep, 1 / sep, atol=atol2)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gges_tgsen(dtype):
+ rng = np.random.RandomState(1234)
+ atol = np.finfo(dtype).eps*100
+
+ n = 10
+ a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+ b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+ gges, tgsen, tgsen_lwork = get_lapack_funcs(
+ ('gges', 'tgsen', 'tgsen_lwork'), dtype=dtype)
+
+ result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
+ assert_equal(result[-1], 0)
+
+ s = result[0]
+ t = result[1]
+ q = result[-4]
+ z = result[-3]
+
+ d1 = s[0, 0] / t[0, 0]
+ d2 = s[6, 6] / t[6, 6]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+ assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+ select = np.zeros(n)
+ select[6] = 1
+
+ lwork = _compute_lwork(tgsen_lwork, select, s, t)
+
+ # off-by-one error in LAPACK, see gh-issue #13397
+ lwork = (lwork[0]+1, lwork[1])
+
+ result = tgsen(select, s, t, q, z, lwork=lwork)
+ assert_equal(result[-1], 0)
+
+ s = result[0]
+ t = result[1]
+ q = result[-7]
+ z = result[-6]
+
+ if dtype in COMPLEX_DTYPES:
+ assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+ assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+ assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+ assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+ assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
+ assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+ "a, b, c, d, e, f, rans, lans",
+ [(np.array([[4.0, 1.0, 1.0, 2.0],
+ [0.0, 3.0, 4.0, 1.0],
+ [0.0, 1.0, 3.0, 1.0],
+ [0.0, 0.0, 0.0, 6.0]]),
+ np.array([[1.0, 1.0, 1.0, 1.0],
+ [0.0, 3.0, 4.0, 1.0],
+ [0.0, 1.0, 3.0, 1.0],
+ [0.0, 0.0, 0.0, 4.0]]),
+ np.array([[-4.0, 7.0, 1.0, 12.0],
+ [-9.0, 2.0, -2.0, -2.0],
+ [-4.0, 2.0, -2.0, 8.0],
+ [-7.0, 7.0, -6.0, 19.0]]),
+ np.array([[2.0, 1.0, 1.0, 3.0],
+ [0.0, 1.0, 2.0, 1.0],
+ [0.0, 0.0, 1.0, 1.0],
+ [0.0, 0.0, 0.0, 2.0]]),
+ np.array([[1.0, 1.0, 1.0, 2.0],
+ [0.0, 1.0, 4.0, 1.0],
+ [0.0, 0.0, 1.0, 1.0],
+ [0.0, 0.0, 0.0, 1.0]]),
+ np.array([[-7.0, 5.0, 0.0, 7.0],
+ [-5.0, 1.0, -8.0, 0.0],
+ [-1.0, 2.0, -3.0, 5.0],
+ [-3.0, 2.0, 0.0, 5.0]]),
+ np.array([[1.0, 1.0, 1.0, 1.0],
+ [-1.0, 2.0, -1.0, -1.0],
+ [-1.0, 1.0, 3.0, 1.0],
+ [-1.0, 1.0, -1.0, 4.0]]),
+ np.array([[4.0, -1.0, 1.0, -1.0],
+ [1.0, 3.0, -1.0, 1.0],
+ [-1.0, 1.0, 2.0, -1.0],
+ [1.0, -1.0, 1.0, 1.0]]))])
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+def test_tgsyl_NAG(a, b, c, d, e, f, rans, lans, dtype):
+ atol = 1e-4
+
+ tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
+ rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f)
+
+ assert_equal(info, 0)
+ assert_allclose(scale, 1.0, rtol=0, atol=np.finfo(dtype).eps*100,
+ err_msg="SCALE must be 1.0")
+ assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
+ err_msg="DIF must be nearly 0")
+ assert_allclose(rout, rans, atol=atol,
+ err_msg="Solution for R is incorrect")
+ assert_allclose(lout, lans, atol=atol,
+ err_msg="Solution for L is incorrect")
+
+
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+@pytest.mark.parametrize('trans', ('N', 'T'))
+@pytest.mark.parametrize('ijob', [0, 1, 2, 3, 4])
+def test_tgsyl(dtype, trans, ijob):
+
+ atol = 1e-3 if dtype == np.float32 else 1e-10
+ rng = np.random.default_rng(1685779866898198)
+ m, n = 10, 15
+
+ a, d, *_ = qz(rng.uniform(-10, 10, [m, m]).astype(dtype),
+ rng.uniform(-10, 10, [m, m]).astype(dtype),
+ output='real')
+
+ b, e, *_ = qz(rng.uniform(-10, 10, [n, n]).astype(dtype),
+ rng.uniform(-10, 10, [n, n]).astype(dtype),
+ output='real')
+
+ c = rng.uniform(-2, 2, [m, n]).astype(dtype)
+ f = rng.uniform(-2, 2, [m, n]).astype(dtype)
+
+ tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
+ rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f,
+ trans=trans, ijob=ijob)
+
+ assert info == 0, "INFO is non-zero"
+ assert scale >= 0.0, "SCALE must be non-negative"
+ if ijob == 0:
+ assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
+ err_msg="DIF must be 0 for ijob =0")
+ else:
+ assert dif >= 0.0, "DIF must be non-negative"
+
+ # Only DIF is calculated for ijob = 3/4
+ if ijob <= 2:
+ if trans == 'N':
+ lhs1 = a @ rout - lout @ b
+ rhs1 = scale*c
+ lhs2 = d @ rout - lout @ e
+ rhs2 = scale*f
+ elif trans == 'T':
+ lhs1 = np.transpose(a) @ rout + np.transpose(d) @ lout
+ rhs1 = scale*c
+ lhs2 = rout @ np.transpose(b) + lout @ np.transpose(e)
+ rhs2 = -1.0*scale*f
+
+ assert_allclose(lhs1, rhs1, atol=atol, rtol=0.,
+ err_msg='lhs1 and rhs1 do not match')
+ assert_allclose(lhs2, rhs2, atol=atol, rtol=0.,
+ err_msg='lhs2 and rhs2 do not match')
+
+
+@pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('lower', (0, 1))
+def test_sy_hetrs(mtype, dtype, lower):
+ if mtype == 'he' and dtype in REAL_DTYPES:
+ pytest.skip("hetrs not for real dtypes.")
+ rng = np.random.default_rng(1723059677121834)
+ n, nrhs = 20, 5
+ if dtype in COMPLEX_DTYPES:
+ A = (rng.uniform(size=(n, n)) + rng.uniform(size=(n, n))*1j).astype(dtype)
+ else:
+ A = rng.uniform(size=(n, n)).astype(dtype)
+
+ A = A + A.T if mtype == 'sy' else A + A.conj().T
+ b = rng.uniform(size=(n, nrhs)).astype(dtype)
+ names = f'{mtype}trf', f'{mtype}trf_lwork', f'{mtype}trs'
+ trf, trf_lwork, trs = get_lapack_funcs(names, dtype=dtype)
+ lwork = trf_lwork(n, lower=lower)
+ ldu, ipiv, info = trf(A, lwork=lwork, lower=lower)
+ assert info == 0
+ x, info = trs(a=ldu, ipiv=ipiv, b=b, lower=lower)
+ assert info == 0
+ eps = np.finfo(dtype).eps
+ assert_allclose(A@x, b, atol=100*n*eps)
+
+
+@pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('lower', (0, 1))
+def test_sy_he_tri(dtype, lower, mtype):
+ if mtype == 'he' and dtype in REAL_DTYPES:
+ pytest.skip("hetri not for real dtypes.")
+ if sysconfig.get_platform() == 'win-arm64' and dtype in COMPLEX_DTYPES:
+ pytest.skip("Test segfaulting on win-arm64 in CI, see gh-23133")
+
+ rng = np.random.default_rng(1723059677121834)
+ n = 20
+ A = rng.random((n, n)) + rng.random((n, n))*1j
+ if np.issubdtype(dtype, np.floating):
+ A = A.real
+ A = A.astype(dtype)
+ A = A + A.T if mtype == 'sy' else A + A.conj().T
+ names = f'{mtype}trf', f'{mtype}tri'
+ trf, tri = get_lapack_funcs(names, dtype=dtype)
+ ldu, ipiv, info = trf(A, lower=lower)
+ assert info == 0
+ A_inv, info = tri(a=ldu, ipiv=ipiv, lower=lower)
+ assert info == 0
+ eps = np.finfo(dtype).eps
+ ref = np.linalg.inv(A)
+ if lower:
+ assert_allclose(np.tril(A_inv), np.tril(ref), atol=100*n*eps)
+ else:
+ assert_allclose(np.triu(A_inv), np.triu(ref), atol=100*n*eps)
+
+
+@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe'))
+@pytest.mark.parametrize('uplo, m, n', [('U', 5, 10), ('U', 10, 10),
+ ('L', 10, 5), ('L', 10, 10)])
+@pytest.mark.parametrize('diag', ['N', 'U'])
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_lantr(norm, uplo, m, n, diag, dtype):
+ rng = np.random.default_rng(98426598246982456)
+ A = rng.random(size=(m, n)).astype(dtype)
+ lantr, lange = get_lapack_funcs(('lantr', 'lange'), (A,))
+ res = lantr(norm, A, uplo=uplo, diag=diag)
+
+ # now modify the matrix according to assumptions made by `lantr`
+ A = np.triu(A) if uplo == 'U' else np.tril(A)
+ if diag == 'U':
+ i = np.arange(min(m, n))
+ A[i, i] = 1
+ ref = lange(norm, A)
+
+ assert_allclose(res, ref, rtol=2e-6)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('norm', ['1', 'I', 'O'])
+def test_gbcon(dtype, norm):
+ rng = np.random.default_rng(17273783424)
+
+ # A is of shape n x n with ku/kl super/sub-diagonals
+ n, ku, kl = 10, 2, 2
+ A = rng.random((n, n)) + rng.random((n, n))*1j
+ # make the condition numbers more interesting
+ offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n))
+ A += offset
+ if np.issubdtype(dtype, np.floating):
+ A = A.real
+ A = A.astype(dtype)
+ A[np.triu_indices(n, ku + 1)] = 0
+ A[np.tril_indices(n, -kl - 1)] = 0
+
+ # construct banded form
+ tmp = _to_banded(kl, ku, A)
+ # add rows required by ?gbtrf
+ LDAB = 2*kl + ku + 1
+ ab = np.zeros((LDAB, n), dtype=dtype)
+ ab[kl:, :] = tmp
+
+ anorm = np.linalg.norm(A, ord=np.inf if norm == 'I' else 1)
+ gbcon, gbtrf = get_lapack_funcs(("gbcon", "gbtrf"), (ab,))
+ lu_band, ipiv, _ = gbtrf(ab, kl, ku)
+ res = gbcon(norm=norm, kl=kl, ku=ku, ab=lu_band, ipiv=ipiv,
+ anorm=anorm)[0]
+
+ gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
+ lu = getrf(A)[0]
+ ref = gecon(lu, anorm, norm=norm)[0]
+ # This is an estimate of reciprocal condition number; we just need order of
+ # magnitude.
+ assert_allclose(res, ref, rtol=1)
+
+
+@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe'))
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_langb(dtype, norm):
+ rng = np.random.default_rng(17273783424)
+
+ # A is of shape n x n with ku/kl super/sub-diagonals
+ n, ku, kl = 10, 2, 2
+ A = rng.random((n, n)) + rng.random((n, n))*1j
+ if np.issubdtype(dtype, np.floating):
+ A = A.real
+ A = A.astype(dtype)
+ A[np.triu_indices(n, ku + 1)] = 0
+ A[np.tril_indices(n, -kl - 1)] = 0
+ ab = _to_banded(kl, ku, A)
+
+ langb, lange = get_lapack_funcs(('langb', 'lange'), (A,))
+ ref = lange(norm, A)
+ res = langb(norm, kl, ku, ab)
+ assert_allclose(res, ref, rtol=2e-6)
+
+
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+@pytest.mark.parametrize('compute_v', (0, 1))
+def test_stevd(dtype, compute_v):
+ rng = np.random.default_rng(266474747488348746)
+ n = 10
+ d = rng.random(n, dtype=dtype)
+ e = rng.random(n - 1, dtype=dtype)
+ A = np.diag(e, -1) + np.diag(d) + np.diag(e, 1)
+ ref = np.linalg.eigvalsh(A)
+
+ stevd = get_lapack_funcs('stevd')
+ U, V, info = stevd(d, e, compute_v=compute_v)
+ assert info == 0
+ assert_allclose(np.sort(U), np.sort(ref))
+ if compute_v:
+ eps = np.finfo(dtype).eps
+ assert_allclose(V @ np.diag(U) @ V.T, A, atol=eps**0.8)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matfuncs.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..42541eed2cf56e3a0469813efaba43c7f436d388
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matfuncs.py
@@ -0,0 +1,1149 @@
+#
+# Created by: Pearu Peterson, March 2002
+#
+""" Test functions for linalg.matfuncs module
+
+"""
+import functools
+import pytest
+import warnings
+
+import numpy as np
+from numpy import array, identity, sqrt
+from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_,
+ assert_array_less, assert_array_equal)
+
+import scipy.linalg
+from scipy.linalg import (funm, signm, logm, sqrtm, fractional_matrix_power,
+ expm, expm_frechet, expm_cond, norm, khatri_rao,
+ cosm, sinm, tanm, coshm, sinhm, tanhm)
+
+from scipy.linalg import _matfuncs_inv_ssq
+from scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarning
+import scipy.linalg._expm_frechet
+from scipy.linalg import LinAlgWarning
+from scipy.optimize import minimize
+
+
+def _get_al_mohy_higham_2012_experiment_1():
+ """
+ Return the test matrix from Experiment (1) of [1]_.
+
+ References
+ ----------
+ .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+ "Improved Inverse Scaling and Squaring Algorithms
+ for the Matrix Logarithm."
+ SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+ ISSN 1095-7197
+
+ """
+ A = np.array([
+ [3.2346e-1, 3e4, 3e4, 3e4],
+ [0, 3.0089e-1, 3e4, 3e4],
+ [0, 0, 3.2210e-1, 3e4],
+ [0, 0, 0, 3.0744e-1]], dtype=float)
+ return A
+
+
+class TestSignM:
+
+ def test_nils(self):
+ a = array([[29.2, -24.2, 69.5, 49.8, 7.],
+ [-9.2, 5.2, -18., -16.8, -2.],
+ [-10., 6., -20., -18., -2.],
+ [-9.6, 9.6, -25.5, -15.4, -2.],
+ [9.8, -4.8, 18., 18.2, 2.]])
+ cr = array([[11.94933333,-2.24533333,15.31733333,21.65333333,-2.24533333],
+ [-3.84266667,0.49866667,-4.59066667,-7.18666667,0.49866667],
+ [-4.08,0.56,-4.92,-7.6,0.56],
+ [-4.03466667,1.04266667,-5.59866667,-7.02666667,1.04266667],
+ [4.15733333,-0.50133333,4.90933333,7.81333333,-0.50133333]])
+ r = signm(a)
+ assert_array_almost_equal(r,cr)
+
+ def test_defective1(self):
+ a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]])
+ signm(a)
+ #XXX: what would be the correct result?
+
+ def test_defective2(self):
+ a = array((
+ [29.2,-24.2,69.5,49.8,7.0],
+ [-9.2,5.2,-18.0,-16.8,-2.0],
+ [-10.0,6.0,-20.0,-18.0,-2.0],
+ [-9.6,9.6,-25.5,-15.4,-2.0],
+ [9.8,-4.8,18.0,18.2,2.0]))
+ signm(a)
+ #XXX: what would be the correct result?
+
+ def test_defective3(self):
+ a = array([[-2., 25., 0., 0., 0., 0., 0.],
+ [0., -3., 10., 3., 3., 3., 0.],
+ [0., 0., 2., 15., 3., 3., 0.],
+ [0., 0., 0., 0., 15., 3., 0.],
+ [0., 0., 0., 0., 3., 10., 0.],
+ [0., 0., 0., 0., 0., -2., 25.],
+ [0., 0., 0., 0., 0., 0., -3.]])
+ signm(a)
+ #XXX: what would be the correct result?
+
+ @pytest.mark.parametrize('dtype', [np.float32, np.float64,
+ np.complex64, np.complex128])
+ def test_signm_dtype_preservation(self, dtype):
+ # gh-25657: signm upcast float32/complex64 for defective matrices
+ # (the iterative fall-through branch) while the non-defective branch
+ # preserved dtype. Output dtype must depend on input dtype, not values.
+ non_defective = np.array([[2, 1], [0, 3]], dtype=dtype) # distinct eigs
+ defective = np.array([[2, 1], [0, 2]], dtype=dtype) # repeated eig
+ assert signm(non_defective).dtype == dtype
+ assert signm(defective).dtype == dtype
+
+
+class TestLogM:
+ @pytest.mark.filterwarnings("ignore:.*inaccurate.*:RuntimeWarning")
+ def test_nils(self):
+ a = array([[-2., 25., 0., 0., 0., 0., 0.],
+ [0., -3., 10., 3., 3., 3., 0.],
+ [0., 0., 2., 15., 3., 3., 0.],
+ [0., 0., 0., 0., 15., 3., 0.],
+ [0., 0., 0., 0., 3., 10., 0.],
+ [0., 0., 0., 0., 0., -2., 25.],
+ [0., 0., 0., 0., 0., 0., -3.]])
+ m = (identity(7)*3.1+0j)-a
+ logm(m)
+ #XXX: what would be the correct result?
+
+ @pytest.mark.filterwarnings("ignore:.*inaccurate.*:RuntimeWarning")
+ def test_al_mohy_higham_2012_experiment_1_logm(self):
+ # The logm completes the round trip successfully.
+ # Note that the expm leg of the round trip is badly conditioned.
+ A = _get_al_mohy_higham_2012_experiment_1()
+ A_logm = logm(A)
+ A_round_trip = expm(A_logm)
+ assert_allclose(A_round_trip, A, rtol=5e-5, atol=1e-14)
+
+ def test_al_mohy_higham_2012_experiment_1_funm_log(self):
+ # The raw funm with np.log does not complete the round trip.
+ # Note that the expm leg of the round trip is badly conditioned.
+ A = _get_al_mohy_higham_2012_experiment_1()
+ A_funm_log = funm(A, np.log)
+ A_round_trip = expm(A_funm_log)
+ assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14))
+
+ def test_round_trip_random_float(self):
+ rng = np.random.default_rng(1738098768840254)
+ for n in range(1, 6):
+ M_unscaled = rng.uniform(size=(n, n))
+ for scale in np.logspace(-4, 4, 9):
+ M = M_unscaled * scale
+
+ # Eigenvalues are related to the branch cut.
+ W = np.linalg.eigvals(M)
+ err_msg = f'M:{M} eivals:{W}'
+
+ # Check sqrtm round trip because it is used within logm.
+ M_sqrtm = sqrtm(M)
+ M_sqrtm_round_trip = M_sqrtm @ M_sqrtm
+ assert_allclose(M_sqrtm_round_trip, M)
+
+ # Check logm round trip.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", RuntimeWarning)
+
+ M_logm = logm(M)
+ M_logm_round_trip = expm(M_logm)
+ assert_allclose(M_logm_round_trip, M, err_msg=err_msg)
+
+ def test_round_trip_random_complex(self):
+ rng = np.random.default_rng(1738098768840254)
+ for n in range(1, 6):
+ M_unscaled = (rng.standard_normal((n, n)) +
+ 1j*rng.standard_normal((n, n)))
+ for scale in np.logspace(-4, 4, 9):
+ M = M_unscaled * scale
+ M_logm = logm(M)
+ M_round_trip = expm(M_logm)
+ assert_allclose(M_round_trip, M)
+
+ def test_logm_type_preservation_and_conversion(self):
+ # The logm matrix function should preserve the type of a matrix
+ # whose eigenvalues are positive with zero imaginary part.
+ # Test this preservation for variously structured matrices.
+ complex_dtype_chars = ('F', 'D', 'G')
+ for matrix_as_list in (
+ [[1, 0], [0, 1]],
+ [[1, 0], [1, 1]],
+ [[2, 1], [1, 1]],
+ [[2, 3], [1, 2]]):
+
+ # check that the spectrum has the expected properties
+ W = scipy.linalg.eigvals(matrix_as_list)
+ assert_(not any(w.imag or w.real < 0 for w in W))
+
+ # check float type preservation
+ A = np.array(matrix_as_list, dtype=float)
+ A_logm = logm(A)
+ assert_(A_logm.dtype.char not in complex_dtype_chars)
+
+ # check complex type preservation
+ A = np.array(matrix_as_list, dtype=complex)
+ A_logm = logm(A)
+ assert_(A_logm.dtype.char in complex_dtype_chars)
+
+ # check float->complex type conversion for the matrix negation
+ A = -np.array(matrix_as_list, dtype=float)
+ A_logm = logm(A)
+ assert_(A_logm.dtype.char in complex_dtype_chars)
+
+ def test_complex_spectrum_real_logm(self):
+ # This matrix has complex eigenvalues and real logm.
+ # Its output dtype depends on its input dtype.
+ M = [[1, 1, 2], [2, 1, 1], [1, 2, 1]]
+ for dt in float, complex:
+ X = np.array(M, dtype=dt)
+ w = scipy.linalg.eigvals(X)
+ assert_(1e-2 < np.absolute(w.imag).sum())
+ Y = logm(X)
+ assert_(np.issubdtype(Y.dtype, np.inexact))
+ assert_allclose(expm(Y), X)
+
+ def test_real_mixed_sign_spectrum(self):
+ # These matrices have real eigenvalues with mixed signs.
+ # The output logm dtype is complex, regardless of input dtype.
+ for M in (
+ [[1, 0], [0, -1]],
+ [[0, 1], [1, 0]]):
+ for dt in float, complex:
+ A = np.array(M, dtype=dt)
+ A_logm, info = logm(A)
+ assert_(np.issubdtype(A_logm.dtype, np.complexfloating))
+
+ def test_exactly_singular(self):
+ A = np.array([[0, 0], [1j, 1j]])
+ B = np.asarray([[1, 1], [0, 0]])
+ for M in A, A.T, B, B.T:
+ with pytest.warns(_matfuncs_inv_ssq.LogmExactlySingularWarning):
+ L = logm(M)
+ E = expm(L)
+ assert_allclose(E, M, atol=1e-14)
+
+ def test_nearly_singular(self):
+ M = np.array([[1e-100]])
+ with pytest.warns(_matfuncs_inv_ssq.LogmNearlySingularWarning):
+ L = logm(M)
+ E = expm(L)
+ assert_allclose(E, M, atol=1e-14)
+
+ def test_opposite_sign_complex_eigenvalues(self):
+ # See gh-6113
+ E = [[0, 1], [-1, 0]]
+ L = [[0, np.pi*0.5], [-np.pi*0.5, 0]]
+ assert_allclose(expm(L), E, atol=1e-14)
+ assert_allclose(logm(E), L, atol=1e-14)
+ E = [[1j, 4], [0, -1j]]
+ L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]]
+ assert_allclose(expm(L), E, atol=1e-14)
+ assert_allclose(logm(E), L, atol=1e-14)
+ E = [[1j, 0], [0, -1j]]
+ L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]]
+ assert_allclose(expm(L), E, atol=1e-14)
+ assert_allclose(logm(E), L, atol=1e-14)
+
+ def test_readonly(self):
+ n = 5
+ a = np.ones((n, n)) + np.identity(n)
+ a.flags.writeable = False
+ logm(a)
+
+ @pytest.mark.xfail(reason="ValueError: attempt to get argmax of an empty sequence")
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ log_a = logm(a)
+ a0 = np.eye(2, dtype=dt)
+ log_a0 = logm(a0)
+
+ assert log_a.shape == (0, 0)
+ assert log_a.dtype == log_a0.dtype
+
+ @pytest.mark.parametrize('dtype', [int, float, np.float32, complex, np.complex64])
+ def test_no_ZeroDivisionError(self, dtype):
+ # gh-17136 reported inconsistent behavior in `logm` depending on input dtype:
+ # sometimes it raised an error, and sometimes it printed a warning message.
+ # check that this is resolved and that the warning is emitted properly.
+ with (pytest.warns(RuntimeWarning, match="logm result may be inaccurate"),
+ pytest.warns(LogmExactlySingularWarning)):
+ logm(np.zeros((2, 2), dtype=dtype))
+
+
+class TestSqrtM:
+
+ def test_round_trip_random_float(self):
+ rng = np.random.default_rng(1738151906092735)
+ for n in range(1, 6):
+ M_unscaled = rng.standard_normal((n, n))
+ for scale in np.logspace(-4, 4, 9):
+ M = M_unscaled * scale
+ M_sqrtm = sqrtm(M)
+ M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+ assert_allclose(M_sqrtm_round_trip, M)
+
+ def test_round_trip_random_complex(self):
+ rng = np.random.default_rng(1738151906092736)
+ for n in range(1, 6):
+ M_unscaled = (rng.standard_normal((n, n)) +
+ 1j * rng.standard_normal((n, n)))
+ for scale in np.logspace(-4, 4, 9):
+ M = M_unscaled * scale
+ M_sqrtm = sqrtm(M)
+ M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+ assert_allclose(M_sqrtm_round_trip, M)
+
+ def test_bad(self):
+ # See https://web.archive.org/web/20051220232650/http://www.maths.man.ac.uk/~nareports/narep336.ps.gz
+ e = 2**-5
+ se = sqrt(e)
+ a = array([[1.0,0,0,1],
+ [0,e,0,0],
+ [0,0,e,0],
+ [0,0,0,1]])
+ sa = array([[1,0,0,0.5],
+ [0,se,0,0],
+ [0,0,se,0],
+ [0,0,0,1]])
+ assert_array_almost_equal(sa @ sa, a)
+ # Check default sqrtm.
+ esa = sqrtm(a)
+ assert_array_almost_equal(esa @ esa, a)
+
+ def test_sqrtm_type_preservation_and_conversion(self):
+ # The sqrtm matrix function should preserve the type of a matrix
+ # whose eigenvalues are nonnegative with zero imaginary part.
+ # Test this preservation for variously structured matrices.
+ complex_dtype_chars = ('F', 'D', 'G')
+ for matrix_as_list in (
+ [[1, 0], [0, 1]],
+ [[1, 0], [1, 1]],
+ [[2, 1], [1, 1]],
+ [[2, 3], [1, 2]],
+ [[1, 1], [1, 1]]):
+
+ # check that the spectrum has the expected properties
+ W = scipy.linalg.eigvals(matrix_as_list)
+ assert_(not any(w.imag or w.real < 0 for w in W))
+
+ # Last test matrix is singular so suppress the warning
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LinAlgWarning)
+
+ # check float type preservation
+ A = np.array(matrix_as_list, dtype=float)
+ A_sqrtm = sqrtm(A)
+ assert_(A_sqrtm.dtype.char not in complex_dtype_chars)
+
+ # check complex type preservation
+ A = np.array(matrix_as_list, dtype=complex)
+ A_sqrtm = sqrtm(A)
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+ # check float->complex type conversion for the matrix negation
+ A = -np.array(matrix_as_list, dtype=float)
+ A_sqrtm = sqrtm(A)
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+ def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self):
+ complex_dtype_chars = ('F', 'D', 'G')
+ for matrix_as_list in (
+ [[1, 0], [0, -1]],
+ [[0, 1], [1, 0]],
+ [[0, 1, 0], [0, 0, -1], [1, 0, 0]]):
+
+ # check that the spectrum has the expected properties
+ W = scipy.linalg.eigvals(matrix_as_list)
+ assert_(any(w.imag or w.real < 0 for w in W))
+
+ # check complex->complex
+ A = np.array(matrix_as_list, dtype=complex)
+ A_sqrtm = sqrtm(A)
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+ # check float->complex
+ A = np.array(matrix_as_list, dtype=float)
+ A_sqrtm = sqrtm(A)
+ assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+ def test_al_mohy_higham_2012_experiment_1(self):
+ # Matrix square root of a tricky upper triangular matrix.
+ A = _get_al_mohy_higham_2012_experiment_1()
+ A_sqrtm = sqrtm(A)
+ A_round_trip = A_sqrtm @ A_sqrtm
+ assert_allclose(A_round_trip, A, rtol=1e-5)
+ assert_allclose(np.tril(A_round_trip), np.tril(A))
+
+ def test_strict_upper_triangular(self):
+ # This matrix has no square root but upper triangular hence upper
+ # triangle will be filled with junk values.
+ for dt in int, float:
+ A = np.array([
+ [0, 3, 0, 0],
+ [0, 0, 3, 0],
+ [0, 0, 0, 3],
+ [0, 0, 0, 0]], dtype=dt)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LinAlgWarning)
+
+ A_sqrtm = sqrtm(A)
+ assert_allclose(np.tril(A_sqrtm), np.zeros((4, 4)))
+ assert np.isnan(A_sqrtm).any()
+ assert np.isinf(A_sqrtm).any()
+
+ # Future edit: This squareroot is not possible to find algorithmically
+ # with the current methods. Now sqrtm docstring has another example of
+ # such matrix whose squareroot is not a polynomial in it. Hence no need
+ # to test it here.
+ """
+ def test_weird_matrix(self):
+ # The square root of matrix B exists.
+ for dt in int, float:
+ A = np.array([
+ [0, 0, 1],
+ [0, 0, 0],
+ [0, 1, 0]], dtype=dt)
+ B = np.array([
+ [0, 1, 0],
+ [0, 0, 0],
+ [0, 0, 0]], dtype=dt)
+ assert_array_equal(B, A @ A)
+
+ # But scipy sqrtm is not clever enough to find it.
+ B_sqrtm, info = sqrtm(B, disp=False)
+ assert_(np.isnan(B_sqrtm).all())
+ """
+
+ def test_opposite_sign_complex_eigenvalues(self):
+ M = [[2j, 4], [0, -2j]]
+ R = [[1+1j, 2], [0, 1-1j]]
+ assert_allclose(np.dot(R, R), M, atol=1e-14)
+ assert_allclose(sqrtm(M), R, atol=1e-14)
+
+ def test_gh4866(self):
+ M = np.array([[1, 0, 0, 1],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [1, 0, 0, 1]])
+ R = np.array([[sqrt(0.5), 0, 0, sqrt(0.5)],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [sqrt(0.5), 0, 0, sqrt(0.5)]])
+ assert_allclose(R @ R, M, atol=1e-14)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LinAlgWarning)
+
+ assert_allclose(sqrtm(M), R, atol=1e-14)
+
+ def test_gh5336(self):
+ M = np.diag([2, 1, 0])
+ R = np.diag([sqrt(2), 1, 0])
+ assert_allclose(R @ R, M, atol=1e-14)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=LinAlgWarning)
+ assert_allclose(sqrtm(M), R, atol=1e-14)
+
+ def test_gh7839(self):
+ M = np.zeros((2, 2))
+ R = np.zeros((2, 2))
+ # Catch and silence LinAlgWarning
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=LinAlgWarning)
+
+ assert_allclose(sqrtm(M), R, atol=1e-14)
+
+ def test_gh17918(self):
+ M = np.empty((19, 19))
+ M.fill(0.94)
+ np.fill_diagonal(M, 1)
+ assert np.isrealobj(sqrtm(M))
+
+ def test_gh23278(self):
+ M = np.array([[1., 0., 0.], [0, 1, -1j], [0, 1j, 2]])
+ sq = sqrtm(M)
+ assert_allclose(sq @ sq, M, atol=1e-14)
+ sq = sqrtm(M.astype(np.complex64))
+ assert_allclose(sq @ sq, M, atol=1e-6)
+
+ def test_data_size_preservation_uint_in_float_out(self):
+ M = np.eye(10, dtype=np.uint8)
+ assert sqrtm(M).dtype == np.float64
+ M = np.eye(10, dtype=np.uint16)
+ assert sqrtm(M).dtype == np.float64
+ M = np.eye(10, dtype=np.uint32)
+ assert sqrtm(M).dtype == np.float64
+ M = np.eye(10, dtype=np.uint64)
+ assert sqrtm(M).dtype == np.float64
+
+ def test_data_size_preservation_int_in_float_out(self):
+ M = np.eye(10, dtype=np.int8)
+ assert sqrtm(M).dtype == np.float64
+ M = np.eye(10, dtype=np.int16)
+ assert sqrtm(M).dtype == np.float64
+ M = np.eye(10, dtype=np.int32)
+ assert sqrtm(M).dtype == np.float64
+ M = np.eye(10, dtype=np.int64)
+ assert sqrtm(M).dtype == np.float64
+
+ def test_data_size_preservation_int_in_comp_out(self):
+ M = np.array([[2, 4], [0, -2]], dtype=np.int8)
+ assert sqrtm(M).dtype == np.complex128
+ M = np.array([[2, 4], [0, -2]], dtype=np.int16)
+ assert sqrtm(M).dtype == np.complex128
+ M = np.array([[2, 4], [0, -2]], dtype=np.int32)
+ assert sqrtm(M).dtype == np.complex128
+ M = np.array([[2, 4], [0, -2]], dtype=np.int64)
+ assert sqrtm(M).dtype == np.complex128
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_data_size_preservation_float_in_float_out(self):
+ M = np.eye(10, dtype=np.float16)
+ assert sqrtm(M).dtype == np.float32
+ M = np.eye(10, dtype=np.float32)
+ assert sqrtm(M).dtype == np.float32
+ M = np.eye(10, dtype=np.float64)
+ assert sqrtm(M).dtype == np.float64
+ if hasattr(np, 'float128'):
+ M = np.eye(10, dtype=np.float128)
+ assert sqrtm(M).dtype == np.float64
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_data_size_preservation_float_in_comp_out(self):
+ M = np.array([[2, 4], [0, -2]], dtype=np.float16)
+ assert sqrtm(M).dtype == np.complex64
+ M = np.array([[2, 4], [0, -2]], dtype=np.float32)
+ assert sqrtm(M).dtype == np.complex64
+ M = np.array([[2, 4], [0, -2]], dtype=np.float64)
+ assert sqrtm(M).dtype == np.complex128
+ if hasattr(np, 'float128') and hasattr(np, 'complex256'):
+ M = np.array([[2, 4], [0, -2]], dtype=np.float128)
+ assert sqrtm(M).dtype == np.complex128
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_data_size_preservation_comp_in_comp_out(self):
+ M = np.array([[2j, 4], [0, -2j]], dtype=np.complex64)
+ assert sqrtm(M).dtype == np.complex64
+ M = np.array([[2j, 4], [0, -2j]], dtype=np.complex128)
+ assert sqrtm(M).dtype == np.complex128
+ if hasattr(np, 'complex256'):
+ M = np.array([[2j, 4], [0, -2j]], dtype=np.complex256)
+ assert sqrtm(M).dtype == np.complex128
+
+ @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+ def test_empty(self, dt):
+ a = np.empty((0, 0), dtype=dt)
+ s = sqrtm(a)
+ a0 = np.eye(2, dtype=dt)
+ s0 = sqrtm(a0)
+
+ assert s.shape == (0, 0)
+ assert s.dtype == s0.dtype
+
+ def test_cf_noncontig_nd_inputs(self):
+ # Check that non-contiguous arrays are handled correctly.
+ # Generate an L, U pair for invertible random matrix.
+ rng = np.random.default_rng(1738151906092737)
+ n = 13
+ A = rng.uniform(size=(3, 2*n, 2*n))
+ L, U = np.tril(A, k=-1) + np.eye(2*n), np.triu(A)
+ A = L @ U
+ # Create strided views of 3D array.
+ A_noncontig_c = A[:, ::2, ::2]
+ A_noncontig_f = np.asfortranarray(A)[:, 1::2, 1::2]
+ assert_allclose(sqrtm(A[:, ::2, ::2]), sqrtm(A_noncontig_c))
+ assert_allclose(sqrtm(A[:, 1::2, 1::2]), sqrtm(A_noncontig_f))
+
+ def test_empty_sizes(self):
+ A = np.empty(shape=[4, 0, 5, 5], dtype=float)
+ assert_array_equal(sqrtm(A), A)
+
+ def test_negative_strides(self):
+ rng = np.random.default_rng(1738151906092738)
+ A = rng.uniform(size=(3, 5, 5))
+ A_negneg_orig = A[:, ::-1, ::-1]
+ A_negneg_copy = A[:, ::-1, ::-1].copy()
+ assert_allclose(sqrtm(A_negneg_orig), sqrtm(A_negneg_copy))
+
+ A_posneg_orig = A[:, :, ::-1]
+ A_posneg_copy = A[:, :, ::-1].copy()
+ assert_allclose(sqrtm(A_posneg_orig), sqrtm(A_posneg_copy))
+
+ A_negpos_orig = A[:, ::-1, :]
+ A_negpos_copy = A[:, ::-1, :].copy()
+ assert_allclose(sqrtm(A_negpos_orig), sqrtm(A_negpos_copy))
+
+ @pytest.mark.parametrize('dtyp', [np.float32, np.float64,
+ np.complex64, np.complex128])
+ def test_gh24508(self, dtyp):
+ # Check that sqrtm raises a warning when the input is singular
+ # And for this example, the top row is filled with infs.
+ a = np.array([[0, 2, 2], [0, 0, 0], [0, 0, 0]], dtype=dtyp)
+ with pytest.warns(LinAlgWarning, match="Matrix is singular."):
+ res = sqrtm(a)
+ assert np.isinf(res[0, 1:]).all()
+
+
+class TestFractionalMatrixPower:
+ def test_round_trip_random_complex(self):
+ rng = np.random.default_rng(1234)
+ for p in range(1, 5):
+ for n in range(1, 5):
+ M_unscaled = (rng.standard_normal((n, n)) +
+ 1j * rng.standard_normal((n, n)))
+ for scale in np.logspace(-4, 4, 9):
+ M = M_unscaled * scale
+ M_root = fractional_matrix_power(M, 1/p)
+ M_round_trip = np.linalg.matrix_power(M_root, p)
+ assert_allclose(M_round_trip, M)
+
+ def test_round_trip_random_float(self):
+ # This test is more annoying because it can hit the branch cut;
+ # this happens when the matrix has an eigenvalue
+ # with no imaginary component and with a real negative component,
+ # and it means that the principal branch does not exist.
+ rng = np.random.default_rng(1234)
+ for p in range(1, 5):
+ for n in range(1, 5):
+ M_unscaled = rng.standard_normal((n, n))
+ for scale in np.logspace(-4, 4, 9):
+ M = M_unscaled * scale
+ M_root = fractional_matrix_power(M, 1/p)
+ M_round_trip = np.linalg.matrix_power(M_root, p)
+ assert_allclose(M_round_trip, M)
+
+ def test_larger_abs_fractional_matrix_powers(self):
+ rng = np.random.default_rng(1234)
+ for n in (2, 3, 5):
+ for i in range(10):
+ M = rng.standard_normal((n, n)) + 1j * rng.standard_normal((n, n))
+ M_one_fifth = fractional_matrix_power(M, 0.2)
+ # Test the round trip.
+ M_round_trip = np.linalg.matrix_power(M_one_fifth, 5)
+ assert_allclose(M, M_round_trip)
+ # Test a large abs fractional power.
+ X = fractional_matrix_power(M, -5.4)
+ Y = np.linalg.matrix_power(M_one_fifth, -27)
+ assert_allclose(X, Y)
+ # Test another large abs fractional power.
+ X = fractional_matrix_power(M, 3.8)
+ Y = np.linalg.matrix_power(M_one_fifth, 19)
+ assert_allclose(X, Y)
+
+ def test_random_matrices_and_powers(self):
+ # Each independent iteration of this fuzz test picks random parameters.
+ # It tries to hit some edge cases.
+ rng = np.random.default_rng(1726500458620605)
+ nsamples = 20
+ for i in range(nsamples):
+ # Sample a matrix size and a random real power.
+ n = rng.integers(1, 5)
+ p = rng.random()
+
+ # Sample a random real or complex matrix.
+ matrix_scale = np.exp(rng.integers(-4, 5))
+ A = rng.random(size=[n, n])
+ if [True, False][rng.choice(2)]:
+ A = A + 1j * rng.random(size=[n, n])
+ A = A * matrix_scale
+
+ # Check a couple of analytically equivalent ways
+ # to compute the fractional matrix power.
+ # These can be compared because they both use the principal branch.
+ A_power = fractional_matrix_power(A, p)
+ A_logm = logm(A)
+ A_power_expm_logm = expm(A_logm * p)
+ assert_allclose(A_power, A_power_expm_logm)
+
+ def test_al_mohy_higham_2012_experiment_1(self):
+ # Fractional powers of a tricky upper triangular matrix.
+ A = _get_al_mohy_higham_2012_experiment_1()
+
+ # Test remainder matrix power.
+ A_funm_sqrt = funm(A, np.sqrt)
+ A_sqrtm = sqrtm(A)
+ A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5)
+ A_power = fractional_matrix_power(A, 0.5)
+ assert_allclose(A_rem_power, A_power, rtol=1e-11)
+ assert_allclose(A_sqrtm, A_power)
+ assert_allclose(A_sqrtm, A_funm_sqrt)
+
+ # Test more fractional powers.
+ for p in (1/2, 5/3):
+ A_power = fractional_matrix_power(A, p)
+ A_round_trip = fractional_matrix_power(A_power, 1/p)
+ assert_allclose(A_round_trip, A, rtol=1e-2)
+ assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1))
+
+ def test_briggs_helper_function(self):
+ rng = np.random.default_rng(1234)
+ for a in rng.standard_normal(10) + 1j * rng.standard_normal(10):
+ for k in range(5):
+ x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k)
+ x_expected = a ** np.exp2(-k) - 1
+ assert_allclose(x_observed, x_expected)
+
+ def test_type_preservation_and_conversion(self):
+ # The fractional_matrix_power matrix function should preserve
+ # the type of a matrix whose eigenvalues
+ # are positive with zero imaginary part.
+ # Test this preservation for variously structured matrices.
+ complex_dtype_chars = ('F', 'D', 'G')
+ for matrix_as_list in (
+ [[1, 0], [0, 1]],
+ [[1, 0], [1, 1]],
+ [[2, 1], [1, 1]],
+ [[2, 3], [1, 2]]):
+
+ # check that the spectrum has the expected properties
+ W = scipy.linalg.eigvals(matrix_as_list)
+ assert_(not any(w.imag or w.real < 0 for w in W))
+
+ # Check various positive and negative powers
+ # with absolute values bigger and smaller than 1.
+ for p in (-2.4, -0.9, 0.2, 3.3):
+
+ # check float type preservation
+ A = np.array(matrix_as_list, dtype=float)
+ A_power = fractional_matrix_power(A, p)
+ assert_(A_power.dtype.char not in complex_dtype_chars)
+
+ # check complex type preservation
+ A = np.array(matrix_as_list, dtype=complex)
+ A_power = fractional_matrix_power(A, p)
+ assert_(A_power.dtype.char in complex_dtype_chars)
+
+ # check float->complex for the matrix negation
+ A = -np.array(matrix_as_list, dtype=float)
+ A_power = fractional_matrix_power(A, p)
+ assert_(A_power.dtype.char in complex_dtype_chars)
+
+ def test_type_conversion_mixed_sign_or_complex_spectrum(self):
+ complex_dtype_chars = ('F', 'D', 'G')
+ for matrix_as_list in (
+ [[1, 0], [0, -1]],
+ [[0, 1], [1, 0]],
+ [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
+
+ # check that the spectrum has the expected properties
+ W = scipy.linalg.eigvals(matrix_as_list)
+ assert_(any(w.imag or w.real < 0 for w in W))
+
+ # Check various positive and negative powers
+ # with absolute values bigger and smaller than 1.
+ for p in (-2.4, -0.9, 0.2, 3.3):
+
+ # check complex->complex
+ A = np.array(matrix_as_list, dtype=complex)
+ A_power = fractional_matrix_power(A, p)
+ assert_(A_power.dtype.char in complex_dtype_chars)
+
+ # check float->complex
+ A = np.array(matrix_as_list, dtype=float)
+ A_power = fractional_matrix_power(A, p)
+ assert_(A_power.dtype.char in complex_dtype_chars)
+
+ @pytest.mark.xfail(reason='Too unstable across LAPACKs.')
+ def test_singular(self):
+ # Negative fractional powers do not work with singular matrices.
+ for matrix_as_list in (
+ [[0, 0], [0, 0]],
+ [[1, 1], [1, 1]],
+ [[1, 2], [3, 6]],
+ [[0, 0, 0], [0, 1, 1], [0, -1, 1]]):
+
+ # Check fractional powers both for float and for complex types.
+ for newtype in (float, complex):
+ A = np.array(matrix_as_list, dtype=newtype)
+ for p in (-0.7, -0.9, -2.4, -1.3):
+ A_power = fractional_matrix_power(A, p)
+ assert_(np.isnan(A_power).all())
+ for p in (0.2, 1.43):
+ A_power = fractional_matrix_power(A, p)
+ A_round_trip = fractional_matrix_power(A_power, 1/p)
+ assert_allclose(A_round_trip, A)
+
+ def test_opposite_sign_complex_eigenvalues(self):
+ M = [[2j, 4], [0, -2j]]
+ R = [[1+1j, 2], [0, 1-1j]]
+ assert_allclose(np.dot(R, R), M, atol=1e-14)
+ assert_allclose(fractional_matrix_power(M, 0.5), R, atol=1e-14)
+
+
+class TestExpM:
+ def test_zero(self):
+ a = array([[0.,0],[0,0]])
+ assert_array_almost_equal(expm(a),[[1,0],[0,1]])
+
+ def test_single_elt(self):
+ elt = expm(1)
+ assert_allclose(elt, np.array([[np.e]]))
+
+ @pytest.mark.parametrize('func', [expm, cosm, sinm, tanm, coshm, sinhm, tanhm])
+ @pytest.mark.parametrize('dt',[int, float, np.float32, complex, np.complex64])
+ @pytest.mark.parametrize('shape', [(0, 0), (1, 1)])
+ def test_small_empty_matrix_input(self, func, dt, shape):
+ # regression test for gh-11082 / gh-20372 - test behavior of expm
+ # and related functions for small and zero-sized arrays.
+ A = np.zeros(shape, dtype=dt)
+ A0 = np.zeros((10, 10), dtype=dt)
+ result = func(A)
+ result0 = func(A0)
+ assert result.shape == shape
+ assert result.dtype == result0.dtype
+
+ def test_2x2_input(self):
+ E = np.e
+ a = array([[1, 4], [1, 1]])
+ aa = (E**4 + 1)/(2*E)
+ bb = (E**4 - 1)/E
+ assert_allclose(expm(a), array([[aa, bb], [bb/4, aa]]))
+ assert expm(a.astype(np.complex64)).dtype.char == 'F'
+ assert expm(a.astype(np.float32)).dtype.char == 'f'
+
+ def test_nx2x2_input(self):
+ E = np.e
+ # These are integer matrices with integer eigenvalues
+ a = np.array([[[1, 4], [1, 1]],
+ [[1, 3], [1, -1]],
+ [[1, 3], [4, 5]],
+ [[1, 3], [5, 3]],
+ [[4, 5], [-3, -4]]], order='F')
+ # Exact results are computed symbolically
+ a_res = np.array([
+ [[(E**4+1)/(2*E), (E**4-1)/E],
+ [(E**4-1)/4/E, (E**4+1)/(2*E)]],
+ [[1/(4*E**2)+(3*E**2)/4, (3*E**2)/4-3/(4*E**2)],
+ [E**2/4-1/(4*E**2), 3/(4*E**2)+E**2/4]],
+ [[3/(4*E)+E**7/4, -3/(8*E)+(3*E**7)/8],
+ [-1/(2*E)+E**7/2, 1/(4*E)+(3*E**7)/4]],
+ [[5/(8*E**2)+(3*E**6)/8, -3/(8*E**2)+(3*E**6)/8],
+ [-5/(8*E**2)+(5*E**6)/8, 3/(8*E**2)+(5*E**6)/8]],
+ [[-3/(2*E)+(5*E)/2, -5/(2*E)+(5*E)/2],
+ [3/(2*E)-(3*E)/2, 5/(2*E)-(3*E)/2]]
+ ])
+ assert_allclose(expm(a), a_res)
+
+ def test_readonly(self):
+ n = 7
+ a = np.ones((n, n))
+ a.flags.writeable = False
+ expm(a)
+
+ @pytest.mark.fail_slow(5)
+ def test_gh18086(self):
+ A = np.zeros((400, 400), dtype=float)
+ rng = np.random.default_rng(100)
+ i = rng.integers(0, 399, 500)
+ j = rng.integers(0, 399, 500)
+ A[i, j] = rng.random(500)
+ # Check that result is accurate
+ first_res = expm(A)
+ np.testing.assert_array_almost_equal(logm(first_res), A)
+ # Check that result is consistent
+ for i in range(5):
+ next_res = expm(A)
+ np.testing.assert_array_almost_equal(first_res, next_res)
+
+ @pytest.mark.parametrize('dt', [np.float32, np.float64,
+ np.complex64, np.complex128])
+ def test_gh25924(self, dt):
+ # The scaling exponent of a slice that needed scaling and squaring
+ # leaked into the following slices that did not, squaring their
+ # unscaled results and returning expm(2**s * A) instead of expm(A).
+ rng = np.random.default_rng(1234)
+ n, batch = 6, 4
+ A = rng.standard_normal((batch, n, n))
+ if np.issubdtype(dt, np.complexfloating):
+ A = A + 1j*rng.standard_normal((batch, n, n))
+ A = A.astype(dt)
+ # First slice needs scaling and squaring, the remaining ones do not.
+ A[0] *= 8
+ A[1:] /= np.abs(A[1:]).sum(axis=1).max(axis=-1)[:, None, None]
+
+ one_at_a_time = np.stack([expm(x) for x in A])
+ assert_allclose(expm(A), one_at_a_time,
+ rtol=10*np.finfo(dt).eps, atol=0)
+
+
+class TestExpmFrechet:
+
+ def test_expm_frechet(self):
+ # a test of the basic functionality
+ M = np.array([
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [0, 0, 1, 2],
+ [0, 0, 5, 6],
+ ], dtype=float)
+ A = np.array([
+ [1, 2],
+ [5, 6],
+ ], dtype=float)
+ E = np.array([
+ [3, 4],
+ [7, 8],
+ ], dtype=float)
+ expected_expm = scipy.linalg.expm(A)
+ expected_frechet = scipy.linalg.expm(M)[:2, 2:]
+ for kwargs in ({}, {'method':'SPS'}, {'method':'blockEnlarge'}):
+ observed_expm, observed_frechet = expm_frechet(A, E, **kwargs)
+ assert_allclose(expected_expm, observed_expm)
+ assert_allclose(expected_frechet, observed_frechet)
+
+ def test_small_norm_expm_frechet(self):
+ # methodically test matrices with a range of norms, for better coverage
+ M_original = np.array([
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [0, 0, 1, 2],
+ [0, 0, 5, 6],
+ ], dtype=float)
+ A_original = np.array([
+ [1, 2],
+ [5, 6],
+ ], dtype=float)
+ E_original = np.array([
+ [3, 4],
+ [7, 8],
+ ], dtype=float)
+ A_original_norm_1 = scipy.linalg.norm(A_original, 1)
+ selected_m_list = [1, 3, 5, 7, 9, 11, 13, 15]
+ m_neighbor_pairs = zip(selected_m_list[:-1], selected_m_list[1:])
+ for ma, mb in m_neighbor_pairs:
+ ell_a = scipy.linalg._expm_frechet.ell_table_61[ma]
+ ell_b = scipy.linalg._expm_frechet.ell_table_61[mb]
+ target_norm_1 = 0.5 * (ell_a + ell_b)
+ scale = target_norm_1 / A_original_norm_1
+ M = scale * M_original
+ A = scale * A_original
+ E = scale * E_original
+ expected_expm = scipy.linalg.expm(A)
+ expected_frechet = scipy.linalg.expm(M)[:2, 2:]
+ observed_expm, observed_frechet = expm_frechet(A, E)
+ assert_allclose(expected_expm, observed_expm)
+ assert_allclose(expected_frechet, observed_frechet)
+
+ def test_fuzz(self):
+ rng = np.random.default_rng(1726500908359153)
+ # try a bunch of crazy inputs
+ rfuncs = (
+ rng.uniform,
+ rng.normal,
+ rng.standard_cauchy,
+ rng.exponential)
+ ntests = 100
+ for i in range(ntests):
+ rfunc = rfuncs[rng.choice(4)]
+ target_norm_1 = rng.exponential()
+ n = rng.integers(2, 16)
+ A_original = rfunc(size=(n,n))
+ E_original = rfunc(size=(n,n))
+ A_original_norm_1 = scipy.linalg.norm(A_original, 1)
+ scale = target_norm_1 / A_original_norm_1
+ A = scale * A_original
+ E = scale * E_original
+ M = np.vstack([
+ np.hstack([A, E]),
+ np.hstack([np.zeros_like(A), A])])
+ expected_expm = scipy.linalg.expm(A)
+ expected_frechet = scipy.linalg.expm(M)[:n, n:]
+ observed_expm, observed_frechet = expm_frechet(A, E)
+ assert_allclose(expected_expm, observed_expm, atol=5e-8)
+ assert_allclose(expected_frechet, observed_frechet, atol=1e-7)
+
+ def test_problematic_matrix(self):
+ # this test case uncovered a bug which has since been fixed
+ A = np.array([
+ [1.50591997, 1.93537998],
+ [0.41203263, 0.23443516],
+ ], dtype=float)
+ E = np.array([
+ [1.87864034, 2.07055038],
+ [1.34102727, 0.67341123],
+ ], dtype=float)
+ scipy.linalg.norm(A, 1)
+ sps_expm, sps_frechet = expm_frechet(
+ A, E, method='SPS')
+ blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
+ A, E, method='blockEnlarge')
+ assert_allclose(sps_expm, blockEnlarge_expm)
+ assert_allclose(sps_frechet, blockEnlarge_frechet)
+
+ @pytest.mark.slow
+ @pytest.mark.skip(reason='this test is deliberately slow')
+ def test_medium_matrix(self):
+ # profile this to see the speed difference
+ n = 1000
+ rng = np.random.default_rng(1234)
+ A = rng.exponential(size=(n, n))
+ E = rng.exponential(size=(n, n))
+ sps_expm, sps_frechet = expm_frechet(
+ A, E, method='SPS')
+ blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
+ A, E, method='blockEnlarge')
+ assert_allclose(sps_expm, blockEnlarge_expm)
+ assert_allclose(sps_frechet, blockEnlarge_frechet)
+
+
+def _help_expm_cond_search(A, A_norm, X, X_norm, eps, p):
+ p = np.reshape(p, A.shape)
+ p_norm = norm(p)
+ perturbation = eps * p * (A_norm / p_norm)
+ X_prime = expm(A + perturbation)
+ scaled_relative_error = norm(X_prime - X) / (X_norm * eps)
+ return -scaled_relative_error
+
+
+def _normalized_like(A, B):
+ return A * (scipy.linalg.norm(B) / scipy.linalg.norm(A))
+
+
+def _relative_error(f, A, perturbation):
+ X = f(A)
+ X_prime = f(A + perturbation)
+ return norm(X_prime - X) / norm(X)
+
+
+class TestExpmConditionNumber:
+ def test_expm_cond_smoke(self):
+ rng = np.random.default_rng(1234)
+ for n in range(1, 4):
+ A = rng.standard_normal((n, n))
+ kappa = expm_cond(A)
+ assert_array_less(0, kappa)
+
+ def test_expm_bad_condition_number(self):
+ A = np.array([
+ [-1.128679820, 9.614183771e4, -4.524855739e9, 2.924969411e14],
+ [0, -1.201010529, 9.634696872e4, -4.681048289e9],
+ [0, 0, -1.132893222, 9.532491830e4],
+ [0, 0, 0, -1.179475332],
+ ])
+ kappa = expm_cond(A)
+ assert_array_less(1e36, kappa)
+
+ def test_univariate(self):
+ rng = np.random.default_rng(1234)
+ for x in np.linspace(-5, 5, num=11):
+ A = np.array([[x]])
+ assert_allclose(expm_cond(A), abs(x))
+ for x in np.logspace(-2, 2, num=11):
+ A = np.array([[x]])
+ assert_allclose(expm_cond(A), abs(x))
+ for i in range(10):
+ A = rng.standard_normal((1, 1))
+ assert_allclose(expm_cond(A), np.absolute(A)[0, 0])
+
+ @pytest.mark.slow
+ def test_expm_cond_fuzz(self):
+ rng = np.random.RandomState(12345)
+ eps = 1e-5
+ nsamples = 10
+ for i in range(nsamples):
+ n = rng.randint(2, 5)
+ A = rng.randn(n, n)
+ A_norm = scipy.linalg.norm(A)
+ X = expm(A)
+ X_norm = scipy.linalg.norm(X)
+ kappa = expm_cond(A)
+
+ # Look for the small perturbation that gives the greatest
+ # relative error.
+ f = functools.partial(_help_expm_cond_search,
+ A, A_norm, X, X_norm, eps)
+ guess = np.ones(n*n)
+ out = minimize(f, guess, method='L-BFGS-B')
+ xopt = out.x
+ yopt = f(xopt)
+ p_best = eps * _normalized_like(np.reshape(xopt, A.shape), A)
+ p_best_relerr = _relative_error(expm, A, p_best)
+ assert_allclose(p_best_relerr, -yopt * eps)
+
+ # Check that the identified perturbation indeed gives greater
+ # relative error than random perturbations with similar norms.
+ for j in range(5):
+ p_rand = eps * _normalized_like(rng.randn(*A.shape), A)
+ assert_allclose(norm(p_best), norm(p_rand))
+ p_rand_relerr = _relative_error(expm, A, p_rand)
+ assert_array_less(p_rand_relerr, p_best_relerr)
+
+ # The greatest relative error should not be much greater than
+ # eps times the condition number kappa.
+ # In the limit as eps approaches zero it should never be greater.
+ assert_array_less(p_best_relerr, (1 + 2*eps) * eps * kappa)
+
+
+class TestKhatriRao:
+
+ def test_basic(self):
+ a = khatri_rao(array([[1, 2], [3, 4]]),
+ array([[5, 6], [7, 8]]))
+
+ assert_array_equal(a, array([[5, 12],
+ [7, 16],
+ [15, 24],
+ [21, 32]]))
+
+ b = khatri_rao(np.empty([2, 2]), np.empty([2, 2]))
+ assert_array_equal(b.shape, (4, 2))
+
+ def test_number_of_columns_equality(self):
+ with pytest.raises(ValueError):
+ a = array([[1, 2, 3],
+ [4, 5, 6]])
+ b = array([[1, 2],
+ [3, 4]])
+ khatri_rao(a, b)
+
+ def test_to_assure_2d_array(self):
+ with pytest.raises(ValueError):
+ # both arrays are 1-D
+ a = array([1, 2, 3])
+ b = array([4, 5, 6])
+ khatri_rao(a, b)
+
+ with pytest.raises(ValueError):
+ # first array is 1-D
+ a = array([1, 2, 3])
+ b = array([
+ [1, 2, 3],
+ [4, 5, 6]
+ ])
+ khatri_rao(a, b)
+
+ with pytest.raises(ValueError):
+ # second array is 1-D
+ a = array([
+ [1, 2, 3],
+ [7, 8, 9]
+ ])
+ b = array([4, 5, 6])
+ khatri_rao(a, b)
+
+ def test_equality_of_two_equations(self):
+ a = array([[1, 2], [3, 4]])
+ b = array([[5, 6], [7, 8]])
+
+ res1 = khatri_rao(a, b)
+ res2 = np.vstack([np.kron(a[:, k], b[:, k])
+ for k in range(b.shape[1])]).T
+
+ assert_array_equal(res1, res2)
+
+ def test_empty(self):
+ a = np.empty((0, 2))
+ b = np.empty((3, 2))
+ res = khatri_rao(a, b)
+ assert_allclose(res, np.empty((0, 2)))
+
+ a = np.empty((3, 0))
+ b = np.empty((5, 0))
+ res = khatri_rao(a, b)
+ assert_allclose(res, np.empty((15, 0)))
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f8f94fd10a5404d4013adf995bba54f76ff803
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py
@@ -0,0 +1,136 @@
+"""Test functions for linalg.matmul_toeplitz function
+"""
+
+import numpy as np
+from scipy.linalg import toeplitz, matmul_toeplitz
+
+from pytest import raises as assert_raises
+from numpy.testing import assert_allclose
+
+
+class TestMatmulToeplitz:
+
+ def setup_method(self):
+ self.rng = np.random.RandomState(42)
+ self.tolerance = 1.5e-13
+
+ def test_real(self):
+ cases = []
+
+ n = 1
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n)
+ x = self.rng.normal(size=(n, 1))
+ cases.append((x, c, r, False))
+
+ n = 2
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n)
+ x = self.rng.normal(size=(n, 1))
+ cases.append((x, c, r, False))
+
+ n = 101
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n)
+ x = self.rng.normal(size=(n, 1))
+ cases.append((x, c, r, True))
+
+ n = 1000
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n)
+ x = self.rng.normal(size=(n, 1))
+ cases.append((x, c, r, False))
+
+ n = 100
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n)
+ x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+ cases.append((x, c, r, False))
+
+ n = 100
+ c = self.rng.normal(size=(n, 1))
+ r = self.rng.normal(size=(n, 1))
+ x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+ cases.append((x, c, r, True))
+
+ n = 100
+ c = self.rng.normal(size=(n, 1))
+ r = None
+ x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+ cases.append((x, c, r, True, -1))
+
+ n = 100
+ c = self.rng.normal(size=(n, 1))
+ r = None
+ x = self.rng.normal(size=n)
+ cases.append((x, c, r, False))
+
+ n = 101
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n-27)
+ x = self.rng.normal(size=(n-27, 1))
+ cases.append((x, c, r, True))
+
+ n = 100
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n//4)
+ x = self.rng.normal(size=(n//4, self.rng.randint(1, 10)))
+ cases.append((x, c, r, True))
+
+ [self.do(*i) for i in cases]
+
+ def test_complex(self):
+ n = 127
+ c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+ r = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+ x = self.rng.normal(size=(n, 3)) + self.rng.normal(size=(n, 3))*1j
+ self.do(x, c, r, False)
+
+ n = 100
+ c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+ r = self.rng.normal(size=(n//2, 1)) +\
+ self.rng.normal(size=(n//2, 1))*1j
+ x = self.rng.normal(size=(n//2, 3)) +\
+ self.rng.normal(size=(n//2, 3))*1j
+ self.do(x, c, r, False)
+
+ def test_empty(self):
+ c = []
+ r = []
+ x = []
+ self.do(x, c, r, False)
+
+ x = np.empty((0, 0))
+ self.do(x, c, r, False)
+
+ def test_exceptions(self):
+
+ n = 100
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=2*n)
+ x = self.rng.normal(size=n)
+ assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+ n = 100
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n)
+ x = self.rng.normal(size=n-1)
+ assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+ n = 100
+ c = self.rng.normal(size=n)
+ r = self.rng.normal(size=n//2)
+ x = self.rng.normal(size=n//2-1)
+ assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+ # For toeplitz matrices, matmul_toeplitz() should be equivalent to @.
+ def do(self, x, c, r=None, check_finite=False, workers=None):
+ c = np.ravel(c)
+ if r is None:
+ actual = matmul_toeplitz(c, x, check_finite, workers)
+ else:
+ r = np.ravel(r)
+ actual = matmul_toeplitz((c, r), x, check_finite)
+ desired = toeplitz(c, r) @ x
+ assert_allclose(actual, desired,
+ rtol=self.tolerance, atol=self.tolerance)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_procrustes.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..658cb806d713344f26ac796c28bf1af591627c84
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_procrustes.py
@@ -0,0 +1,209 @@
+from itertools import product, permutations
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+
+from scipy.linalg import orthogonal_procrustes
+from scipy.sparse._sputils import matrix
+from scipy._lib._array_api import make_xp_test_case, xp_assert_close
+from scipy.conftest import skip_xp_invalid_arg
+
+def _centered(A, xp):
+ mu = xp.mean(A, axis=0)
+ return A - mu, mu
+
+@make_xp_test_case(orthogonal_procrustes)
+class TestOrthogonalProcrustes:
+ def test_orthogonal_procrustes_ndim_too_small(self, xp):
+ rng = np.random.RandomState(1234)
+ A = xp.asarray(rng.randn(3))
+ B = xp.asarray(rng.randn(3))
+ assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+ def test_orthogonal_procrustes_shape_mismatch(self, xp):
+ rng = np.random.RandomState(1234)
+ shapes = ((3, 3), (3, 4), (4, 3), (4, 4))
+ for a, b in permutations(shapes, 2):
+ A = xp.asarray(rng.randn(*a))
+ B = xp.asarray(rng.randn(*b))
+ assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+ def test_orthogonal_procrustes_checkfinite_exception(self, xp):
+ rng = np.random.RandomState(1234)
+ m, n = 2, 3
+ A_good = rng.randn(m, n)
+ B_good = rng.randn(m, n)
+ for bad_value in np.inf, -np.inf, np.nan:
+ A_bad = A_good.copy()
+ A_bad[1, 2] = bad_value
+ B_bad = B_good.copy()
+ B_bad[1, 2] = bad_value
+ for A, B in ((A_good, B_bad), (A_bad, B_good), (A_bad, B_bad)):
+ assert_raises(ValueError, orthogonal_procrustes, xp.asarray(A),
+ xp.asarray(B))
+
+ def test_orthogonal_procrustes_scale_invariance(self, xp):
+ rng = np.random.RandomState(1234)
+ m, n = 4, 3
+ for i in range(3):
+ A_orig = xp.asarray(rng.randn(m, n))
+ B_orig = xp.asarray(rng.randn(m, n))
+ R_orig, s = orthogonal_procrustes(A_orig, B_orig)
+ for A_scale in np.square(rng.randn(3)):
+ for B_scale in np.square(rng.randn(3)):
+ R, s = orthogonal_procrustes(A_orig * xp.asarray(A_scale),
+ B_orig * xp.asarray(B_scale))
+ xp_assert_close(R, R_orig)
+
+ @skip_xp_invalid_arg()
+ def test_orthogonal_procrustes_array_conversion(self):
+ rng = np.random.RandomState(1234)
+ for m, n in ((6, 4), (4, 4), (4, 6)):
+ A_arr = rng.randn(m, n)
+ B_arr = rng.randn(m, n)
+ As = (A_arr, A_arr.tolist(), matrix(A_arr))
+ Bs = (B_arr, B_arr.tolist(), matrix(B_arr))
+ R_arr, s = orthogonal_procrustes(A_arr, B_arr)
+ AR_arr = A_arr.dot(R_arr)
+ for A, B in product(As, Bs):
+ R, s = orthogonal_procrustes(A, B)
+ AR = A_arr.dot(R)
+ assert_allclose(AR, AR_arr)
+
+ def test_orthogonal_procrustes(self, xp):
+ rng = np.random.RandomState(1234)
+ for m, n in ((6, 4), (4, 4), (4, 6)):
+ # Sample a random target matrix.
+ B = xp.asarray(rng.randn(m, n))
+ # Sample a random orthogonal matrix
+ # by computing eigh of a sampled symmetric matrix.
+ X = xp.asarray(rng.randn(n, n))
+ w, V = xp.linalg.eigh(X.T + X)
+ xp_assert_close(xp.linalg.inv(V), V.T)
+ # Compute a matrix with a known orthogonal transformation that gives B.
+ A = B @ V.T
+ # Check that an orthogonal transformation from A to B can be recovered.
+ R, s = orthogonal_procrustes(A, B)
+ xp_assert_close(xp.linalg.inv(R), R.T)
+ xp_assert_close(A @ R, B)
+ # Create a perturbed input matrix.
+ A_perturbed = A + 1e-2 * xp.asarray(rng.randn(m, n))
+ # Check that the orthogonal procrustes function can find an orthogonal
+ # transformation that is better than the orthogonal transformation
+ # computed from the original input matrix.
+ R_prime, s = orthogonal_procrustes(A_perturbed, B)
+ xp_assert_close(xp.linalg.inv(R_prime), R_prime.T)
+ # Compute the naive and optimal transformations of the perturbed input.
+ naive_approx = A_perturbed @ R
+ optim_approx = A_perturbed @ R_prime
+ # Compute the Frobenius norm errors of the matrix approximations.
+ naive_approx_error = xp.linalg.matrix_norm(naive_approx - B, ord='fro')
+ optim_approx_error = xp.linalg.matrix_norm(optim_approx - B, ord='fro')
+ # Check that the orthogonal Procrustes approximation is better.
+ assert xp.all(optim_approx_error < naive_approx_error)
+
+ def test_orthogonal_procrustes_exact_example(self, xp):
+ # Check a small application.
+ # It uses translation, scaling, reflection, and rotation.
+ #
+ # |
+ # a b |
+ # |
+ # d c | w
+ # |
+ # --------+--- x ----- z ---
+ # |
+ # | y
+ # |
+ #
+ A_orig = xp.asarray([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=xp.float64)
+ B_orig = xp.asarray([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=xp.float64)
+ A, A_mu = _centered(A_orig, xp)
+ B, B_mu = _centered(B_orig, xp)
+ R, s = orthogonal_procrustes(A, B)
+ scale = s / xp.linalg.matrix_norm(A)**2
+ B_approx = scale * A @ R + B_mu
+ xp_assert_close(B_approx, B_orig, atol=1e-8)
+
+ def test_orthogonal_procrustes_stretched_example(self, xp):
+ # Try again with a target with a stretched y axis.
+ A_orig = xp.asarray([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=xp.float64)
+ B_orig = xp.asarray([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=xp.float64)
+ A, A_mu = _centered(A_orig, xp)
+ B, B_mu = _centered(B_orig, xp)
+ R, s = orthogonal_procrustes(A, B)
+ scale = s / xp.linalg.matrix_norm(A)**2
+ B_approx = scale * A @ R + B_mu
+ expected = xp.asarray([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=xp.float64)
+ xp_assert_close(B_approx, expected, atol=1e-8)
+ # Check disparity symmetry.
+ expected_disparity = xp.asarray(0.4501246882793018, dtype=xp.float64)[()]
+ AB_disparity = (xp.linalg.matrix_norm(B_approx - B_orig)
+ / xp.linalg.matrix_norm(B))**2
+ xp_assert_close(AB_disparity, expected_disparity)
+ R, s = orthogonal_procrustes(B, A)
+ scale = s / xp.linalg.matrix_norm(B)**2
+ A_approx = scale * B @ R + A_mu
+ BA_disparity = (xp.linalg.matrix_norm(A_approx - A_orig)
+ / xp.linalg.matrix_norm(A))**2
+ xp_assert_close(BA_disparity, expected_disparity)
+
+ def test_orthogonal_procrustes_skbio_example(self, xp):
+ # This transformation is also exact.
+ # It uses translation, scaling, and reflection.
+ #
+ # |
+ # | a
+ # | b
+ # | c d
+ # --+---------
+ # |
+ # | w
+ # |
+ # | x
+ # |
+ # | z y
+ # |
+ #
+ A_orig = xp.asarray([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=xp.float64)
+ B_orig = xp.asarray([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=xp.float64)
+ B_standardized = xp.asarray([[-0.13363062, 0.6681531],
+ [-0.13363062, 0.13363062],
+ [-0.13363062, -0.40089186],
+ [0.40089186, -0.40089186]], dtype=xp.float64)
+ A, A_mu = _centered(A_orig, xp)
+ B, B_mu = _centered(B_orig, xp)
+ R, s = orthogonal_procrustes(A, B)
+ scale = s / xp.linalg.matrix_norm(A)**2
+ B_approx = scale * A @ R + B_mu
+ xp_assert_close(B_approx, B_orig)
+ xp_assert_close(B / xp.linalg.matrix_norm(B), B_standardized)
+
+ def test_empty(self, xp):
+ a = xp.empty((0, 0))
+ r, s = orthogonal_procrustes(a, a)
+ xp_assert_close(r, xp.empty((0, 0)))
+
+ a = xp.empty((0, 3))
+ r, s = orthogonal_procrustes(a, a)
+ xp_assert_close(r, xp.eye(3))
+
+ @pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)])
+ def test_unitary(self, shape, xp):
+ # gh-12071 added support for unitary matrices; check that it
+ # works as intended.
+ m, n = shape
+ rng = np.random.default_rng(589234981235)
+ A = xp.asarray(rng.random(shape) + rng.random(shape) * 1j)
+ Q = xp.asarray(rng.random((n, n)) + rng.random((n, n)) * 1j)
+ Q, _ = xp.linalg.qr(Q)
+ B = A @ Q
+ R, scale = orthogonal_procrustes(A, B)
+ xp_assert_close(R @ xp.conj(R).T, xp.eye(n, dtype=xp.complex128), atol=1e-14)
+ xp_assert_close(A @ Q, B)
+ if shape != (4, 5): # solution is unique
+ xp_assert_close(R, Q)
+ _, s, _ = xp.linalg.svd(xp.conj(A).T @ B)
+ xp_assert_close(scale, xp.sum(s))
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_sketches.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0cb2dec3c4ea5558929e97eae7d86ebfde254f5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_sketches.py
@@ -0,0 +1,112 @@
+"""Tests for _sketches.py."""
+
+import numpy as np
+from numpy.testing import assert_, assert_equal
+from scipy.linalg import clarkson_woodruff_transform
+from scipy.linalg._sketches import cwt_matrix
+from scipy.sparse import issparse, random_array
+from scipy.sparse.linalg import norm
+
+
+class TestClarksonWoodruffTransform:
+ """
+ Testing the Clarkson Woodruff Transform
+ """
+ # set seed for generating test matrices
+ rng = np.random.default_rng(1179103485)
+
+ # Test matrix parameters
+ n_rows = 2000
+ n_cols = 100
+ density = 0.1
+
+ # Sketch matrix dimensions
+ n_sketch_rows = 200
+
+ # Seeds to test with
+ seeds = [1755490010, 934377150, 1391612830, 1752708722, 2008891431,
+ 1302443994, 1521083269, 1501189312, 1126232505, 1533465685]
+
+ shape = (n_rows, n_cols)
+ A_dense = rng.random(shape)
+ A_csc = random_array(shape, density=density, format='csc', rng=rng)
+ A_csr = random_array(shape, density=density, format='csr', rng=rng)
+ A_coo = random_array(shape, density=density, format='coo', rng=rng)
+
+ # Collect the test matrices
+ test_matrices = [A_dense, A_csc, A_csr, A_coo]
+
+ # Test vector with norm ~1
+ x = rng.random((n_rows, 1)) / np.sqrt(n_rows)
+ del rng # Not deterministic in pytest-run-parallel
+
+ def test_sketch_dimensions(self):
+ for A in self.test_matrices:
+ for seed in self.seeds:
+ # seed to ensure backwards compatibility post SPEC7
+ sketch = clarkson_woodruff_transform(
+ A, self.n_sketch_rows, seed=seed
+ )
+ assert_(sketch.shape == (self.n_sketch_rows, self.n_cols))
+
+ def test_seed_returns_identical_transform_matrix(self):
+ for seed in self.seeds:
+ S1 = cwt_matrix(
+ self.n_sketch_rows, self.n_rows, rng=seed
+ ).toarray()
+ S2 = cwt_matrix(
+ self.n_sketch_rows, self.n_rows, rng=seed
+ ).toarray()
+ assert_equal(S1, S2)
+
+ def test_seed_returns_identically(self):
+ for A in self.test_matrices:
+ for seed in self.seeds:
+ sketch1 = clarkson_woodruff_transform(
+ A, self.n_sketch_rows, rng=seed
+ )
+ sketch2 = clarkson_woodruff_transform(
+ A, self.n_sketch_rows, rng=seed
+ )
+ if issparse(sketch1):
+ sketch1 = sketch1.toarray()
+ if issparse(sketch2):
+ sketch2 = sketch2.toarray()
+ assert_equal(sketch1, sketch2)
+
+ def test_sketch_preserves_frobenius_norm(self):
+ # Given the probabilistic nature of the sketches
+ # we run the test multiple times and check that
+ # we pass all/almost all the tries.
+ n_errors = 0
+ for A in self.test_matrices:
+ if issparse(A):
+ true_norm = norm(A)
+ else:
+ true_norm = np.linalg.norm(A)
+ for seed in self.seeds:
+ sketch = clarkson_woodruff_transform(
+ A, self.n_sketch_rows, rng=seed,
+ )
+ if issparse(sketch):
+ sketch_norm = norm(sketch)
+ else:
+ sketch_norm = np.linalg.norm(sketch)
+
+ if np.abs(true_norm - sketch_norm) > 0.1 * true_norm:
+ n_errors += 1
+ assert_(n_errors == 0)
+
+ def test_sketch_preserves_vector_norm(self):
+ n_errors = 0
+ n_sketch_rows = int(np.ceil(2. / (0.01 * 0.5**2)))
+ true_norm = np.linalg.norm(self.x)
+ for seed in self.seeds:
+ sketch = clarkson_woodruff_transform(
+ self.x, n_sketch_rows, rng=seed,
+ )
+ sketch_norm = np.linalg.norm(sketch)
+
+ if np.abs(true_norm - sketch_norm) > 0.5 * true_norm:
+ n_errors += 1
+ assert_(n_errors == 0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solve_toeplitz.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ed1bec48691b94ff6ae997f57523b7248bfe9e5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
@@ -0,0 +1,137 @@
+"""Test functions for linalg._solve_toeplitz module
+"""
+import numpy as np
+from scipy.linalg._solve_toeplitz import levinson
+from scipy.linalg import solve, toeplitz, solve_toeplitz
+from numpy.testing import assert_equal, assert_allclose
+
+import pytest
+from pytest import raises as assert_raises
+
+
+def test_solve_equivalence():
+ # For toeplitz matrices, solve_toeplitz() should be equivalent to solve().
+ random = np.random.RandomState(1234)
+ for n in (1, 2, 3, 10):
+ c = random.randn(n)
+ if random.rand() < 0.5:
+ c = c + 1j * random.randn(n)
+ r = random.randn(n)
+ if random.rand() < 0.5:
+ r = r + 1j * random.randn(n)
+ y = random.randn(n)
+ if random.rand() < 0.5:
+ y = y + 1j * random.randn(n)
+
+ # Check equivalence when both the column and row are provided.
+ actual = solve_toeplitz((c,r), y)
+ desired = solve(toeplitz(c, r=r), y)
+ assert_allclose(actual, desired)
+
+ # Check equivalence when the column is provided but not the row.
+ actual = solve_toeplitz(c, b=y)
+ desired = solve(toeplitz(c), y)
+ assert_allclose(actual, desired)
+
+
+def test_multiple_rhs():
+ random = np.random.RandomState(1234)
+ c = random.randn(4)
+ r = random.randn(4)
+ for offset in [0, 1j]:
+ for yshape in ((4,), (4, 3)):
+ y = random.randn(*yshape) + offset
+ actual = solve_toeplitz((c,r), b=y)
+ desired = solve(toeplitz(c, r=r), y)
+ assert_equal(actual.shape, yshape)
+ assert_equal(desired.shape, yshape)
+ assert_allclose(actual, desired)
+
+
+def test_native_list_arguments():
+ c = [1,2,4,7]
+ r = [1,3,9,12]
+ y = [5,1,4,2]
+ actual = solve_toeplitz((c,r), y)
+ desired = solve(toeplitz(c, r=r), y)
+ assert_allclose(actual, desired)
+
+
+def test_zero_diag_error():
+ # The Levinson-Durbin implementation fails when the diagonal is zero.
+ random = np.random.RandomState(1234)
+ n = 4
+ c = random.randn(n)
+ r = random.randn(n)
+ y = random.randn(n)
+ c[0] = 0
+ assert_raises(np.linalg.LinAlgError,
+ solve_toeplitz, (c, r), b=y)
+
+
+def test_wikipedia_counterexample():
+ # The Levinson-Durbin implementation also fails in other cases.
+ # This example is from the talk page of the wikipedia article.
+ random = np.random.RandomState(1234)
+ c = [2, 2, 1]
+ y = random.randn(3)
+ assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y)
+
+
+def test_reflection_coeffs():
+ # check that the partial solutions are given by the reflection
+ # coefficients
+
+ random = np.random.RandomState(1234)
+ y_d = random.randn(10)
+ y_z = random.randn(10) + 1j
+ reflection_coeffs_d = [1]
+ reflection_coeffs_z = [1]
+ for i in range(2, 10):
+ reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1])
+ reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1])
+
+ y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1]))
+ y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1]))
+ _, ref_d = levinson(y_d_concat, b=y_d[1:])
+ _, ref_z = levinson(y_z_concat, b=y_z[1:])
+
+ assert_allclose(reflection_coeffs_d, ref_d[:-1])
+ assert_allclose(reflection_coeffs_z, ref_z[:-1])
+
+
+@pytest.mark.xfail(reason='Instability of Levinson iteration')
+def test_unstable():
+ # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of
+ # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with
+ # Partial Pivoting for Matrices with Displacement Structure"
+ # Mathematics of Computation, 64, 212 (1995), pp 1557-1576
+ # which can be unstable for levinson recursion.
+
+ # other fast toeplitz solvers such as GKO or Burg should be better.
+ random = np.random.RandomState(1234)
+ n = 100
+ c = 0.9 ** (np.arange(n)**2)
+ y = random.randn(n)
+
+ solution1 = solve_toeplitz(c, b=y)
+ solution2 = solve(toeplitz(c), y)
+
+ assert_allclose(solution1, solution2)
+
+
+@pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])
+@pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+def test_empty(dt_c, dt_b):
+ c = np.array([], dtype=dt_c)
+ b = np.array([], dtype=dt_b)
+ x = solve_toeplitz(c, b)
+ assert x.shape == (0,)
+ assert x.dtype == solve_toeplitz(np.array([2, 1], dtype=dt_c),
+ np.ones(2, dtype=dt_b)).dtype
+
+ b = np.empty((0, 0), dtype=dt_b)
+ x1 = solve_toeplitz(c, b)
+ assert x1.shape == (0, 0)
+ assert x1.dtype == x.dtype
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solvers.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..d81df855198c1ad5a0bbae9a522fdffb6ee382f4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_solvers.py
@@ -0,0 +1,862 @@
+import os
+import numpy as np
+
+from numpy.testing import assert_array_almost_equal, assert_allclose
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import solve_sylvester
+from scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunov
+from scipy.linalg import solve_continuous_are, solve_discrete_are
+from scipy.linalg import block_diag, solve, LinAlgError
+from scipy.sparse._sputils import matrix
+from scipy.conftest import skip_xp_invalid_arg
+
+
+# dtypes for testing size-0 case following precedent set in gh-20295
+dtypes = [int, float, np.float32, complex, np.complex64]
+
+
+def _load_data(name):
+ """
+ Load npz data file under data/
+ Returns a copy of the data, rather than keeping the npz file open.
+ """
+ filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
+ 'data', name)
+ with np.load(filename) as f:
+ return dict(f.items())
+
+
+class TestSolveLyapunov:
+
+ cases = [
+ # empty case
+ (np.empty((0, 0)),
+ np.empty((0, 0))),
+ (np.array([[1, 2], [3, 4]]),
+ np.array([[9, 10], [11, 12]])),
+ # a, q all complex.
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+ # a real; q complex.
+ (np.array([[1.0, 2.0], [3.0, 5.0]]),
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+ # a complex; q real.
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+ np.array([[2.0, 2.0], [-1.0, 2.0]])),
+ # An example from Kitagawa, 1977
+ (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3],
+ [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]),
+ np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3],
+ [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])),
+ # Companion matrix example. a complex; q real; a.shape[0] = 11
+ (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j,
+ 0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j,
+ 0.010+0.j],
+ [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
+ 0.000+0.j],
+ [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+ 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
+ 0.000+0.j]]),
+ np.eye(11)),
+ # https://github.com/scipy/scipy/issues/4176
+ (matrix([[0, 1], [-1/2, -1]]),
+ (matrix([0, 3]).T @ matrix([0, 3]).T.T)),
+ # https://github.com/scipy/scipy/issues/4176
+ (matrix([[0, 1], [-1/2, -1]]),
+ (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))),
+ ]
+
+ def test_continuous_squareness_and_shape(self):
+ nsq = np.ones((3, 2))
+ sq = np.eye(3)
+ assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq)
+ assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq)
+ assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2))
+
+ def check_continuous_case(self, a, q):
+ x = solve_continuous_lyapunov(a, q)
+ assert_array_almost_equal(
+ np.dot(a, x) + np.dot(x, a.conj().transpose()), q)
+
+ def check_discrete_case(self, a, q, method=None):
+ x = solve_discrete_lyapunov(a, q, method=method)
+ assert_array_almost_equal(
+ np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q)
+
+ @skip_xp_invalid_arg
+ def test_cases(self):
+ for case in self.cases:
+ self.check_continuous_case(case[0], case[1])
+ self.check_discrete_case(case[0], case[1])
+ self.check_discrete_case(case[0], case[1], method='direct')
+ self.check_discrete_case(case[0], case[1], method='bilinear')
+
+ @pytest.mark.parametrize("dtype_a", dtypes)
+ @pytest.mark.parametrize("dtype_q", dtypes)
+ def test_size_0(self, dtype_a, dtype_q):
+ rng = np.random.default_rng(234598235)
+
+ a = np.zeros((0, 0), dtype=dtype_a)
+ q = np.zeros((0, 0), dtype=dtype_q)
+ res = solve_continuous_lyapunov(a, q)
+
+ a = (rng.random((5, 5))*100).astype(dtype_a)
+ q = (rng.random((5, 5))*100).astype(dtype_q)
+ ref = solve_continuous_lyapunov(a, q)
+
+ assert res.shape == (0, 0)
+ assert res.dtype == ref.dtype
+
+
+class TestSolveContinuousAre:
+ mat6 = _load_data('carex_6_data.npz')
+ mat15 = _load_data('carex_15_data.npz')
+ mat18 = _load_data('carex_18_data.npz')
+ mat19 = _load_data('carex_19_data.npz')
+ mat20 = _load_data('carex_20_data.npz')
+ cases = [
+ # Carex examples taken from (with default parameters):
+ # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
+ # Examples for the Numerical Solution of Algebraic Riccati
+ # Equations II: Continuous-Time Case', Tech. Report SPC 95_23,
+ # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
+ #
+ # The format of the data is (a, b, q, r, knownfailure), where
+ # knownfailure is None if the test passes or a string
+ # indicating the reason for failure.
+ #
+ # Test Case 0: carex #1
+ (np.diag([1.], 1),
+ np.array([[0], [1]]),
+ block_diag(1., 2.),
+ 1,
+ None),
+ # Test Case 1: carex #2
+ (np.array([[4, 3], [-4.5, -3.5]]),
+ np.array([[1], [-1]]),
+ np.array([[9, 6], [6, 4.]]),
+ 1,
+ None),
+ # Test Case 2: carex #3
+ (np.array([[0, 1, 0, 0],
+ [0, -1.89, 0.39, -5.53],
+ [0, -0.034, -2.98, 2.43],
+ [0.034, -0.0011, -0.99, -0.21]]),
+ np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]),
+ np.array([[2.313, 2.727, 0.688, 0.023],
+ [2.727, 4.271, 1.148, 0.323],
+ [0.688, 1.148, 0.313, 0.102],
+ [0.023, 0.323, 0.102, 0.083]]),
+ np.eye(2),
+ None),
+ # Test Case 3: carex #4
+ (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0],
+ [0.522, -1.051, 0.596, 0, 0, 0, 0, 0],
+ [0, 0.522, -1.118, 0.596, 0, 0, 0, 0],
+ [0, 0, 0.522, -1.548, 0.718, 0, 0, 0],
+ [0, 0, 0, 0.922, -1.64, 0.799, 0, 0],
+ [0, 0, 0, 0, 0.922, -1.721, 0.901, 0],
+ [0, 0, 0, 0, 0, 0.922, -1.823, 1.021],
+ [0, 0, 0, 0, 0, 0, 0.922, -1.943]]),
+ np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00],
+ [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]]
+ ).T * 0.001,
+ np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1],
+ [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+ [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0],
+ [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]),
+ np.eye(2),
+ None),
+ # Test Case 4: carex #5
+ (np.array(
+ [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870],
+ [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970],
+ [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680],
+ [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390],
+ [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400],
+ [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.],
+ [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0],
+ [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0],
+ [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]),
+ np.array([[0.010, -0.011, -0.151],
+ [0.003, -0.021, 0.000],
+ [0.009, -0.059, 0.000],
+ [0.024, -0.162, 0.000],
+ [0.068, -0.445, 0.000],
+ [0.000, 0.000, 0.000],
+ [0.000, 0.000, 0.000],
+ [0.000, 0.000, 0.000],
+ [0.000, 0.000, 0.000]]),
+ np.eye(9),
+ np.eye(3),
+ None),
+ # Test Case 5: carex #6
+ (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None),
+ # Test Case 6: carex #7
+ (np.array([[1, 0], [0, -2.]]),
+ np.array([[1e-6], [0]]),
+ np.ones((2, 2)),
+ 1.,
+ 'Bad residual accuracy'),
+ # Test Case 7: carex #8
+ (block_diag(-0.1, -0.02),
+ np.array([[0.100, 0.000], [0.001, 0.010]]),
+ np.array([[100, 1000], [1000, 10000]]),
+ np.ones((2, 2)) + block_diag(1e-6, 0),
+ None),
+ # Test Case 8: carex #9
+ (np.array([[0, 1e6], [0, 0]]),
+ np.array([[0], [1.]]),
+ np.eye(2),
+ 1.,
+ None),
+ # Test Case 9: carex #10
+ (np.array([[1.0000001, 1], [1., 1.0000001]]),
+ np.eye(2),
+ np.eye(2),
+ np.eye(2),
+ None),
+ # Test Case 10: carex #11
+ (np.array([[3, 1.], [4, 2]]),
+ np.array([[1], [1]]),
+ np.array([[-11, -5], [-5, -2.]]),
+ 1.,
+ None),
+ # Test Case 11: carex #12
+ (np.array([[7000000., 2000000., -0.],
+ [2000000., 6000000., -2000000.],
+ [0., -2000000., 5000000.]]) / 3,
+ np.eye(3),
+ np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot(
+ np.diag([1e-6, 1, 1e6])).dot(
+ np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9,
+ np.eye(3) * 1e6,
+ 'Bad Residual Accuracy'),
+ # Test Case 12: carex #13
+ (np.array([[0, 0.4, 0, 0],
+ [0, 0, 0.345, 0],
+ [0, -0.524e6, -0.465e6, 0.262e6],
+ [0, 0, 0, -1e6]]),
+ np.array([[0, 0, 0, 1e6]]).T,
+ np.diag([1, 0, 1, 0]),
+ 1.,
+ None),
+ # Test Case 13: carex #14
+ (np.array([[-1e-6, 1, 0, 0],
+ [-1, -1e-6, 0, 0],
+ [0, 0, 1e-6, 1],
+ [0, 0, -1, 1e-6]]),
+ np.ones((4, 1)),
+ np.ones((4, 4)),
+ 1.,
+ None),
+ # Test Case 14: carex #15
+ (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None),
+ # Test Case 15: carex #16
+ (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90(
+ block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1),
+ np.eye(64),
+ np.eye(64),
+ np.eye(64),
+ None),
+ # Test Case 16: carex #17
+ (np.diag(np.ones((20, )), 1),
+ np.flipud(np.eye(21, 1)),
+ np.eye(21, 1) * np.eye(21, 1).T,
+ 1,
+ 'Bad Residual Accuracy'),
+ # Test Case 17: carex #18
+ (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None),
+ # Test Case 18: carex #19
+ (mat19['A'], mat19['B'], mat19['Q'], mat19['R'],
+ 'Bad Residual Accuracy'),
+ # Test Case 19: carex #20
+ (mat20['A'], mat20['B'], mat20['Q'], mat20['R'],
+ 'Bad Residual Accuracy')
+ ]
+ # Makes the minimum precision requirements customized to the test.
+ # Here numbers represent the number of decimals that agrees with zero
+ # matrix when the solution x is plugged in to the equation.
+ #
+ # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
+ #
+ # If the test is failing use "None" for that entry.
+ #
+ min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14,
+ None, 9, 14, 13, 14, None, 12, None, None)
+
+ @pytest.mark.parametrize("j, case", list(enumerate(cases)))
+ def test_solve_continuous_are(self, j, case):
+ """Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true"""
+ a, b, q, r, knownfailure = case
+ if knownfailure:
+ pytest.xfail(reason=knownfailure)
+
+ dec = self.min_decimal[j]
+ x = solve_continuous_are(a, b, q, r)
+ res = x @ a + a.conj().T @ x + q
+ out_fact = x @ b
+ res -= out_fact @ solve(np.atleast_2d(r), out_fact.conj().T)
+ assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+
+
+class TestSolveDiscreteAre:
+ cases = [
+ # Darex examples taken from (with default parameters):
+ # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
+ # Examples for the Numerical Solution of Algebraic Riccati
+ # Equations II: Discrete-Time Case', Tech. Report SPC 95_23,
+ # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
+ # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the
+ # Discrete-Time Algebraic Riccati Equation to Enhance Stability
+ # of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4)
+ #
+ # The format of the data is (a, b, q, r, knownfailure), where
+ # knownfailure is None if the test passes or a string
+ # indicating the reason for failure.
+ #
+ # TEST CASE 0 : Complex a; real b, q, r
+ (np.array([[2, 1-2j], [0, -3j]]),
+ np.array([[0], [1]]),
+ np.array([[1, 0], [0, 2]]),
+ np.array([[1]]),
+ None),
+ # TEST CASE 1 :Real a, q, r; complex b
+ (np.array([[2, 1], [0, -1]]),
+ np.array([[-2j], [1j]]),
+ np.array([[1, 0], [0, 2]]),
+ np.array([[1]]),
+ None),
+ # TEST CASE 2 : Real a, b; complex q, r
+ (np.array([[3, 1], [0, -1]]),
+ np.array([[1, 2], [1, 3]]),
+ np.array([[1, 1+1j], [1-1j, 2]]),
+ np.array([[2, -2j], [2j, 3]]),
+ None),
+ # TEST CASE 3 : User-reported gh-2251 (Trac #1732)
+ (np.array([[0.63399379, 0.54906824, 0.76253406],
+ [0.5404729, 0.53745766, 0.08731853],
+ [0.27524045, 0.84922129, 0.4681622]]),
+ np.array([[0.96861695], [0.05532739], [0.78934047]]),
+ np.eye(3),
+ np.eye(1),
+ None),
+ # TEST CASE 4 : darex #1
+ (np.array([[4, 3], [-4.5, -3.5]]),
+ np.array([[1], [-1]]),
+ np.array([[9, 6], [6, 4]]),
+ np.array([[1]]),
+ None),
+ # TEST CASE 5 : darex #2
+ (np.array([[0.9512, 0], [0, 0.9048]]),
+ np.array([[4.877, 4.877], [-1.1895, 3.569]]),
+ np.array([[0.005, 0], [0, 0.02]]),
+ np.array([[1/3, 0], [0, 3]]),
+ None),
+ # TEST CASE 6 : darex #3
+ (np.array([[2, -1], [1, 0]]),
+ np.array([[1], [0]]),
+ np.array([[0, 0], [0, 1]]),
+ np.array([[0]]),
+ None),
+ # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S)
+ (np.array([[0, 1], [0, -1]]),
+ np.array([[1, 0], [2, 1]]),
+ np.array([[-4, -4], [-4, 7]]) * (1/11),
+ np.array([[9, 3], [3, 1]]),
+ None),
+ # TEST CASE 8 : darex #5
+ (np.array([[0, 1], [0, 0]]),
+ np.array([[0], [1]]),
+ np.array([[1, 2], [2, 4]]),
+ np.array([[1]]),
+ None),
+ # TEST CASE 9 : darex #6
+ (np.array([[0.998, 0.067, 0, 0],
+ [-.067, 0.998, 0, 0],
+ [0, 0, 0.998, 0.153],
+ [0, 0, -.153, 0.998]]),
+ np.array([[0.0033, 0.0200],
+ [0.1000, -.0007],
+ [0.0400, 0.0073],
+ [-.0028, 0.1000]]),
+ np.array([[1.87, 0, 0, -0.244],
+ [0, 0.744, 0.205, 0],
+ [0, 0.205, 0.589, 0],
+ [-0.244, 0, 0, 1.048]]),
+ np.eye(2),
+ None),
+ # TEST CASE 10 : darex #7
+ (np.array([[0.984750, -.079903, 0.0009054, -.0010765],
+ [0.041588, 0.998990, -.0358550, 0.0126840],
+ [-.546620, 0.044916, -.3299100, 0.1931800],
+ [2.662400, -.100450, -.9245500, -.2632500]]),
+ np.array([[0.0037112, 0.0007361],
+ [-.0870510, 9.3411e-6],
+ [-1.198440, -4.1378e-4],
+ [-3.192700, 9.2535e-4]]),
+ np.eye(4)*1e-2,
+ np.eye(2),
+ None),
+ # TEST CASE 11 : darex #8
+ (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180],
+ [1.0000000, 0.6000000, 0.8000000, 3.3999820],
+ [0.0000000, 1.0000000, 1.8000000, 3.7999820],
+ [0.0000000, 0.0000000, 0.0000000, -0.9999820]]),
+ np.array([[1.0, -1.0, -1.0, -1.0],
+ [0.0, 1.0, -1.0, -1.0],
+ [0.0, 0.0, 1.0, -1.0],
+ [0.0, 0.0, 0.0, 1.0]]),
+ np.array([[2, 1, 3, 6],
+ [1, 2, 2, 5],
+ [3, 2, 6, 11],
+ [6, 5, 11, 22]]),
+ np.eye(4),
+ None),
+ # TEST CASE 12 : darex #9
+ (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190],
+ [40.8490, 41.3170, 16.0840, 4.4679, 1.1971],
+ [12.2170, 26.3260, 36.1490, 15.9300, 12.3830],
+ [4.1118, 12.8580, 27.2090, 21.4420, 40.9760],
+ [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01,
+ np.array([[0.0434, -0.0122],
+ [2.6606, -1.0453],
+ [3.7530, -5.5100],
+ [3.6076, -6.6000],
+ [0.4617, -0.9148]]) * 0.01,
+ np.eye(5),
+ np.eye(2),
+ None),
+ # TEST CASE 13 : darex #10
+ (np.kron(np.eye(2), np.diag([1, 1], k=1)),
+ np.kron(np.eye(2), np.array([[0], [0], [1]])),
+ np.array([[1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, -1, 0],
+ [0, 0, 0, -1, 1, 0],
+ [0, 0, 0, 0, 0, 0]]),
+ np.array([[3, 0], [0, 1]]),
+ None),
+ # TEST CASE 14 : darex #11
+ (0.001 * np.array(
+ [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249],
+ [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499],
+ [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72],
+ [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82],
+ [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9],
+ [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6],
+ [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67],
+ [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54],
+ [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]),
+ np.array([[4.7600, -0.5701, -83.6800],
+ [0.8790, -4.7730, -2.7300],
+ [1.4820, -13.1200, 8.8760],
+ [3.8920, -35.1300, 24.8000],
+ [10.3400, -92.7500, 66.8000],
+ [7.2030, -61.5900, 38.3400],
+ [4.4540, -36.8300, 20.2900],
+ [1.9710, -15.5400, 6.9370],
+ [3.7730, -30.2800, 14.6900]]) * 0.001,
+ np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]),
+ np.eye(3),
+ None),
+ # TEST CASE 15 : darex #12 - numerically least accurate example
+ (np.array([[0, 1e6], [0, 0]]),
+ np.array([[0], [1]]),
+ np.eye(2),
+ np.array([[1]]),
+ None),
+ # TEST CASE 16 : darex #13
+ (np.array([[16, 10, -2],
+ [10, 13, -8],
+ [-2, -8, 7]]) * (1/9),
+ np.eye(3),
+ 1e6 * np.eye(3),
+ 1e6 * np.eye(3),
+ None),
+ # TEST CASE 17 : darex #14
+ (np.array([[1 - 1/1e8, 0, 0, 0],
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, 0]]),
+ np.array([[1e-08], [0], [0], [0]]),
+ np.diag([0, 0, 0, 1]),
+ np.array([[0.25]]),
+ None),
+ # TEST CASE 18 : darex #15
+ (np.eye(100, k=1),
+ np.flipud(np.eye(100, 1)),
+ np.eye(100),
+ np.array([[1]]),
+ None)
+ ]
+
+ # Makes the minimum precision requirements customized to the test.
+ # Here numbers represent the number of decimals that agrees with zero
+ # matrix when the solution x is plugged in to the equation.
+ #
+ # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
+ #
+ # If the test is failing use "None" for that entry.
+ #
+ min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13,
+ 14, 13, 13, 14, 12, 2, 4, 6, 10)
+ max_tol = [1.5 * 10**-ind for ind in min_decimal]
+ # relaxed tolerance in gh-18012 after bump to OpenBLAS
+ max_tol[11] = 2.5e-13
+
+ # relaxed tolerance in gh-20335 for linux-aarch64 build on Cirrus
+ # with OpenBLAS from ubuntu jammy
+ max_tol[15] = 2.0e-2
+
+ # relaxed tolerance in gh-20335 for OpenBLAS 3.20 on ubuntu jammy
+ # bump not needed for OpenBLAS 3.26
+ max_tol[16] = 2.0e-4
+
+ @pytest.mark.parametrize("j, case", list(enumerate(cases)))
+ def test_solve_discrete_are(self, j, case):
+ """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+ a, b, q, r, knownfailure = case
+ if knownfailure:
+ pytest.xfail(reason=knownfailure)
+
+ atol = self.max_tol[j]
+
+ x = solve_discrete_are(a, b, q, r)
+ bH = b.conj().T
+ xa, xb = x @ a, x @ b
+
+ res = a.conj().T @ xa - x + q
+ res -= a.conj().T @ xb @ (solve(r + bH @ xb, bH) @ xa)
+
+ # changed from
+ # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+ # in gh-18012 as it's easier to relax a tolerance and allclose is
+ # preferred
+ assert_allclose(res, np.zeros_like(res), atol=atol)
+
+ def test_infeasible(self):
+ # An infeasible example taken from https://arxiv.org/abs/1505.04861v1
+ A = np.triu(np.ones((3, 3)))
+ A[0, 1] = -1
+ B = np.array([[1, 1, 0], [0, 0, 1]]).T
+ Q = np.full_like(A, -2) + np.diag([8, -1, -1.9])
+ R = np.diag([-10, 0.1])
+ assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R)
+
+
+class TestSolveCommonAre:
+ @pytest.mark.parametrize("solver", [solve_continuous_are, solve_discrete_are])
+ def test_with_skipped_array_argument_gh23336(self, solver):
+ # gh-23336 reported a failure when optional argument `e` was skipped
+ A = np.array([[-0.9, 0.25], [0, -1.1]])
+ B = np.array([[0.23], [0.45]])
+ Q = np.eye(2)
+ R = np.atleast_2d(0.45)
+ E = np.eye(2)
+ S = np.array([[0.1], [0.2]])
+
+ res = solver(A, B, Q, R, s=S)
+ ref = solver(A, B, Q, R, E, S)
+ np.testing.assert_allclose(res, ref)
+
+
+def test_solve_generalized_continuous_are():
+ cases = [
+ # Two random examples differ by s term
+ # in the absence of any literature for demanding examples.
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+ np.array([[3.815585e-01, 1.868726e-01],
+ [7.655168e-01, 4.897644e-01],
+ [7.951999e-01, 4.455862e-01]]),
+ np.eye(3),
+ np.eye(2),
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+ np.zeros((3, 2)),
+ None),
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+ np.array([[3.815585e-01, 1.868726e-01],
+ [7.655168e-01, 4.897644e-01],
+ [7.951999e-01, 4.455862e-01]]),
+ np.eye(3),
+ np.eye(2),
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+ np.ones((3, 2)),
+ None)
+ ]
+
+ min_decimal = (10, 10)
+
+ def _test_factory(case, dec):
+ """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+ a, b, q, r, e, s, knownfailure = case
+ if knownfailure:
+ pytest.xfail(reason=knownfailure)
+
+ x = solve_continuous_are(a, b, q, r, e, s)
+ res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q
+ out_fact = e.conj().T.dot(x).dot(b) + s
+ res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T))
+ assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+
+ for ind, case in enumerate(cases):
+ _test_factory(case, min_decimal[ind])
+
+
+def test_solve_generalized_discrete_are():
+ mat20170120 = _load_data('gendare_20170120_data.npz')
+
+ cases = [
+ # Two random examples differ by s term
+ # in the absence of any literature for demanding examples.
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+ np.array([[3.815585e-01, 1.868726e-01],
+ [7.655168e-01, 4.897644e-01],
+ [7.951999e-01, 4.455862e-01]]),
+ np.eye(3),
+ np.eye(2),
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+ np.zeros((3, 2)),
+ None),
+ (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+ [4.617139e-02, 6.948286e-01, 3.444608e-02],
+ [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+ np.array([[3.815585e-01, 1.868726e-01],
+ [7.655168e-01, 4.897644e-01],
+ [7.951999e-01, 4.455862e-01]]),
+ np.eye(3),
+ np.eye(2),
+ np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+ [7.093648e-01, 6.797027e-01, 1.189977e-01],
+ [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+ np.ones((3, 2)),
+ None),
+ # user-reported (under PR-6616) 20-Jan-2017
+ # tests against the case where E is None but S is provided
+ (mat20170120['A'],
+ mat20170120['B'],
+ mat20170120['Q'],
+ mat20170120['R'],
+ None,
+ mat20170120['S'],
+ None),
+ ]
+
+ max_atol = (1.5e-11, 1.5e-11, 3.5e-16)
+
+ def _test_factory(case, atol):
+ """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+ a, b, q, r, e, s, knownfailure = case
+ if knownfailure:
+ pytest.xfail(reason=knownfailure)
+
+ x = solve_discrete_are(a, b, q, r, e, s)
+ if e is None:
+ e = np.eye(a.shape[0])
+ if s is None:
+ s = np.zeros_like(b)
+ res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q
+ res -= (a.conj().T.dot(x.dot(b)) + s).dot(
+ solve(r+b.conj().T.dot(x.dot(b)),
+ (b.conj().T.dot(x.dot(a)) + s.conj().T)
+ )
+ )
+ # changed from:
+ # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+ # in gh-17950 because of a Linux 32 bit fail.
+ assert_allclose(res, np.zeros_like(res), atol=atol)
+
+ for ind, case in enumerate(cases):
+ _test_factory(case, max_atol[ind])
+
+
+def test_are_validate_args():
+
+ def test_square_shape():
+ nsq = np.ones((3, 2))
+ sq = np.eye(3)
+ for x in (solve_continuous_are, solve_discrete_are):
+ assert_raises(ValueError, x, nsq, 1, 1, 1)
+ assert_raises(ValueError, x, sq, sq, nsq, 1)
+ assert_raises(ValueError, x, sq, sq, sq, nsq)
+ assert_raises(ValueError, x, sq, sq, sq, sq, nsq)
+
+ def test_compatible_sizes():
+ nsq = np.ones((3, 2))
+ sq = np.eye(4)
+ for x in (solve_continuous_are, solve_discrete_are):
+ assert_raises(ValueError, x, sq, nsq, 1, 1)
+ assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq)
+ assert_raises(ValueError, x, sq, sq, np.eye(3), sq)
+ assert_raises(ValueError, x, sq, sq, sq, np.eye(3))
+ assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3))
+
+ def test_symmetry():
+ nsym = np.arange(9).reshape(3, 3)
+ sym = np.eye(3)
+ for x in (solve_continuous_are, solve_discrete_are):
+ assert_raises(ValueError, x, sym, sym, nsym, sym)
+ assert_raises(ValueError, x, sym, sym, sym, nsym)
+
+ def test_singularity():
+ sing = np.full((3, 3), 1e12)
+ sing[2, 2] -= 1
+ sq = np.eye(3)
+ for x in (solve_continuous_are, solve_discrete_are):
+ assert_raises(ValueError, x, sq, sq, sq, sq, sing)
+
+ assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing)
+
+ def test_finiteness():
+ nm = np.full((2, 2), np.nan)
+ sq = np.eye(2)
+ for x in (solve_continuous_are, solve_discrete_are):
+ assert_raises(ValueError, x, nm, sq, sq, sq)
+ assert_raises(ValueError, x, sq, nm, sq, sq)
+ assert_raises(ValueError, x, sq, sq, nm, sq)
+ assert_raises(ValueError, x, sq, sq, sq, nm)
+ assert_raises(ValueError, x, sq, sq, sq, sq, nm)
+ assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm)
+
+
+class TestSolveSylvester:
+ cases = [
+ # empty cases
+ (np.empty((0, 0)),
+ np.empty((0, 0)),
+ np.empty((0, 0))),
+ (np.empty((0, 0)),
+ np.empty((2, 2)),
+ np.empty((0, 2))),
+ (np.empty((2, 2)),
+ np.empty((0, 0)),
+ np.empty((2, 0))),
+ # a, b, c all real.
+ (np.array([[1, 2], [0, 4]]),
+ np.array([[5, 6], [0, 8]]),
+ np.array([[9, 10], [11, 12]])),
+ # a, b, c all real, 4x4. a and b have non-trivial 2x2 blocks in their
+ # quasi-triangular form.
+ (np.array([[1.0, 0, 0, 0],
+ [0, 1.0, 2.0, 0.0],
+ [0, 0, 3.0, -4],
+ [0, 0, 2, 5]]),
+ np.array([[2.0, 0, 0, 1.0],
+ [0, 1.0, 0.0, 0.0],
+ [0, 0, 1.0, -1],
+ [0, 0, 1, 1]]),
+ np.array([[1.0, 0, 0, 0],
+ [0, 1.0, 0, 0],
+ [0, 0, 1.0, 0],
+ [0, 0, 0, 1.0]])),
+ # a, b, c all complex.
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+ np.array([[-1.0, 2j], [3.0, 4.0]]),
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+ # a and b real; c complex.
+ (np.array([[1.0, 2.0], [3.0, 5.0]]),
+ np.array([[-1.0, 0], [3.0, 4.0]]),
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+ # a and c complex; b real.
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+ np.array([[-1.0, 0], [3.0, 4.0]]),
+ np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+ # a complex; b and c real.
+ (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+ np.array([[-1.0, 0], [3.0, 4.0]]),
+ np.array([[2.0, 2.0], [-1.0, 2.0]])),
+ # not square matrices, real
+ (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]),
+ np.array([[2, 3], [4, 5]]),
+ np.array([[1, 2], [3, 4], [5, 6]])),
+ # not square matrices, complex
+ (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]),
+ np.array([[2, 3], [4, 5-1j]]),
+ np.array([[1, 2j], [3, 4j], [5j, 6+7j]])),
+ ]
+
+ def check_case(self, a, b, c):
+ x = solve_sylvester(a, b, c)
+ assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c)
+
+ def test_cases(self):
+ for case in self.cases:
+ self.check_case(case[0], case[1], case[2])
+
+ def test_trivial(self):
+ a = np.array([[1.0, 0.0], [0.0, 1.0]])
+ b = np.array([[1.0]])
+ c = np.array([2.0, 2.0]).reshape(-1, 1)
+ x = solve_sylvester(a, b, c)
+ assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1))
+
+ # Feel free to adjust this to test fewer dtypes or random selections rather than
+ # the Cartesian product. It doesn't take very long to test all combinations,
+ # though, so we'll start there and trim it down as we see fit.
+ @pytest.mark.parametrize("dtype_a", dtypes)
+ @pytest.mark.parametrize("dtype_b", dtypes)
+ @pytest.mark.parametrize("dtype_q", dtypes)
+ @pytest.mark.parametrize("m", [0, 3])
+ @pytest.mark.parametrize("n", [0, 3])
+ def test_size_0(self, m, n, dtype_a, dtype_b, dtype_q):
+ if m == n != 0:
+ pytest.skip('m = n != 0 is not a case that needs to be tested here.')
+
+ rng = np.random.default_rng(598435298262546)
+
+ a = np.zeros((m, m), dtype=dtype_a)
+ b = np.zeros((n, n), dtype=dtype_b)
+ q = np.zeros((m, n), dtype=dtype_q)
+ res = solve_sylvester(a, b, q)
+
+ a = (rng.random((5, 5))*100).astype(dtype_a)
+ b = (rng.random((6, 6))*100).astype(dtype_b)
+ q = (rng.random((5, 6))*100).astype(dtype_q)
+ ref = solve_sylvester(a, b, q)
+
+ assert res.shape == (m, n)
+ assert res.dtype == ref.dtype
diff --git a/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_special_matrices.py b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..288b530c4a8392e047115df86a5ee9db102d1781
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/linalg/tests/test_special_matrices.py
@@ -0,0 +1,619 @@
+import pytest
+import numpy as np
+from numpy import arange, array, eye, copy, sqrt
+from numpy.testing import (assert_equal, assert_array_equal,
+ assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+
+from scipy.fft import fft
+from scipy.special import comb
+from scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft,
+ companion, block_diag,
+ helmert, hilbert, invhilbert, pascal, invpascal,
+ fiedler, fiedler_companion, eigvals,
+ convolution_matrix)
+from numpy.linalg import cond
+from scipy._lib._array_api import (make_xp_test_case, xp_assert_equal, xp_size,
+ xp_default_dtype)
+
+
+class TestToeplitz:
+
+ def test_basic(self):
+ y = toeplitz([1, 2, 3])
+ assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]])
+ y = toeplitz([1, 2, 3], [1, 4, 5])
+ assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]])
+
+ def test_complex_01(self):
+ data = (1.0 + arange(3.0)) * (1.0 + 1.0j)
+ x = copy(data)
+ t = toeplitz(x)
+ # Calling toeplitz should not change x.
+ assert_array_equal(x, data)
+ # According to the docstring, x should be the first column of t.
+ col0 = t[:, 0]
+ assert_array_equal(col0, data)
+ assert_array_equal(t[0, 1:], data[1:].conj())
+
+ def test_scalar_00(self):
+ """Scalar arguments still produce a 2D array."""
+ t = toeplitz(10)
+ assert_array_equal(t, [[10]])
+ t = toeplitz(10, 20)
+ assert_array_equal(t, [[10]])
+
+ def test_scalar_01(self):
+ c = array([1, 2, 3])
+ t = toeplitz(c, 1)
+ assert_array_equal(t, [[1], [2], [3]])
+
+ def test_scalar_02(self):
+ c = array([1, 2, 3])
+ t = toeplitz(c, array(1))
+ assert_array_equal(t, [[1], [2], [3]])
+
+ def test_scalar_03(self):
+ c = array([1, 2, 3])
+ t = toeplitz(c, array([1]))
+ assert_array_equal(t, [[1], [2], [3]])
+
+ def test_scalar_04(self):
+ r = array([10, 2, 3])
+ t = toeplitz(1, r)
+ assert_array_equal(t, [[1, 2, 3]])
+
+
+class TestHankel:
+ def test_basic(self):
+ y = hankel([1, 2, 3])
+ assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]])
+ y = hankel([1, 2, 3], [3, 4, 5])
+ assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+
+
+class TestCirculant:
+ def test_basic(self):
+ y = circulant([1, 2, 3])
+ assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]])
+
+
+class TestHadamard:
+
+ def test_basic(self):
+
+ y = hadamard(1)
+ assert_array_equal(y, [[1]])
+
+ y = hadamard(2, dtype=float)
+ assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]])
+
+ y = hadamard(4)
+ assert_array_equal(y, [[1, 1, 1, 1],
+ [1, -1, 1, -1],
+ [1, 1, -1, -1],
+ [1, -1, -1, 1]])
+
+ assert_raises(ValueError, hadamard, 0)
+ assert_raises(ValueError, hadamard, 5)
+
+
+class TestLeslie:
+
+ def test_bad_shapes(self):
+ assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5])
+ assert_raises(ValueError, leslie, [1, 2], [1, 2])
+ assert_raises(ValueError, leslie, [1], [])
+
+ def test_basic(self):
+ a = leslie([1, 2, 3], [0.25, 0.5])
+ expected = array([[1.0, 2.0, 3.0],
+ [0.25, 0.0, 0.0],
+ [0.0, 0.5, 0.0]])
+ assert_array_equal(a, expected)
+
+
+class TestCompanion:
+
+ def test_bad_shapes(self):
+ assert_raises(ValueError, companion, [0, 4, 5])
+ assert_raises(ValueError, companion, [1])
+ assert_raises(ValueError, companion, [])
+
+ def test_basic(self):
+ c = companion([1, 2, 3])
+ expected = array([
+ [-2.0, -3.0],
+ [1.0, 0.0]])
+ assert_array_equal(c, expected)
+
+ c = companion([2.0, 5.0, -10.0])
+ expected = array([
+ [-2.5, 5.0],
+ [1.0, 0.0]])
+ assert_array_equal(c, expected)
+
+ c = companion([(1.0, 2.0, 3.0),
+ (4.0, 5.0, 6.0)])
+ expected = array([
+ ([-2.00, -3.00],
+ [+1.00, +0.00]),
+ ([-1.25, -1.50],
+ [+1.00, +0.00])
+ ])
+ assert_array_equal(c, expected)
+
+
+@make_xp_test_case(block_diag)
+class TestBlockDiag:
+ def test_basic(self, xp):
+ dtype = xp.asarray(1).dtype
+ x = block_diag(xp.eye(2, dtype=dtype), xp.asarray([[1, 2], [3, 4], [5, 6]]),
+ xp.asarray([[1, 2, 3]]))
+ xp_assert_equal(x, xp.asarray([[1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 2, 0, 0, 0],
+ [0, 0, 3, 4, 0, 0, 0],
+ [0, 0, 5, 6, 0, 0, 0],
+ [0, 0, 0, 0, 1, 2, 3]]))
+
+ def test_dtype(self, xp):
+ x = block_diag(xp.asarray([[1.5]]))
+ assert x.dtype == xp_default_dtype(xp)
+
+ x = block_diag(xp.asarray([[True]]))
+ assert x.dtype == xp.bool
+
+ def test_mixed_dtypes(self, xp):
+ actual = block_diag(xp.asarray([[1.]]), xp.asarray([[1j]]))
+ desired = xp.asarray([[1, 0], [0, 1j]])
+ xp_assert_equal(actual, desired)
+
+ def test_scalar_and_1d_args(self, xp):
+ a = block_diag(xp.asarray(1))
+ assert a.shape == (1, 1)
+ xp_assert_equal(a, xp.asarray([[1]]))
+
+ a = block_diag(xp.asarray([2, 3]), xp.asarray(4))
+ xp_assert_equal(a, xp.asarray([[2, 3, 0], [0, 0, 4]]))
+
+ def test_no_args(self):
+ a = block_diag()
+ assert a.ndim == 2
+ assert a.nbytes == 0
+
+ def test_empty_matrix_arg(self, xp):
+ # regression test for gh-4596: check the shape of the result
+ # for empty matrix inputs. Empty matrices are no longer ignored
+ # (gh-4908) it is viewed as a shape (1, 0) matrix.
+ dtype = xp.asarray(1).dtype
+ a = block_diag(xp.asarray([[1, 0], [0, 1]]),
+ xp.asarray([], dtype=dtype),
+ xp.asarray([[2, 3], [4, 5], [6, 7]]))
+ xp_assert_equal(a, xp.asarray([[1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 2, 3],
+ [0, 0, 4, 5],
+ [0, 0, 6, 7]]))
+
+ @pytest.mark.skip_xp_backends("dask.array", reason="dask/dask#11800")
+ def test_zerosized_matrix_arg(self, xp):
+ # test for gh-4908: check the shape of the result for
+ # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0).
+ # note that [[]] takes shape (1,0)
+ dtype = xp.asarray(1).dtype
+ a = block_diag(xp.asarray([[1, 0], [0, 1]]),
+ xp.asarray([[]], dtype=dtype),
+ xp.asarray([[2, 3], [4, 5], [6, 7]]),
+ xp.zeros([0, 2], dtype=dtype))
+ xp_assert_equal(a, xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 2, 3, 0, 0],
+ [0, 0, 4, 5, 0, 0],
+ [0, 0, 6, 7, 0, 0]]))
+
+
+class TestHelmert:
+
+ def test_orthogonality(self):
+ for n in range(1, 7):
+ H = helmert(n, full=True)
+ Id = np.eye(n)
+ assert_allclose(H.dot(H.T), Id, atol=1e-12)
+ assert_allclose(H.T.dot(H), Id, atol=1e-12)
+
+ def test_subspace(self):
+ for n in range(2, 7):
+ H_full = helmert(n, full=True)
+ H_partial = helmert(n)
+ for U in H_full[1:, :].T, H_partial.T:
+ C = np.eye(n) - np.full((n, n), 1 / n)
+ assert_allclose(U.dot(U.T), C)
+ assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12)
+
+
+class TestHilbert:
+
+ def test_basic(self):
+ h3 = array([[1.0, 1/2., 1/3.],
+ [1/2., 1/3., 1/4.],
+ [1/3., 1/4., 1/5.]])
+ assert_array_almost_equal(hilbert(3), h3)
+
+ assert_array_equal(hilbert(1), [[1.0]])
+
+ h0 = hilbert(0)
+ assert_equal(h0.shape, (0, 0))
+
+
+class TestInvHilbert:
+
+ def test_basic(self):
+ invh1 = array([[1]])
+ assert_array_equal(invhilbert(1, exact=True), invh1)
+ assert_array_equal(invhilbert(1), invh1)
+
+ invh2 = array([[4, -6],
+ [-6, 12]])
+ assert_array_equal(invhilbert(2, exact=True), invh2)
+ assert_array_almost_equal(invhilbert(2), invh2)
+
+ invh3 = array([[9, -36, 30],
+ [-36, 192, -180],
+ [30, -180, 180]])
+ assert_array_equal(invhilbert(3, exact=True), invh3)
+ assert_array_almost_equal(invhilbert(3), invh3)
+
+ invh4 = array([[16, -120, 240, -140],
+ [-120, 1200, -2700, 1680],
+ [240, -2700, 6480, -4200],
+ [-140, 1680, -4200, 2800]])
+ assert_array_equal(invhilbert(4, exact=True), invh4)
+ assert_array_almost_equal(invhilbert(4), invh4)
+
+ invh5 = array([[25, -300, 1050, -1400, 630],
+ [-300, 4800, -18900, 26880, -12600],
+ [1050, -18900, 79380, -117600, 56700],
+ [-1400, 26880, -117600, 179200, -88200],
+ [630, -12600, 56700, -88200, 44100]])
+ assert_array_equal(invhilbert(5, exact=True), invh5)
+ assert_array_almost_equal(invhilbert(5), invh5)
+
+ invh17 = array([
+ [289, -41616, 1976760, -46124400, 629598060, -5540462928,
+ 33374693352, -143034400080, 446982500250, -1033026222800,
+ 1774926873720, -2258997839280, 2099709530100, -1384423866000,
+ 613101997800, -163493866080, 19835652870],
+ [-41616, 7990272, -426980160, 10627061760, -151103534400,
+ 1367702848512, -8410422724704, 36616806420480, -115857864064800,
+ 270465047424000, -468580694662080, 600545887119360,
+ -561522320049600, 372133135180800, -165537539406000,
+ 44316454993920, -5395297580640],
+ [1976760, -426980160, 24337869120, -630981792000, 9228108708000,
+ -85267724461920, 532660105897920, -2348052711713280,
+ 7504429831470000, -17664748409880000, 30818191841236800,
+ -39732544853164800, 37341234283298400, -24857330514030000,
+ 11100752642520000, -2982128117299200, 364182586693200],
+ [-46124400, 10627061760, -630981792000, 16826181120000,
+ -251209625940000, 2358021022156800, -14914482965141760,
+ 66409571644416000, -214015221119700000, 507295338950400000,
+ -890303319857952000, 1153715376477081600, -1089119333262870000,
+ 727848632044800000, -326170262829600000, 87894302404608000,
+ -10763618673376800],
+ [629598060, -151103534400, 9228108708000,
+ -251209625940000, 3810012660090000, -36210360321495360,
+ 231343968720664800, -1038687206500944000, 3370739732635275000,
+ -8037460526495400000, 14178080368737885600, -18454939322943942000,
+ 17489975175339030000, -11728977435138600000, 5272370630081100000,
+ -1424711708039692800, 174908803442373000],
+ [-5540462928, 1367702848512, -85267724461920, 2358021022156800,
+ -36210360321495360, 347619459086355456, -2239409617216035264,
+ 10124803292907663360, -33052510749726468000,
+ 79217210949138662400, -140362995650505067440,
+ 183420385176741672960, -174433352415381259200,
+ 117339159519533952000, -52892422160973595200,
+ 14328529177999196160, -1763080738699119840],
+ [33374693352, -8410422724704, 532660105897920,
+ -14914482965141760, 231343968720664800, -2239409617216035264,
+ 14527452132196331328, -66072377044391477760,
+ 216799987176909536400, -521925895055522958000,
+ 928414062734059661760, -1217424500995626443520,
+ 1161358898976091015200, -783401860847777371200,
+ 354015418167362952000, -96120549902411274240,
+ 11851820521255194480],
+ [-143034400080, 36616806420480, -2348052711713280,
+ 66409571644416000, -1038687206500944000, 10124803292907663360,
+ -66072377044391477760, 302045152202932469760,
+ -995510145200094810000, 2405996923185123840000,
+ -4294704507885446054400, 5649058909023744614400,
+ -5403874060541811254400, 3654352703663101440000,
+ -1655137020003255360000, 450325202737117593600,
+ -55630994283442749600],
+ [446982500250, -115857864064800, 7504429831470000,
+ -214015221119700000, 3370739732635275000, -33052510749726468000,
+ 216799987176909536400, -995510145200094810000,
+ 3293967392206196062500, -7988661659013106500000,
+ 14303908928401362270000, -18866974090684772052000,
+ 18093328327706957325000, -12263364009096700500000,
+ 5565847995255512250000, -1517208935002984080000,
+ 187754605706619279900],
+ [-1033026222800, 270465047424000, -17664748409880000,
+ 507295338950400000, -8037460526495400000, 79217210949138662400,
+ -521925895055522958000, 2405996923185123840000,
+ -7988661659013106500000, 19434404971634224000000,
+ -34894474126569249192000, 46141453390504792320000,
+ -44349976506971935800000, 30121928988527376000000,
+ -13697025107665828500000, 3740200989399948902400,
+ -463591619028689580000],
+ [1774926873720, -468580694662080,
+ 30818191841236800, -890303319857952000, 14178080368737885600,
+ -140362995650505067440, 928414062734059661760,
+ -4294704507885446054400, 14303908928401362270000,
+ -34894474126569249192000, 62810053427824648545600,
+ -83243376594051600326400, 80177044485212743068000,
+ -54558343880470209780000, 24851882355348879230400,
+ -6797096028813368678400, 843736746632215035600],
+ [-2258997839280, 600545887119360, -39732544853164800,
+ 1153715376477081600, -18454939322943942000, 183420385176741672960,
+ -1217424500995626443520, 5649058909023744614400,
+ -18866974090684772052000, 46141453390504792320000,
+ -83243376594051600326400, 110552468520163390156800,
+ -106681852579497947388000, 72720410752415168870400,
+ -33177973900974346080000, 9087761081682520473600,
+ -1129631016152221783200],
+ [2099709530100, -561522320049600, 37341234283298400,
+ -1089119333262870000, 17489975175339030000,
+ -174433352415381259200, 1161358898976091015200,
+ -5403874060541811254400, 18093328327706957325000,
+ -44349976506971935800000, 80177044485212743068000,
+ -106681852579497947388000, 103125790826848015808400,
+ -70409051543137015800000, 32171029219823375700000,
+ -8824053728865840192000, 1098252376814660067000],
+ [-1384423866000, 372133135180800,
+ -24857330514030000, 727848632044800000, -11728977435138600000,
+ 117339159519533952000, -783401860847777371200,
+ 3654352703663101440000, -12263364009096700500000,
+ 30121928988527376000000, -54558343880470209780000,
+ 72720410752415168870400, -70409051543137015800000,
+ 48142941226076592000000, -22027500987368499000000,
+ 6049545098753157120000, -753830033789944188000],
+ [613101997800, -165537539406000,
+ 11100752642520000, -326170262829600000, 5272370630081100000,
+ -52892422160973595200, 354015418167362952000,
+ -1655137020003255360000, 5565847995255512250000,
+ -13697025107665828500000, 24851882355348879230400,
+ -33177973900974346080000, 32171029219823375700000,
+ -22027500987368499000000, 10091416708498869000000,
+ -2774765838662800128000, 346146444087219270000],
+ [-163493866080, 44316454993920, -2982128117299200,
+ 87894302404608000, -1424711708039692800,
+ 14328529177999196160, -96120549902411274240,
+ 450325202737117593600, -1517208935002984080000,
+ 3740200989399948902400, -6797096028813368678400,
+ 9087761081682520473600, -8824053728865840192000,
+ 6049545098753157120000, -2774765838662800128000,
+ 763806510427609497600, -95382575704033754400],
+ [19835652870, -5395297580640, 364182586693200, -10763618673376800,
+ 174908803442373000, -1763080738699119840, 11851820521255194480,
+ -55630994283442749600, 187754605706619279900,
+ -463591619028689580000, 843736746632215035600,
+ -1129631016152221783200, 1098252376814660067000,
+ -753830033789944188000, 346146444087219270000,
+ -95382575704033754400, 11922821963004219300]
+ ])
+ assert_array_equal(invhilbert(17, exact=True), invh17)
+ assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12)
+
+ def test_inverse(self):
+ for n in range(1, 10):
+ a = hilbert(n)
+ b = invhilbert(n)
+ # The Hilbert matrix is increasingly badly conditioned,
+ # so take that into account in the test
+ c = cond(a)
+ assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c)
+
+
+class TestPascal:
+
+ cases = [
+ (1, array([[1]]), array([[1]])),
+ (2, array([[1, 1],
+ [1, 2]]),
+ array([[1, 0],
+ [1, 1]])),
+ (3, array([[1, 1, 1],
+ [1, 2, 3],
+ [1, 3, 6]]),
+ array([[1, 0, 0],
+ [1, 1, 0],
+ [1, 2, 1]])),
+ (4, array([[1, 1, 1, 1],
+ [1, 2, 3, 4],
+ [1, 3, 6, 10],
+ [1, 4, 10, 20]]),
+ array([[1, 0, 0, 0],
+ [1, 1, 0, 0],
+ [1, 2, 1, 0],
+ [1, 3, 3, 1]])),
+ ]
+
+ def check_case(self, n, sym, low):
+ assert_array_equal(pascal(n), sym)
+ assert_array_equal(pascal(n, kind='lower'), low)
+ assert_array_equal(pascal(n, kind='upper'), low.T)
+ assert_array_almost_equal(pascal(n, exact=False), sym)
+ assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low)
+ assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T)
+
+ def test_cases(self):
+ for n, sym, low in self.cases:
+ self.check_case(n, sym, low)
+
+ def test_big(self):
+ p = pascal(50)
+ assert p[-1, -1] == comb(98, 49, exact=True)
+
+ def test_threshold(self):
+ # Regression test. An early version of `pascal` returned an
+ # array of type np.uint64 for n=35, but that data type is too small
+ # to hold p[-1, -1]. The second assert_equal below would fail
+ # because p[-1, -1] overflowed.
+ p = pascal(34)
+ assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34")
+ p = pascal(35)
+ assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35")
+
+
+def test_invpascal():
+
+ def check_invpascal(n, kind, exact):
+ ip = invpascal(n, kind=kind, exact=exact)
+ p = pascal(n, kind=kind, exact=exact)
+ # Matrix-multiply ip and p, and check that we get the identity matrix.
+ # We can't use the simple expression e = ip.dot(p), because when
+ # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is
+ # np.int64. The product of those dtypes is np.float64, which loses
+ # precision when n is greater than 18. Instead we'll cast both to
+ # object arrays, and then multiply.
+ e = ip.astype(object).dot(p.astype(object))
+ assert_array_equal(e, eye(n), err_msg=f"n={n} kind={kind!r} exact={exact!r}")
+
+ kinds = ['symmetric', 'lower', 'upper']
+
+ ns = [1, 2, 5, 18]
+ for n in ns:
+ for kind in kinds:
+ for exact in [True, False]:
+ check_invpascal(n, kind, exact)
+
+ ns = [19, 34, 35, 50]
+ for n in ns:
+ for kind in kinds:
+ check_invpascal(n, kind, True)
+
+
+def test_dft():
+ m = dft(2)
+ expected = array([[1.0, 1.0], [1.0, -1.0]])
+ assert_array_almost_equal(m, expected)
+ m = dft(2, scale='n')
+ assert_array_almost_equal(m, expected/2.0)
+ m = dft(2, scale='sqrtn')
+ assert_array_almost_equal(m, expected/sqrt(2.0))
+
+ x = array([0, 1, 2, 3, 4, 5, 0, 1])
+ m = dft(8)
+ mx = m.dot(x)
+ fx = fft(x)
+ assert_array_almost_equal(mx, fx)
+
+
+@make_xp_test_case(fiedler)
+def test_fiedler(xp):
+ f = fiedler(xp.asarray([]))
+ assert xp_size(f) == 0
+ assert f.shape == (0, 0)
+
+ f = fiedler(xp.asarray([123.]))
+ xp_assert_equal(f, xp.asarray([[0.]]))
+
+ f = fiedler(xp.arange(1, 7))
+ des = xp.asarray([[0, 1, 2, 3, 4, 5],
+ [1, 0, 1, 2, 3, 4],
+ [2, 1, 0, 1, 2, 3],
+ [3, 2, 1, 0, 1, 2],
+ [4, 3, 2, 1, 0, 1],
+ [5, 4, 3, 2, 1, 0]])
+ xp_assert_equal(f, des)
+
+
+def test_fiedler_companion():
+ fc = fiedler_companion([])
+ assert_equal(fc.size, 0)
+ fc = fiedler_companion([1.])
+ assert_equal(fc.size, 0)
+ assert_equal(fc.shape, (0, 0))
+ fc = fiedler_companion([1., 2.])
+ assert_array_equal(fc, np.array([[-2.]]))
+ fc = fiedler_companion([1e-12, 2., 3.])
+ assert_array_almost_equal(fc, companion([1e-12, 2., 3.]))
+ with assert_raises(ValueError):
+ fiedler_companion([0, 1, 2])
+ fc = fiedler_companion([1., -16., 86., -176., 105.])
+ assert_array_almost_equal(eigvals(fc),
+ np.array([7., 5., 3., 1.]))
+
+
+class TestConvolutionMatrix:
+ """
+ Test convolution_matrix vs. numpy.convolve for various parameters.
+ """
+
+ def create_vector(self, n, cpx):
+ """Make a complex or real test vector of length n."""
+ x = np.linspace(-2.5, 2.2, n)
+ if cpx:
+ x = x + 1j*np.linspace(-1.5, 3.1, n)
+ return x
+
+ def test_bad_n(self):
+ # n must be a positive integer
+ with pytest.raises(ValueError, match='n must be a positive integer'):
+ convolution_matrix([1, 2, 3], 0)
+
+ def test_empty_first_arg(self):
+ # first arg must have at least one value
+ with pytest.raises(ValueError, match=r'len\(a\)'):
+ convolution_matrix([], 4)
+
+ def test_bad_mode(self):
+ # mode must be in ('full', 'valid', 'same')
+ with pytest.raises(ValueError, match='mode.*must be one of'):
+ convolution_matrix((1, 1), 4, mode='invalid argument')
+
+ @pytest.mark.parametrize('cpx', [False, True])
+ @pytest.mark.parametrize('na', [1, 2, 9])
+ @pytest.mark.parametrize('nv', [1, 2, 9])
+ @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same'])
+ def test_against_numpy_convolve(self, cpx, na, nv, mode):
+ a = self.create_vector(na, cpx)
+ v = self.create_vector(nv, cpx)
+ if mode is None:
+ y1 = np.convolve(v, a)
+ A = convolution_matrix(a, nv)
+ else:
+ y1 = np.convolve(v, a, mode)
+ A = convolution_matrix(a, nv, mode)
+ y2 = A @ v
+ assert_array_almost_equal(y1, y2)
+
+
+@pytest.mark.fail_slow(5) # `leslie` has an import in the function
+@pytest.mark.parametrize('f, args', [(circulant, ()),
+ (companion, ()),
+ (convolution_matrix, (5, 'same')),
+ (fiedler, ()),
+ (fiedler_companion, ()),
+ (hankel, (np.arange(9),)),
+ (leslie, (np.arange(9),)),
+ (toeplitz, (np.arange(9),)),
+ ])
+def test_batch(f, args):
+ rng = np.random.default_rng(283592436523456)
+ batch_shape = (2, 3)
+ m = 10
+ A = rng.random(batch_shape + (m,))
+
+ if f in {hankel}:
+ message = "Beginning in SciPy 1.19, multidimensional input will be..."
+ with pytest.warns(FutureWarning, match=message):
+ f(A, *args)
+ return
+
+ res = f(A, *args)
+ ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)])
+ ref = ref.reshape(A.shape[:-1] + ref.shape[-2:])
+ assert_allclose(res, ref)
diff --git a/.venv/lib/python3.12/site-packages/scipy/misc/__init__.py b/.venv/lib/python3.12/site-packages/scipy/misc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eb2f71afd54a67b54d7012347e5d1a983fac7be
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/misc/__init__.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+ "scipy.misc is deprecated and will be removed in 2.0.0",
+ DeprecationWarning,
+ stacklevel=2
+)
diff --git a/.venv/lib/python3.12/site-packages/scipy/misc/common.py b/.venv/lib/python3.12/site-packages/scipy/misc/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..e85acca3ac49d1cb84792bdf369cffe69a5d8ad8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/misc/common.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+ "scipy.misc.common is deprecated and will be removed in 2.0.0",
+ DeprecationWarning,
+ stacklevel=2
+)
diff --git a/.venv/lib/python3.12/site-packages/scipy/misc/doccer.py b/.venv/lib/python3.12/site-packages/scipy/misc/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..74cabc8c2fd14fe6424b8aad828c329ecdaee4b2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/misc/doccer.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+ "scipy.misc.doccer is deprecated and will be removed in 2.0.0",
+ DeprecationWarning,
+ stacklevel=2
+)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/__init__.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d766ca76fd85e7dd34b587a6b337dcd4c72968e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/__init__.py
@@ -0,0 +1,174 @@
+"""
+=========================================================
+Multidimensional image processing (:mod:`scipy.ndimage`)
+=========================================================
+
+.. currentmodule:: scipy.ndimage
+
+This package contains various functions for multidimensional image
+processing.
+
+
+Filters
+=======
+
+.. autosummary::
+ :toctree: generated/
+
+ convolve - Multidimensional convolution
+ convolve1d - 1-D convolution along the given axis
+ correlate - Multidimensional correlation
+ correlate1d - 1-D correlation along the given axis
+ gaussian_filter
+ gaussian_filter1d
+ gaussian_gradient_magnitude
+ gaussian_laplace
+ generic_filter - Multidimensional filter using a given function
+ generic_filter1d - 1-D generic filter along the given axis
+ generic_gradient_magnitude
+ generic_laplace
+ laplace - N-D Laplace filter based on approximate second derivatives
+ maximum_filter
+ maximum_filter1d
+ median_filter - Calculates a multidimensional median filter
+ minimum_filter
+ minimum_filter1d
+ percentile_filter - Calculates a multidimensional percentile filter
+ prewitt
+ rank_filter - Calculates a multidimensional rank filter
+ sobel
+ uniform_filter - Multidimensional uniform filter
+ uniform_filter1d - 1-D uniform filter along the given axis
+ vectorized_filter
+
+Fourier filters
+===============
+
+.. autosummary::
+ :toctree: generated/
+
+ fourier_ellipsoid
+ fourier_gaussian
+ fourier_shift
+ fourier_uniform
+
+Interpolation
+=============
+
+.. autosummary::
+ :toctree: generated/
+
+ affine_transform - Apply an affine transformation
+ geometric_transform - Apply an arbitrary geometric transform
+ map_coordinates - Map input array to new coordinates by interpolation
+ rotate - Rotate an array
+ shift - Shift an array
+ spline_filter
+ spline_filter1d
+ zoom - Zoom an array
+
+Measurements
+============
+
+.. autosummary::
+ :toctree: generated/
+
+ center_of_mass - The center of mass of the values of an array at labels
+ extrema - Min's and max's of an array at labels, with their positions
+ find_objects - Find objects in a labeled array
+ histogram - Histogram of the values of an array, optionally at labels
+ label - Label features in an array
+ labeled_comprehension
+ maximum
+ maximum_position
+ mean - Mean of the values of an array at labels
+ median
+ minimum
+ minimum_position
+ standard_deviation - Standard deviation of an N-D image array
+ sum_labels - Sum of the values of the array
+ value_indices - Find indices of each distinct value in given array
+ variance - Variance of the values of an N-D image array
+ watershed_ift
+
+Morphology
+==========
+
+.. autosummary::
+ :toctree: generated/
+
+ binary_closing
+ binary_dilation
+ binary_erosion
+ binary_fill_holes
+ binary_hit_or_miss
+ binary_opening
+ binary_propagation
+ black_tophat
+ distance_transform_bf
+ distance_transform_cdt
+ distance_transform_edt
+ generate_binary_structure
+ grey_closing
+ grey_dilation
+ grey_erosion
+ grey_opening
+ iterate_structure
+ morphological_gradient
+ morphological_laplace
+ white_tophat
+
+"""
+
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+# bring in the public functionality from private namespaces
+
+# mypy: ignore-errors
+
+from ._support_alternative_backends import *
+
+# adjust __all__ and do not leak implementation details
+from . import _support_alternative_backends
+__all__ = _support_alternative_backends.__all__
+del _support_alternative_backends, _ndimage_api, _delegators # noqa: F821 # pyrefly:ignore[unbound-name]
+
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import filters
+from . import fourier
+from . import interpolation
+from . import measurements
+from . import morphology
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..fd9fe54cbaa41abf6938e39f9802cee6b9edef76
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..6e9a687f6d62b52aabc8e77f1329a4dd5fdefbef
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_delegators.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..bac1286a56c0937cc29ee926de4c77fbfb79c77f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_delegators.py
@@ -0,0 +1,303 @@
+"""Delegators for alternative backends in scipy.ndimage.
+
+The signature of `func_signature` must match the signature of ndimage.func.
+The job of a `func_signature` is to know which arguments of `ndimage.func`
+are arrays.
+
+* signatures are generated by
+
+--------------
+import inspect
+from scipy import ndimage
+
+names = [x for x in dir(ndimage) if not x.startswith('_')]
+objs = [getattr(ndimage, name) for name in names]
+funcs = [obj for obj in objs if inspect.isroutine(obj)]
+
+for func in funcs:
+ sig = inspect.signature(func)
+ print(f"def {func.__name__}_signature{sig}:\n\tpass\n\n")
+---------------
+
+* which arguments to delegate on: manually trawled the documentation for
+ array-like and array arguments
+
+"""
+import numpy as np
+from scipy._lib._array_api import array_namespace
+from scipy.ndimage._ni_support import _skip_if_dtype
+
+
+def affine_transform_signature(
+ input, matrix, offset=0.0, output_shape=None, output=None, *args, **kwds
+):
+ return array_namespace(input, matrix, _skip_if_dtype(output))
+
+
+def binary_closing_signature(
+ input, structure=None, iterations=1, output=None, *args, **kwds
+):
+ return array_namespace(input, structure, _skip_if_dtype(output))
+
+binary_opening_signature = binary_closing_signature
+
+
+def binary_dilation_signature(
+ input, structure=None, iterations=1, mask=None, output=None, *args, **kwds
+):
+ return array_namespace(input, structure, _skip_if_dtype(output), mask)
+
+binary_erosion_signature = binary_dilation_signature
+
+
+def binary_fill_holes_signature(
+ input, structure=None, output=None, origin=0, *args, **kwargs
+):
+ return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def label_signature(input, structure=None, output=None, origin=0):
+ return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def binary_hit_or_miss_signature(
+ input, structure1=None, structure2=None, output=None, *args, **kwds
+):
+ return array_namespace(input, structure1, structure2, _skip_if_dtype(output))
+
+
+def binary_propagation_signature(
+ input, structure=None, mask=None, output=None, *args, **kwds
+):
+ return array_namespace(input, structure, mask, _skip_if_dtype(output))
+
+
+def convolve_signature(input, weights, output=None, *args, **kwds):
+ return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate_signature = convolve_signature
+
+
+def convolve1d_signature(input, weights, axis=-1, output=None, *args, **kwds):
+ return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate1d_signature = convolve1d_signature
+
+
+def distance_transform_bf_signature(
+ input, metric='euclidean', sampling=None, return_distances=True,
+ return_indices=False, distances=None, indices=None
+):
+ return array_namespace(input, distances, indices)
+
+
+def distance_transform_cdt_signature(
+ input, metric='chessboard', return_distances=True, return_indices=False,
+ distances=None, indices=None
+):
+ return array_namespace(input, distances, indices)
+
+
+def distance_transform_edt_signature(
+ input, sampling=None, return_distances=True, return_indices=False,
+ distances=None, indices=None
+):
+ return array_namespace(input, distances, indices)
+
+
+def find_objects_signature(input, max_label=0):
+ return array_namespace(input)
+
+
+def fourier_ellipsoid_signature(input, size, n=-1, axis=-1, output=None):
+ return array_namespace(input, _skip_if_dtype(output))
+
+fourier_uniform_signature = fourier_ellipsoid_signature
+
+
+def fourier_gaussian_signature(input, sigma, n=-1, axis=-1, output=None):
+ return array_namespace(input, _skip_if_dtype(output))
+
+def fourier_shift_signature(input, shift, n=-1, axis=-1, output=None):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter_signature(input, sigma, order=0, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter1d_signature(
+ input, sigma, axis=-1, order=0, output=None, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_gradient_magnitude_signature(input, sigma, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+gaussian_laplace_signature = gaussian_gradient_magnitude_signature
+
+
+def generate_binary_structure_signature(rank, connectivity):
+ # XXX: no input arrays; always return numpy
+ return np
+
+
+def generic_filter_signature(
+ input, function, size=None, footprint=None, output=None, *args, **kwds
+):
+ # XXX: function LowLevelCallable w/backends
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def generic_filter1d_signature(
+ input, function, filter_size, axis=-1, output=None, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_gradient_magnitude_signature(
+ input, derivative, output=None, *args, **kwds
+):
+ # XXX: function LowLevelCallable w/backends
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_laplace_signature(input, derivative2, output=None, *args, **kwds):
+ # XXX: function LowLevelCallable w/backends
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def geometric_transform_signature(
+ input, mapping, output_shape=None, output=None, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def histogram_signature(input, min, max, bins, labels=None, index=None):
+ return array_namespace(input, labels)
+
+
+def iterate_structure_signature(structure, iterations, origin=None):
+ return array_namespace(structure)
+
+
+def labeled_comprehension_signature(input, labels, *args, **kwds):
+ return array_namespace(input, labels)
+
+
+def laplace_signature(input, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def map_coordinates_signature(input, coordinates, output=None, *args, **kwds):
+ return array_namespace(input, coordinates, _skip_if_dtype(output))
+
+
+def maximum_filter1d_signature(input, size, axis=-1, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+minimum_filter1d_signature = maximum_filter1d_signature
+uniform_filter1d_signature = maximum_filter1d_signature
+
+
+def maximum_signature(input, labels=None, index=None):
+ return array_namespace(input, labels, index)
+
+minimum_signature = maximum_signature
+median_signature = maximum_signature
+mean_signature = maximum_signature
+variance_signature = maximum_signature
+standard_deviation_signature = maximum_signature
+sum_labels_signature = maximum_signature
+sum_signature = maximum_signature # ndimage.sum is sum_labels
+
+maximum_position_signature = maximum_signature
+minimum_position_signature = maximum_signature
+
+extrema_signature = maximum_signature
+center_of_mass_signature = extrema_signature
+
+
+def median_filter_signature(
+ input, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+minimum_filter_signature = median_filter_signature
+maximum_filter_signature = median_filter_signature
+
+
+def morphological_gradient_signature(
+ input, size=None, footprint=None, structure=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, structure, _skip_if_dtype(output))
+
+morphological_laplace_signature = morphological_gradient_signature
+white_tophat_signature = morphological_gradient_signature
+black_tophat_signature = morphological_gradient_signature
+grey_closing_signature = morphological_gradient_signature
+grey_dilation_signature = morphological_gradient_signature
+grey_erosion_signature = morphological_gradient_signature
+grey_opening_signature = morphological_gradient_signature
+
+
+def percentile_filter_signature(
+ input, percentile, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def prewitt_signature(input, axis=-1, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+sobel_signature = prewitt_signature
+
+
+def rank_filter_signature(
+ input, rank, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def rotate_signature(
+ input, angle, axes=(1, 0), reshape=True, output=None , *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def shift_signature(input, shift, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter_signature(input, order=3, output=np.float64, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter1d_signature(
+ input, order=3, axis=-1, output=np.float64, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def uniform_filter_signature(input, size=3, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def value_indices_signature(arr, *args, **kwds):
+ return array_namespace(arr)
+
+
+def vectorized_filter_signature(
+ input, function, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def watershed_ift_signature(input, markers, structure=None, output=None):
+ return array_namespace(input, markers, structure, _skip_if_dtype(output))
+
+
+def zoom_signature(input, zoom, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_filters.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..83a8f4803869b2f2656e6e9e2e381e2874fb6999
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_filters.py
@@ -0,0 +1,2446 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+from collections.abc import Iterable
+import numbers
+import warnings
+import numpy as np
+import operator
+import math
+
+from scipy._lib._util import normalize_axis_index
+from scipy._lib._array_api import array_namespace, is_cupy, xp_size
+from . import _ni_support
+from . import _nd_image
+from . import _ni_docstrings
+from . import _rank_filter_1d
+
+__all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter',
+ 'prewitt', 'sobel', 'generic_laplace', 'laplace',
+ 'gaussian_laplace', 'generic_gradient_magnitude',
+ 'gaussian_gradient_magnitude', 'correlate', 'convolve',
+ 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+ 'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+ 'rank_filter', 'median_filter', 'percentile_filter',
+ 'generic_filter1d', 'generic_filter', 'vectorized_filter']
+
+
+def _vectorized_filter_iv(input, function, size, footprint, output, mode, cval, origin,
+ axes, batch_memory):
+ xp = array_namespace(input, footprint, output)
+
+ # vectorized_filter input validation and standardization
+ input = xp.asarray(input)
+
+ if not callable(function):
+ raise ValueError("`function` must be a callable.")
+
+ if size is None and footprint is None:
+ raise ValueError("Either `size` or `footprint` must be provided.")
+
+ if size is not None and footprint is not None:
+ raise ValueError("Either `size` or `footprint` may be provided, not both.")
+
+ if axes is None:
+ axes = tuple(range(-input.ndim, 0))
+ elif np.isscalar(axes):
+ axes = (axes,)
+ n_axes = len(axes)
+ n_batch = input.ndim - n_axes
+
+ if n_axes > input.ndim:
+ message = ("The length of `axes` may not exceed the dimensionality of `input`"
+ "(`input.ndim`).")
+ raise ValueError(message)
+
+ # Either footprint or size must be provided
+ footprinted_function = function
+ if size is not None:
+ # If provided, size must be an integer or tuple of integers.
+ size = (size,)*n_axes if np.isscalar(size) else tuple(size)
+ valid = [xp.isdtype(xp.asarray(i).dtype, 'integral') and i > 0 for i in size]
+ if not all(valid):
+ raise ValueError("All elements of `size` must be positive integers.")
+ else:
+ # If provided, `footprint` must be array-like
+ footprint = xp.asarray(footprint, dtype=xp.bool)
+ size = footprint.shape
+ def footprinted_function(input, *args, axis=-1, **kwargs):
+ return function(input[..., footprint], *args, axis=-1, **kwargs)
+
+ # And by now, the dimensionality of the footprint must equal the number of axes
+ if n_axes != len(size):
+ message = ("`axes` must be compatible with the dimensionality "
+ "of the window specified by `size` or `footprint`.")
+ raise ValueError(message)
+
+ # If this is not *equal* to the dimensionality of `input`, then `axes`
+ # must be a provided tuple, and its length must equal the core dimensionality.
+ elif n_axes < input.ndim:
+ if axes is None:
+ message = ("`axes` must be provided if the dimensionality of the window "
+ "(`len(size)` or `footprint.ndim`) does not equal the number "
+ "of axes of `input` (`input.ndim`).")
+ raise ValueError(message)
+ else:
+ axes = tuple(range(-n_axes, 0)) if axes is None else axes
+
+ axes = (axes,) if np.isscalar(axes) else axes
+
+ # If `origin` is provided, then it must be "broadcastable" to a tuple with length
+ # equal to the core dimensionality.
+ if origin is None:
+ origin = (0,) * n_axes
+ else:
+ origin = (origin,)*n_axes if np.isscalar(origin) else tuple(origin)
+ integral = [xp.isdtype(xp.asarray(i).dtype, 'integral') for i in origin]
+ if not all(integral):
+ raise ValueError("All elements of `origin` must be integers.")
+ if not len(origin) == n_axes:
+ message = ("`origin` must be an integer or tuple of integers with length "
+ "equal to the number of axes.")
+ raise ValueError(message)
+
+ # mode must be one of the allowed strings, and we should convert it to the
+ # value required by `np.pad`/`cp.pad` here.
+ valid_modes = {'reflect', 'constant', 'nearest', 'mirror', 'wrap',
+ 'grid-mirror', 'grid-constant', 'grid-wrap', 'valid'}
+ if mode not in valid_modes:
+ raise ValueError(f"`mode` must be one of {valid_modes}.")
+ mode_map = {'nearest': 'edge', 'reflect': 'symmetric', 'mirror': 'reflect',
+ 'grid-mirror': 'reflect', 'grid-constant': 'constant',
+ 'grid-wrap': 'wrap'}
+ mode = mode_map.get(mode, mode)
+
+ if mode == 'valid' and any(origin):
+ raise ValueError("`mode='valid'` is incompatible with use of `origin`.")
+
+ if cval is None:
+ cval = 0.0
+ elif mode != 'constant':
+ raise ValueError("Use of `cval` is compatible only with `mode='constant'`.")
+
+ # `cval` must be a scalar or "broadcastable" to a tuple with the same
+ # dimensionality of `input`. (Full input validation done by `np.pad`/`cp.pad`.)
+ if not xp.isdtype(xp.asarray(cval).dtype, 'numeric'):
+ raise ValueError("`cval` must include only numbers.")
+
+ # `batch_memory` must be a positive number.
+ temp = xp.asarray(batch_memory)
+ if temp.ndim != 0 or (not xp.isdtype(temp.dtype, 'numeric')) or temp <= 0:
+ raise ValueError("`batch_memory` must be positive number.")
+
+ # For simplicity, work with `axes` at the end.
+ working_axes = tuple(range(-n_axes, 0))
+ input = xp.moveaxis(input, axes, working_axes)
+ output = (xp.moveaxis(output, axes, working_axes)
+ if output is not None else output)
+
+ # Wrap the function to limit maximum memory usage, deal with `footprint`,
+ # and populate `output`. The latter requires some verbosity because we
+ # don't know the output dtype.
+ def wrapped_function(view, output=output):
+ kwargs = {'axis': working_axes}
+
+ if working_axes == ():
+ return footprinted_function(xp.asarray(view), **kwargs)
+
+ # for now, assume we only have to iterate over zeroth axis
+ chunk_size = math.prod(view.shape[1:]) * view.dtype.itemsize
+ slices_per_batch = min(view.shape[0], batch_memory // chunk_size)
+ if slices_per_batch < 1:
+ raise ValueError("`batch_memory` is insufficient for minimum chunk size.")
+
+ elif slices_per_batch == view.shape[0]:
+ if output is None:
+ return footprinted_function(xp.asarray(view), **kwargs)
+ else:
+ output[...] = footprinted_function(xp.asarray(view), **kwargs)
+ return output
+
+ for i in range(0, view.shape[0], slices_per_batch):
+ i2 = min(i + slices_per_batch, view.shape[0])
+ if output is None:
+ # Look at the dtype before allocating the array. (In a follow-up, we
+ # can also look at the shape to support non-scalar elements.)
+ temp = footprinted_function(xp.asarray(view[i:i2]), **kwargs)
+ output = xp.empty(view.shape[:-n_axes], dtype=temp.dtype)
+ output[i:i2, ...] = temp
+ else:
+ output[i:i2, ...] = footprinted_function(xp.asarray(view[i:i2]),
+ **kwargs)
+ return output
+
+ return (input, wrapped_function, size, mode, cval, origin,
+ working_axes, axes, n_axes, n_batch, xp)
+
+
+@_ni_docstrings.docfiller
+def vectorized_filter(input, function, *, size=None, footprint=None, output=None,
+ mode='reflect', cval=None, origin=None, axes=None,
+ batch_memory=2**30):
+ """Filter an array with a vectorized Python callable as the kernel.
+
+ Parameters
+ ----------
+ %(input)s
+ function : callable
+ Kernel to apply over a window centered at each element of `input`.
+ Callable must have signature::
+
+ function(window: ndarray, *, axis: int | tuple) -> scalar
+
+ where ``axis`` specifies the axis (or axes) of ``window`` along which
+ the filter function is evaluated.
+ size : scalar or tuple, optional
+ See `footprint` below. Ignored if `footprint` is given.
+ footprint : array, optional
+ Either `size` or `footprint` must be defined. `size` gives
+ the shape that is taken from the input array, at every element
+ position, to define the input to the filter function.
+ `footprint` is a boolean array that specifies (implicitly) a
+ shape, but also which of the elements within this shape will get
+ passed to the filter function. Thus ``size=(n, m)`` is equivalent
+ to ``footprint=np.ones((n, m))``.
+ We adjust `size` to the number of dimensions indicated by `axes`.
+ For instance, if `axes` is ``(0, 2, 1)`` and ``n`` is passed for ``size``,
+ then the effective `size` is ``(n, n, n)``.
+ output : array, optional
+ The array in which to place the output. By default, an array of the dtype
+ returned by `function` will be created.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the input array is extended
+ beyond its boundaries. Default is 'reflect'. Behavior for each valid
+ value is as follows:
+
+ 'reflect' (`d c b a | a b c d | d c b a`)
+ The input is extended by reflecting about the edge of the last
+ pixel. This mode is also sometimes referred to as half-sample
+ symmetric.
+
+ 'constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter.
+
+ 'nearest' (`a a a a | a b c d | d d d d`)
+ The input is extended by replicating the last pixel.
+
+ 'mirror' (`d c b | a b c d | c b a`)
+ The input is extended by reflecting about the center of the last
+ pixel. This mode is also sometimes referred to as whole-sample
+ symmetric.
+
+ 'wrap' (`a b c d | a b c d | a b c d`)
+ The input is extended by wrapping around to the opposite edge.
+
+ 'valid' (`| a b c d |`)
+ The input is not extended; rather, the output shape is reduced depending
+ on the window size according to the following calculation::
+
+ window_size = np.asarray(size if size is not None else footprint.shape)
+ output_shape = np.asarray(input.shape)
+ output_shape[np.asarray(axes)] -= (window_size - 1)
+
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int, optional
+ If None, `input` is filtered along all axes. Otherwise, `input` is filtered
+ along the specified axes. When `axes` is specified, the dimensionality of
+ `footprint` and the length of any tuples used for `size` or `origin` must
+ match the length of `axes`. The ith axis of `footprint` and the ith element
+ in these tuples corresponds to the ith element of `axes`.
+ batch_memory : int, default: 2**30
+ The maximum number of bytes occupied by data in the ``window``
+ array passed to ``function``.
+
+ Returns
+ -------
+ output : ndarray
+ Filtered array. The dtype is the output dtype of `function`. If `function` is
+ scalar-valued when applied to a single window, the shape of the output is that
+ of `input` (unless ``mode=='valid'``; see `mode` documentation). If `function`
+ is multi-valued when applied to a single window, the placement of the
+ corresponding dimensions within the output shape depends entirely on the
+ behavior of `function`; see Examples.
+
+ See Also
+ --------
+ scipy.ndimage.generic_filter
+
+ Notes
+ -----
+ This function works by padding `input` according to `mode`, then calling the
+ provided `function` on chunks of a sliding window view over the padded array.
+ This approach is very simple and flexible, and so the function has many features
+ not offered by some other filter functions (e.g. memory control, ``float16``
+ and complex dtype support, and any NaN-handling features provided by the
+ `function` argument).
+
+ However, this brute-force approach may perform considerable redundant work.
+ Use a specialized filter (e.g. `minimum_filter` instead of this function with
+ `numpy.min` as the callable; `uniform_filter` instead of this function with
+ `numpy.mean` as the callable) when possible, as it may use a more efficient
+ algorithm.
+
+ When a specialized filter is not available, this function is ideal when `function`
+ is a vectorized, pure-Python callable. Even better performance may be possible
+ by passing a `scipy.LowLevelCallable` to `generic_filter`. `generic_filter` may
+ also be preferred for expensive callables with large filter footprints and
+ callables that are not vectorized (i.e. those without ``axis`` support).
+
+ This function does not provide the ``extra_arguments`` or ``extra_keywords``
+ arguments provided by some `ndimage` functions. There are two reasons:
+
+ - The passthrough functionality can be achieved by the user: simply wrap the
+ original callable in another function that provides the required arguments;
+ e.g., ``function=lambda input, axis: function(input, *extra_arguments, axis=axis, **extra_keywords)``.
+ - There are use cases for `function` to be passed additional *sliding-window data*
+ to `function` besides `input`. This is not yet implemented, but we reserve
+ these argument names for such a feature, which would add capability rather than
+ providing a duplicate interface to existing capability.
+
+ Examples
+ --------
+ Suppose we wish to perform a median filter with even window size on a ``float16``
+ image. Furthermore, the image has NaNs that we wish to be ignored (and effectively
+ removed by the filter). `median_filter` does not support ``float16`` data, its
+ behavior when NaNs are present is not defined, and for even window sizes, it does
+ not return the usual sample median - the average of the two middle elements. This
+ would be an excellent use case for `vectorized_filter` with
+ ``function=np.nanmedian``, which supports the required interface: it accepts a
+ data array of any shape as the first positional argument, and tuple of axes as
+ keyword argument ``axis``.
+
+ >>> import numpy as np
+ >>> from scipy import datasets, ndimage
+ >>> from scipy.ndimage import vectorized_filter
+ >>> import matplotlib.pyplot as plt
+ >>> ascent = ndimage.zoom(datasets.ascent(), 0.5).astype(np.float16)
+ >>> ascent[::16, ::16] = np.nan
+ >>> result = vectorized_filter(ascent, function=np.nanmedian, size=4)
+
+ Plot the original and filtered images.
+
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ Another need satisfied by `vectorized_filter` is to perform multi-output
+ filters. For instance, suppose we wish to filter an image according to the 25th
+ and 75th percentiles in addition to the median. We could perform the three
+ filters separately.
+
+ >>> ascent = ndimage.zoom(datasets.ascent(), 0.5)
+ >>> def get_quantile_fun(p):
+ ... return lambda x, axis: np.quantile(x, p, axis=axis)
+ >>> ref1 = vectorized_filter(ascent, get_quantile_fun(0.25), size=4)
+ >>> ref2 = vectorized_filter(ascent, get_quantile_fun(0.50), size=4)
+ >>> ref3 = vectorized_filter(ascent, get_quantile_fun(0.75), size=4)
+ >>> ref = np.stack([ref1, ref2, ref3])
+
+ However, `vectorized_filter` also supports filters that return multiple outputs
+ as long as `output` is unspecified and `batch_memory` is sufficiently high to
+ perform the calculation in a single chunk.
+
+ >>> def quartiles(x, axis):
+ ... return np.quantile(x, [0.25, 0.50, 0.75], axis=axis)
+ >>> res = vectorized_filter(ascent, quartiles, size=4, batch_memory=np.inf)
+ >>> np.all(np.isclose(res, ref))
+ np.True_
+
+ The placement of the additional dimension(s) corresponding with multiple outputs
+ is at the discretion of `function`. `quartiles` happens to prepend one dimension
+ corresponding with the three outputs simply because that is the behavior of
+ `np.quantile`:
+
+ >>> res.shape == (3,) + ascent.shape
+ True
+
+ If we wished for this dimension to be appended:
+
+ >>> def quartiles(x, axis):
+ ... return np.moveaxis(np.quantile(x, [0.25, 0.50, 0.75], axis=axis), 0, -1)
+ >>> res = vectorized_filter(ascent, quartiles, size=4, batch_memory=np.inf)
+ >>> res.shape == ascent.shape + (3,)
+ True
+
+ Suppose we wish to implment a "mode" filter - a filter that selects the most
+ frequently occuring value within the window. A simple (but rather slow)
+ approach is to use `generic_filter` with `scipy.stats.mode`.
+
+ >>> from scipy import stats
+ >>> rng = np.random.default_rng(3195824598724609246)
+ >>> input = rng.integers(255, size=(50, 50)).astype(np.uint8)
+ >>> def simple_mode(input):
+ ... return stats.mode(input, axis=None).mode
+ >>> ref = ndimage.generic_filter(input, simple_mode, size=5)
+
+ If speed is important, `vectorized_filter` can take advantage of the performance
+ benefit of a vectorized callable.
+
+ >>> def vectorized_mode(x, axis=(-1,)):
+ ... n_axes = 1 if np.isscalar(axis) else len(axis)
+ ... x = np.moveaxis(x, axis, tuple(range(-n_axes, 0)))
+ ... x = np.reshape(x, x.shape[:-n_axes] + (-1,))
+ ... y = np.sort(x, axis=-1)
+ ... i = np.concatenate([np.ones(y.shape[:-1] + (1,), dtype=bool),
+ ... y[..., :-1] != y[..., 1:]], axis=-1)
+ ... indices = np.arange(y.size)[i.ravel()]
+ ... counts = np.diff(indices, append=y.size)
+ ... counts = np.reshape(np.repeat(counts, counts), y.shape)
+ ... k = np.argmax(counts, axis=-1, keepdims=True)
+ ... return np.take_along_axis(y, k, axis=-1)[..., 0]
+ >>> res = vectorized_filter(input, vectorized_mode, size=5)
+ >>> np.all(res == ref)
+ np.True_
+
+ Depending on the machine, the `vectorized_filter` version may be as much as
+ 100x faster.
+
+ """ # noqa: E501
+
+ (input, function, size, mode, cval, origin, working_axes, axes, n_axes, n_batch, xp
+ ) = _vectorized_filter_iv(input, function, size, footprint, output, mode, cval,
+ origin, axes, batch_memory)
+
+ # `np.pad`/`cp.pad` raises with these sorts of cases, but the best result is
+ # probably to return the original array. It could be argued that we should call
+ # the function on the empty array with `axis=None` just to determine the output
+ # dtype, but I can also see rationale against that.
+ if xp_size(input) == 0:
+ return xp.asarray(input)
+
+ # This seems to be defined.
+ if input.ndim == 0 and size == ():
+ return xp.asarray(function(input) if footprint is None
+ else function(input[footprint]))
+
+ if is_cupy(xp):
+ # CuPy is the only GPU backend that has `pad` (with all modes)
+ # and `sliding_window_view`. An enhancement would be to use
+ # no-copy conversion to CuPy whenever the data is on the GPU.
+ cp = xp # let there be no ambiguity!
+ swv = cp.lib.stride_tricks.sliding_window_view
+ pad = cp.pad
+ else:
+ # Try to perform no-copy conversion to NumPy for padding and
+ # `sliding_window_view`. (If that fails, fine - for now, the only
+ # GPU backend we support is CuPy.)
+ swv = np.lib.stride_tricks.sliding_window_view
+ pad = np.pad
+ input = np.asarray(input)
+ cval = np.asarray(cval)[()] if mode == 'constant' else None
+
+ # Border the image according to `mode` and `offset`.
+ if mode != 'valid':
+ kwargs = {'constant_values': cval} if mode == 'constant' else {}
+ borders = tuple((i//2 + j, (i-1)//2 - j) for i, j in zip(size, origin))
+ bordered_input = pad(input, ((0, 0),)*n_batch + borders, mode=mode, **kwargs)
+ else:
+ bordered_input = input
+
+ # Evaluate function with sliding window view. Function is already wrapped to
+ # manage memory, deal with `footprint`, populate `output`, etc.
+ view = swv(bordered_input, size, working_axes)
+ res = function(view)
+
+ # move working_axes back to original positions
+ return xp.moveaxis(res, working_axes, axes)
+
+
+def _invalid_origin(origin, lenw):
+ return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2)
+
+
+def _complex_via_real_components(func, input, weights, output, cval, **kwargs):
+ """Complex convolution via a linear combination of real convolutions."""
+ complex_input = input.dtype.kind == 'c'
+ complex_weights = weights.dtype.kind == 'c'
+ if complex_input and complex_weights:
+ # real component of the output
+ func(input.real, weights.real, output=output.real,
+ cval=np.real(cval), **kwargs)
+ output.real -= func(input.imag, weights.imag, output=None,
+ cval=np.imag(cval), **kwargs)
+ # imaginary component of the output
+ func(input.real, weights.imag, output=output.imag,
+ cval=np.real(cval), **kwargs)
+ output.imag += func(input.imag, weights.real, output=None,
+ cval=np.imag(cval), **kwargs)
+ elif complex_input:
+ func(input.real, weights, output=output.real, cval=np.real(cval),
+ **kwargs)
+ func(input.imag, weights, output=output.imag, cval=np.imag(cval),
+ **kwargs)
+ else:
+ if np.iscomplexobj(cval):
+ raise ValueError("Cannot provide a complex-valued cval when the "
+ "input is real.")
+ func(input, weights.real, output=output.real, cval=cval, **kwargs)
+ func(input, weights.imag, output=output.imag, cval=cval, **kwargs)
+ return output
+
+
+def _expand_origin(ndim_image, axes, origin):
+ num_axes = len(axes)
+ origins = _ni_support._normalize_sequence(origin, num_axes)
+ if num_axes < ndim_image:
+ # set origin = 0 for any axes not being filtered
+ origins_temp = [0,] * ndim_image
+ for o, ax in zip(origins, axes):
+ origins_temp[ax] = o
+ origins = origins_temp
+ return origins
+
+
+def _expand_footprint(ndim_image, axes, footprint,
+ footprint_name="footprint"):
+ num_axes = len(axes)
+ if num_axes < ndim_image:
+ if footprint.ndim != num_axes:
+ raise RuntimeError(f"{footprint_name}.ndim ({footprint.ndim}) "
+ f"must match len(axes) ({num_axes})")
+
+ footprint = np.expand_dims(
+ footprint,
+ tuple(ax for ax in range(ndim_image) if ax not in axes)
+ )
+ return footprint
+
+
+def _expand_mode(ndim_image, axes, mode):
+ num_axes = len(axes)
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ # set mode = 'constant' for any axes not being filtered
+ modes = _ni_support._normalize_sequence(mode, num_axes)
+ modes_temp = ['constant'] * ndim_image
+ for m, ax in zip(modes, axes):
+ modes_temp[ax] = m
+ mode = modes_temp
+ return mode
+
+
+@_ni_docstrings.docfiller
+def correlate1d(input, weights, axis=-1, output=None, mode="reflect",
+ cval=0.0, origin=0):
+ """Calculate a 1-D correlation along the given axis.
+
+ The lines of the array along the given axis are correlated with the
+ given weights.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : array
+ 1-D sequence of numbers.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ result : ndarray
+ Correlation result. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy.ndimage import correlate1d
+ >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+ array([ 8, 26, 8, 12, 7, 28, 36, 9])
+ """
+ input = np.asarray(input)
+ weights = np.asarray(weights)
+ complex_input = input.dtype.kind == 'c'
+ complex_weights = weights.dtype.kind == 'c'
+ if complex_input or complex_weights:
+ if complex_weights:
+ weights = weights.conj()
+ weights = weights.astype(np.complex128, copy=False)
+ kwargs = dict(axis=axis, mode=mode, origin=origin)
+ output = _ni_support._get_output(output, input, complex_output=True)
+ return _complex_via_real_components(correlate1d, input, weights,
+ output, cval, **kwargs)
+
+ output = _ni_support._get_output(output, input)
+ weights = np.asarray(weights, dtype=np.float64)
+ if weights.ndim != 1 or weights.shape[0] < 1:
+ raise RuntimeError('no filter weights given')
+ if not weights.flags.contiguous:
+ weights = weights.copy()
+ axis = normalize_axis_index(axis, input.ndim)
+ if _invalid_origin(origin, len(weights)):
+ raise ValueError('Invalid origin; origin must satisfy '
+ '-(len(weights) // 2) <= origin <= '
+ '(len(weights)-1) // 2')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.correlate1d(input, weights, axis, output, mode, cval,
+ origin)
+ return output
+
+
+@_ni_docstrings.docfiller
+def convolve1d(input, weights, axis=-1, output=None, mode="reflect",
+ cval=0.0, origin=0):
+ """Calculate a 1-D convolution along the given axis.
+
+ The lines of the array along the given axis are convolved with the
+ given weights.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : ndarray
+ 1-D sequence of numbers.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ convolve1d : ndarray
+ Convolved array with same shape as input
+
+ Examples
+ --------
+ >>> from scipy.ndimage import convolve1d
+ >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+ array([14, 24, 4, 13, 12, 36, 27, 0])
+ """
+ weights = np.asarray(weights)
+ weights = weights[::-1]
+ origin = -origin
+ if not weights.shape[0] & 1:
+ origin -= 1
+ if weights.dtype.kind == 'c':
+ # pre-conjugate here to counteract the conjugation in correlate1d
+ weights = weights.conj()
+ return correlate1d(input, weights, axis, output, mode, cval, origin)
+
+
+def _gaussian_kernel1d(sigma, order, radius):
+ """
+ Computes a 1-D Gaussian convolution kernel.
+ """
+ if order < 0:
+ raise ValueError('order must be non-negative')
+ exponent_range = np.arange(order + 1)
+ sigma2 = sigma * sigma
+ x = np.arange(-radius, radius+1)
+ phi_x = np.exp(-0.5 / sigma2 * x ** 2)
+ phi_x = phi_x / phi_x.sum()
+
+ if order == 0:
+ return phi_x
+ else:
+ # f(x) = q(x) * phi(x) = q(x) * exp(p(x))
+ # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x)
+ # p'(x) = -1 / sigma ** 2
+ # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the
+ # coefficients of q(x)
+ q = np.zeros(order + 1)
+ q[0] = 1
+ D = np.diag(exponent_range[1:], 1) # D @ q(x) = q'(x)
+ P = np.diag(np.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x)
+ Q_deriv = D + P
+ for _ in range(order):
+ q = Q_deriv.dot(q)
+ q = (x[:, None] ** exponent_range).dot(q)
+ return q * phi_x
+
+
+@_ni_docstrings.docfiller
+def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None,
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None):
+ """1-D Gaussian filter.
+
+ Parameters
+ ----------
+ %(input)s
+ sigma : scalar
+ standard deviation for Gaussian kernel
+ %(axis)s
+ order : int, optional
+ An order of 0 corresponds to convolution with a Gaussian
+ kernel. A positive order corresponds to convolution with
+ that derivative of a Gaussian.
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ truncate : float, optional
+ Truncate the filter at this many standard deviations.
+ Default is 4.0.
+ radius : None or int, optional
+ Radius of the Gaussian kernel. If specified, the size of
+ the kernel will be ``2*radius + 1``, and `truncate` is ignored.
+ Default is None.
+
+ Returns
+ -------
+ gaussian_filter1d : ndarray
+ Returned array of same shape as `input`.
+
+ Notes
+ -----
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
+ `radius` is None, a default ``radius = round(truncate * sigma)`` will be
+ used.
+
+ Examples
+ --------
+ >>> from scipy.ndimage import gaussian_filter1d
+ >>> import numpy as np
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1)
+ array([ 1.42704095, 2.06782203, 3. , 3.93217797, 4.57295905])
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4)
+ array([ 2.91948343, 2.95023502, 3. , 3.04976498, 3.08051657])
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+ >>> x = rng.standard_normal(101).cumsum()
+ >>> y3 = gaussian_filter1d(x, 3)
+ >>> y6 = gaussian_filter1d(x, 6)
+ >>> plt.plot(x, 'k', label='original data')
+ >>> plt.plot(y3, '--', label='filtered, sigma=3')
+ >>> plt.plot(y6, ':', label='filtered, sigma=6')
+ >>> plt.legend()
+ >>> plt.grid()
+ >>> plt.show()
+
+ """
+ sd = float(sigma)
+ # make the radius of the filter equal to truncate standard deviations
+ lw = int(truncate * sd + 0.5)
+ if radius is not None:
+ lw = radius
+ if not isinstance(lw, numbers.Integral) or lw < 0:
+ raise ValueError('Radius must be a nonnegative integer.')
+ # Since we are calling correlate, not convolve, revert the kernel
+ weights = _gaussian_kernel1d(sigma, order, lw)[::-1]
+ return correlate1d(input, weights, axis, output, mode, cval, 0)
+
+
+@_ni_docstrings.docfiller
+def gaussian_filter(input, sigma, order=0, output=None,
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None,
+ axes=None):
+ """Multidimensional Gaussian filter.
+
+ Parameters
+ ----------
+ %(input)s
+ sigma : scalar or sequence of scalars
+ Standard deviation for Gaussian kernel. The standard
+ deviations of the Gaussian filter are given for each axis as a
+ sequence, or as a single number, in which case it is equal for
+ all axes.
+ order : int or sequence of ints, optional
+ The order of the filter along each axis is given as a sequence
+ of integers, or as a single number. An order of 0 corresponds
+ to convolution with a Gaussian kernel. A positive order
+ corresponds to convolution with that derivative of a Gaussian.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ truncate : float, optional
+ Truncate the filter at this many standard deviations.
+ Default is 4.0.
+ radius : None or int or sequence of ints, optional
+ Radius of the Gaussian kernel. The radius are given for each axis
+ as a sequence, or as a single number, in which case it is equal
+ for all axes. If specified, the size of the kernel along each axis
+ will be ``2*radius + 1``, and `truncate` is ignored.
+ Default is None.
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `sigma`, `order`, `mode` and/or `radius`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ gaussian_filter : ndarray
+ Returned array of same shape as `input`.
+
+ Notes
+ -----
+ The multidimensional filter is implemented as a sequence of
+ 1-D convolution filters. The intermediate arrays are
+ stored in the same data type as the output. Therefore, for output
+ types with a limited precision, the results may be imprecise
+ because intermediate results may be stored with insufficient
+ precision.
+
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
+ `radius` is None, the default ``radius = round(truncate * sigma)`` will be
+ used.
+
+ Examples
+ --------
+ >>> from scipy.ndimage import gaussian_filter
+ >>> import numpy as np
+ >>> a = np.arange(50, step=2).reshape((5,5))
+ >>> a
+ array([[ 0, 2, 4, 6, 8],
+ [10, 12, 14, 16, 18],
+ [20, 22, 24, 26, 28],
+ [30, 32, 34, 36, 38],
+ [40, 42, 44, 46, 48]])
+ >>> gaussian_filter(a, sigma=1)
+ array([[ 4, 6, 8, 9, 11],
+ [10, 12, 14, 15, 17],
+ [20, 22, 24, 25, 27],
+ [29, 31, 33, 34, 36],
+ [35, 37, 39, 40, 42]])
+
+ >>> from scipy import datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = gaussian_filter(ascent, sigma=5)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _ni_support._get_output(output, input)
+
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ orders = _ni_support._normalize_sequence(order, num_axes)
+ sigmas = _ni_support._normalize_sequence(sigma, num_axes)
+ modes = _ni_support._normalize_sequence(mode, num_axes)
+ radiuses = _ni_support._normalize_sequence(radius, num_axes)
+ axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii])
+ for ii in range(num_axes) if sigmas[ii] > 1e-15]
+ if len(axes) > 0:
+ for axis, sigma, order, mode, radius in axes:
+ gaussian_filter1d(input, sigma, axis, order, output,
+ mode, cval, truncate, radius=radius)
+ input = output
+ else:
+ output[...] = input[...]
+ return output
+
+
+@_ni_docstrings.docfiller
+def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0):
+ """Calculate a Prewitt filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(axis)s
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+
+ Returns
+ -------
+ prewitt : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ See Also
+ --------
+ sobel: Sobel filter
+
+ Notes
+ -----
+ This function computes the one-dimensional Prewitt filter.
+ Horizontal edges are emphasised with the horizontal transform (axis=0),
+ vertical edges with the vertical transform (axis=1), and so on for higher
+ dimensions. These can be combined to give the magnitude.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> ascent = datasets.ascent()
+ >>> prewitt_h = ndimage.prewitt(ascent, axis=0)
+ >>> prewitt_v = ndimage.prewitt(ascent, axis=1)
+ >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2)
+ >>> magnitude *= 255 / np.max(magnitude) # Normalization
+ >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8))
+ >>> plt.gray()
+ >>> axes[0, 0].imshow(ascent)
+ >>> axes[0, 1].imshow(prewitt_h)
+ >>> axes[1, 0].imshow(prewitt_v)
+ >>> axes[1, 1].imshow(magnitude)
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
+ >>> for i, ax in enumerate(axes.ravel()):
+ ... ax.set_title(titles[i])
+ ... ax.axis("off")
+ >>> plt.show()
+
+ """
+ input = np.asarray(input)
+ axis = normalize_axis_index(axis, input.ndim)
+ output = _ni_support._get_output(output, input)
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
+ axes = [ii for ii in range(input.ndim) if ii != axis]
+ for ii in axes:
+ correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,)
+ return output
+
+
+@_ni_docstrings.docfiller
+def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
+ """Calculate a Sobel filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(axis)s
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+
+ Returns
+ -------
+ sobel : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ This function computes the axis-specific Sobel gradient.
+ The horizontal edges can be emphasised with the horizontal transform (axis=0),
+ the vertical edges with the vertical transform (axis=1) and so on for higher
+ dimensions. These can be combined to give the magnitude.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> ascent = datasets.ascent().astype('int32')
+ >>> sobel_h = ndimage.sobel(ascent, 0) # horizontal gradient
+ >>> sobel_v = ndimage.sobel(ascent, 1) # vertical gradient
+ >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2)
+ >>> magnitude *= 255.0 / np.max(magnitude) # normalization
+ >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8))
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> axs[0, 0].imshow(ascent)
+ >>> axs[0, 1].imshow(sobel_h)
+ >>> axs[1, 0].imshow(sobel_v)
+ >>> axs[1, 1].imshow(magnitude)
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
+ >>> for i, ax in enumerate(axs.ravel()):
+ ... ax.set_title(titles[i])
+ ... ax.axis("off")
+ >>> plt.show()
+
+ """
+ input = np.asarray(input)
+ axis = normalize_axis_index(axis, input.ndim)
+ output = _ni_support._get_output(output, input)
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
+ axes = [ii for ii in range(input.ndim) if ii != axis]
+ for ii in axes:
+ correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0)
+ return output
+
+
+@_ni_docstrings.docfiller
+def generic_laplace(input, derivative2, output=None, mode="reflect",
+ cval=0.0,
+ extra_arguments=(),
+ extra_keywords=None,
+ *, axes=None):
+ """
+ N-D Laplace filter using a provided second derivative function.
+
+ Parameters
+ ----------
+ %(input)s
+ derivative2 : callable
+ Callable with the following signature::
+
+ derivative2(input, axis, output, mode, cval,
+ *extra_arguments, **extra_keywords)
+
+ See `extra_arguments`, `extra_keywords` below.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(extra_arguments)s
+ %(extra_keywords)s
+ axes : tuple of int or None
+ The axes over which to apply the filter. If a `mode` tuple is
+ provided, its length must match the number of axes.
+
+ Returns
+ -------
+ generic_laplace : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ """
+ if extra_keywords is None:
+ extra_keywords = {}
+ input = np.asarray(input)
+ output = _ni_support._get_output(output, input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ if len(axes) > 0:
+ modes = _ni_support._normalize_sequence(mode, len(axes))
+ derivative2(input, axes[0], output, modes[0], cval,
+ *extra_arguments, **extra_keywords)
+ for ii in range(1, len(axes)):
+ tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval,
+ *extra_arguments, **extra_keywords)
+ output += tmp
+ else:
+ output[...] = input[...]
+ return output
+
+
+@_ni_docstrings.docfiller
+def laplace(input, output=None, mode="reflect", cval=0.0, *, axes=None):
+ """N-D Laplace filter based on approximate second derivatives.
+
+ Parameters
+ ----------
+ %(input)s
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ axes : tuple of int or None
+ The axes over which to apply the filter. If a `mode` tuple is
+ provided, its length must match the number of axes.
+
+ Returns
+ -------
+ laplace : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.laplace(ascent)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ def derivative2(input, axis, output, mode, cval):
+ return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
+ return generic_laplace(input, derivative2, output, mode, cval, axes=axes)
+
+
+@_ni_docstrings.docfiller
+def gaussian_laplace(input, sigma, output=None, mode="reflect",
+ cval=0.0, *, axes=None, **kwargs):
+ """Multidimensional Laplace filter using Gaussian second derivatives.
+
+ Parameters
+ ----------
+ %(input)s
+ sigma : scalar or sequence of scalars
+ The standard deviations of the Gaussian filter are given for
+ each axis as a sequence, or as a single number, in which case
+ it is equal for all axes.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ axes : tuple of int or None
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
+ are provided, their length must match the number of axes.
+ **kwargs
+ Extra keyword arguments will be passed to `gaussian_filter`.
+
+ Returns
+ -------
+ gaussian_laplace : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> ascent = datasets.ascent()
+
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=1)
+ >>> ax1.imshow(result)
+
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=3)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+
+ def derivative2(input, axis, output, mode, cval, sigma, **kwargs):
+ order = [0] * input.ndim
+ order[axis] = 2
+ return gaussian_filter(input, sigma, order, output, mode, cval,
+ **kwargs)
+
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ sigma = _ni_support._normalize_sequence(sigma, num_axes)
+ if num_axes < input.ndim:
+ # set sigma = 0 for any axes not being filtered
+ sigma_temp = [0,] * input.ndim
+ for s, ax in zip(sigma, axes):
+ sigma_temp[ax] = s
+ sigma = sigma_temp
+
+ return generic_laplace(input, derivative2, output, mode, cval,
+ extra_arguments=(sigma,),
+ extra_keywords=kwargs,
+ axes=axes)
+
+
+@_ni_docstrings.docfiller
+def generic_gradient_magnitude(input, derivative, output=None,
+ mode="reflect", cval=0.0,
+ extra_arguments=(), extra_keywords=None,
+ *, axes=None):
+ """Gradient magnitude using a provided gradient function.
+
+ Parameters
+ ----------
+ %(input)s
+ derivative : callable
+ Callable with the following signature::
+
+ derivative(input, axis, output, mode, cval,
+ *extra_arguments, **extra_keywords)
+
+ See `extra_arguments`, `extra_keywords` below.
+ `derivative` can assume that `input` and `output` are ndarrays.
+ Note that the output from `derivative` is modified inplace;
+ be careful to copy important inputs before returning them.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(extra_arguments)s
+ %(extra_keywords)s
+ axes : tuple of int or None
+ The axes over which to apply the filter. If a `mode` tuple is
+ provided, its length must match the number of axes.
+
+ Returns
+ -------
+ generic_gradient_magnitude : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ """
+ if extra_keywords is None:
+ extra_keywords = {}
+ input = np.asarray(input)
+ output = _ni_support._get_output(output, input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ if len(axes) > 0:
+ modes = _ni_support._normalize_sequence(mode, len(axes))
+ derivative(input, axes[0], output, modes[0], cval,
+ *extra_arguments, **extra_keywords)
+ np.multiply(output, output, output)
+ for ii in range(1, len(axes)):
+ tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval,
+ *extra_arguments, **extra_keywords)
+ np.multiply(tmp, tmp, tmp)
+ output += tmp
+ # This allows the sqrt to work with a different default casting
+ np.sqrt(output, output, casting='unsafe')
+ else:
+ output[...] = input[...]
+ return output
+
+
+@_ni_docstrings.docfiller
+def gaussian_gradient_magnitude(input, sigma, output=None,
+ mode="reflect", cval=0.0, *, axes=None,
+ **kwargs):
+ """Multidimensional gradient magnitude using Gaussian derivatives.
+
+ Parameters
+ ----------
+ %(input)s
+ sigma : scalar or sequence of scalars
+ The standard deviations of the Gaussian filter are given for
+ each axis as a sequence, or as a single number, in which case
+ it is equal for all axes.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ axes : tuple of int or None
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
+ are provided, their length must match the number of axes.
+ **kwargs
+ Extra keyword arguments will be passed to `gaussian_filter`.
+
+ Returns
+ -------
+ gaussian_gradient_magnitude : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+
+ def derivative(input, axis, output, mode, cval, sigma, **kwargs):
+ order = [0] * input.ndim
+ order[axis] = 1
+ return gaussian_filter(input, sigma, order, output, mode,
+ cval, **kwargs)
+
+ return generic_gradient_magnitude(input, derivative, output, mode,
+ cval, extra_arguments=(sigma,),
+ extra_keywords=kwargs, axes=axes)
+
+
+def _correlate_or_convolve(input, weights, output, mode, cval, origin,
+ convolution, axes):
+ input = np.asarray(input)
+ weights = np.asarray(weights)
+ complex_input = input.dtype.kind == 'c'
+ complex_weights = weights.dtype.kind == 'c'
+ if complex_input or complex_weights:
+ if complex_weights and not convolution:
+ # As for np.correlate, conjugate weights rather than input.
+ weights = weights.conj()
+ kwargs = dict(
+ mode=mode, origin=origin, convolution=convolution, axes=axes
+ )
+ output = _ni_support._get_output(output, input, complex_output=True)
+
+ return _complex_via_real_components(_correlate_or_convolve, input,
+ weights, output, cval, **kwargs)
+
+ axes = _ni_support._check_axes(axes, input.ndim)
+ weights = np.asarray(weights, dtype=np.float64)
+
+ # expand weights and origins if num_axes < input.ndim
+ weights = _expand_footprint(input.ndim, axes, weights, "weights")
+ origins = _expand_origin(input.ndim, axes, origin)
+
+ wshape = [ii for ii in weights.shape if ii > 0]
+ if len(wshape) != input.ndim:
+ raise RuntimeError(f"weights.ndim ({len(wshape)}) must match "
+ f"len(axes) ({len(axes)})")
+ if convolution:
+ weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
+ for ii in range(len(origins)):
+ origins[ii] = -origins[ii]
+ if not weights.shape[ii] & 1:
+ origins[ii] -= 1
+ for origin, lenw in zip(origins, wshape):
+ if _invalid_origin(origin, lenw):
+ raise ValueError('Invalid origin; origin must satisfy '
+ '-(weights.shape[k] // 2) <= origin[k] <= '
+ '(weights.shape[k]-1) // 2')
+
+ if not weights.flags.contiguous:
+ weights = weights.copy()
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ raise RuntimeError("A sequence of modes is not supported")
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.correlate(input, weights, output, mode, cval, origins)
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+@_ni_docstrings.docfiller
+def correlate(input, weights, output=None, mode='reflect', cval=0.0,
+ origin=0, *, axes=None):
+ """
+ Multidimensional correlation.
+
+ The array is correlated with the given kernel.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : ndarray
+ array of weights, same number of dimensions as input
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `mode` or `origin` must match the length
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
+ entry in `axes`.
+
+ Returns
+ -------
+ result : ndarray
+ The result of correlation of `input` with `weights`.
+
+ See Also
+ --------
+ convolve : Convolve an image with a kernel.
+
+ Examples
+ --------
+ Correlation is the process of moving a filter mask often referred to
+ as kernel over the image and computing the sum of products at each location.
+
+ >>> from scipy.ndimage import correlate
+ >>> import numpy as np
+ >>> input_img = np.arange(25).reshape(5,5)
+ >>> print(input_img)
+ [[ 0 1 2 3 4]
+ [ 5 6 7 8 9]
+ [10 11 12 13 14]
+ [15 16 17 18 19]
+ [20 21 22 23 24]]
+
+ Define a kernel (weights) for correlation. In this example, it is for sum of
+ center and up, down, left and right next elements.
+
+ >>> weights = [[0, 1, 0],
+ ... [1, 1, 1],
+ ... [0, 1, 0]]
+
+ We can calculate a correlation result:
+ For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``.
+
+ >>> correlate(input_img, weights)
+ array([[ 6, 10, 15, 20, 24],
+ [ 26, 30, 35, 40, 44],
+ [ 51, 55, 60, 65, 69],
+ [ 76, 80, 85, 90, 94],
+ [ 96, 100, 105, 110, 114]])
+
+ """
+ return _correlate_or_convolve(input, weights, output, mode, cval,
+ origin, False, axes)
+
+
+@_ni_docstrings.docfiller
+def convolve(input, weights, output=None, mode='reflect', cval=0.0,
+ origin=0, *, axes=None):
+ """
+ Multidimensional convolution.
+
+ The array is convolved with the given kernel.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : array_like
+ Array of weights, same number of dimensions as input
+ %(output)s
+ %(mode_reflect)s
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0
+ origin : int or sequence, optional
+ Controls the placement of the filter on the input array's pixels.
+ A value of 0 (the default) centers the filter over the pixel, with
+ positive values shifting the filter to the right, and negative ones
+ to the left. By passing a sequence of origins with length equal to
+ the number of dimensions of the input array, different shifts can
+ be specified along each axis.
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `mode` or `origin` must match the length
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
+ entry in `axes`.
+
+ Returns
+ -------
+ result : ndarray
+ The result of convolution of `input` with `weights`.
+
+ See Also
+ --------
+ correlate : Correlate an image with a kernel.
+
+ Notes
+ -----
+ Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
+ W is the `weights` kernel,
+ j is the N-D spatial index over :math:`W`,
+ I is the `input` and k is the coordinate of the center of
+ W, specified by `origin` in the input parameters.
+
+ Examples
+ --------
+ Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
+ because in this case borders (i.e., where the `weights` kernel, centered
+ on any one value, extends beyond an edge of `input`) are treated as zeros.
+
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
+ >>> from scipy import ndimage
+ >>> ndimage.convolve(a, k, mode='constant', cval=0.0)
+ array([[11, 10, 7, 4],
+ [10, 3, 11, 11],
+ [15, 12, 14, 7],
+ [12, 3, 7, 0]])
+
+ Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
+ with 1.0's (and then extracting only the original region of the result).
+
+ >>> ndimage.convolve(a, k, mode='constant', cval=1.0)
+ array([[13, 11, 8, 7],
+ [11, 3, 11, 14],
+ [16, 12, 14, 10],
+ [15, 6, 10, 5]])
+
+ With ``mode='reflect'`` (the default), outer values are reflected at the
+ edge of `input` to fill in missing values.
+
+ >>> b = np.array([[2, 0, 0],
+ ... [1, 0, 0],
+ ... [0, 0, 0]])
+ >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
+ >>> ndimage.convolve(b, k, mode='reflect')
+ array([[5, 0, 0],
+ [3, 0, 0],
+ [1, 0, 0]])
+
+ This includes diagonally at the corners.
+
+ >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
+ >>> ndimage.convolve(b, k)
+ array([[4, 2, 0],
+ [3, 2, 0],
+ [1, 1, 0]])
+
+ With ``mode='nearest'``, the single nearest value in to an edge in
+ `input` is repeated as many times as needed to match the overlapping
+ `weights`.
+
+ >>> c = np.array([[2, 0, 1],
+ ... [1, 0, 0],
+ ... [0, 0, 0]])
+ >>> k = np.array([[0, 1, 0],
+ ... [0, 1, 0],
+ ... [0, 1, 0],
+ ... [0, 1, 0],
+ ... [0, 1, 0]])
+ >>> ndimage.convolve(c, k, mode='nearest')
+ array([[7, 0, 3],
+ [5, 0, 2],
+ [3, 0, 1]])
+
+ """
+ return _correlate_or_convolve(input, weights, output, mode, cval,
+ origin, True, axes)
+
+
+@_ni_docstrings.docfiller
+def uniform_filter1d(input, size, axis=-1, output=None,
+ mode="reflect", cval=0.0, origin=0):
+ """Calculate a 1-D uniform filter along the given axis.
+
+ The lines of the array along the given axis are filtered with a
+ uniform filter of given size.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int
+ length of uniform filter
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ result : ndarray
+ Filtered array. Has same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy.ndimage import uniform_filter1d
+ >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+ array([4, 3, 4, 1, 4, 6, 6, 3])
+ """
+ input = np.asarray(input)
+ axis = normalize_axis_index(axis, input.ndim)
+ if size < 1:
+ raise RuntimeError('incorrect filter size')
+ complex_output = input.dtype.kind == 'c'
+ output = _ni_support._get_output(output, input,
+ complex_output=complex_output)
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ if not complex_output:
+ _nd_image.uniform_filter1d(input, size, axis, output, mode, cval,
+ origin)
+ else:
+ _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode,
+ np.real(cval), origin)
+ _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode,
+ np.imag(cval), origin)
+ return output
+
+
+@_ni_docstrings.docfiller
+def uniform_filter(input, size=3, output=None, mode="reflect",
+ cval=0.0, origin=0, *, axes=None):
+ """Multidimensional uniform filter.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int or sequence of ints, optional
+ The sizes of the uniform filter are given for each axis as a
+ sequence, or as a single number, in which case the size is
+ equal for all axes.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ uniform_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ The multidimensional filter is implemented as a sequence of
+ 1-D uniform filters. The intermediate arrays are stored
+ in the same data type as the output. Therefore, for output types
+ with a limited precision, the results may be imprecise because
+ intermediate results may be stored with insufficient precision.
+
+ %(nan)s
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.uniform_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _ni_support._get_output(output, input,
+ complex_output=input.dtype.kind == 'c')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ origins = _ni_support._normalize_sequence(origin, num_axes)
+ modes = _ni_support._normalize_sequence(mode, num_axes)
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+ for ii in range(num_axes) if sizes[ii] > 1]
+ if len(axes) > 0:
+ for axis, size, origin, mode in axes:
+ uniform_filter1d(input, int(size), axis, output, mode,
+ cval, origin)
+ input = output
+ else:
+ output[...] = input[...]
+ return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter1d(input, size, axis=-1, output=None,
+ mode="reflect", cval=0.0, origin=0):
+ """Calculate a 1-D minimum filter along the given axis.
+
+ The lines of the array along the given axis are filtered with a
+ minimum filter of given size.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int
+ length along which to calculate 1D minimum
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ result : ndarray.
+ Filtered image. Has the same shape as `input`.
+
+ Notes
+ -----
+ This function implements the MINLIST algorithm [1]_, as described by
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+ the `input` length, regardless of filter size.
+
+ References
+ ----------
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777.
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+
+ Examples
+ --------
+ >>> from scipy.ndimage import minimum_filter1d
+ >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+ array([2, 0, 0, 0, 1, 1, 0, 0])
+ """
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axis = normalize_axis_index(axis, input.ndim)
+ if size < 1:
+ raise RuntimeError('incorrect filter size')
+ output = _ni_support._get_output(output, input)
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+ origin, 1)
+ return output
+
+
+@_ni_docstrings.docfiller
+def maximum_filter1d(input, size, axis=-1, output=None,
+ mode="reflect", cval=0.0, origin=0):
+ """Calculate a 1-D maximum filter along the given axis.
+
+ The lines of the array along the given axis are filtered with a
+ maximum filter of given size.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int
+ Length along which to calculate the 1-D maximum.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ maximum1d : ndarray, None
+ Maximum-filtered array with same shape as input.
+ None if `output` is not None
+
+ Notes
+ -----
+ This function implements the MAXLIST algorithm [1]_, as described by
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+ the `input` length, regardless of filter size.
+
+ References
+ ----------
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777.
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+ Examples
+ --------
+ >>> from scipy.ndimage import maximum_filter1d
+ >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+ array([8, 8, 8, 4, 9, 9, 9, 9])
+ """
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axis = normalize_axis_index(axis, input.ndim)
+ if size < 1:
+ raise RuntimeError('incorrect filter size')
+ output = _ni_support._get_output(output, input)
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+ origin, 0)
+ return output
+
+
+def _min_or_max_filter(input, size, footprint, structure, output, mode,
+ cval, origin, minimum, axes=None):
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=3)
+ if structure is None:
+ if footprint is None:
+ if size is None:
+ raise RuntimeError("no footprint provided")
+ separable = True
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+ if not footprint.any():
+ raise ValueError("All-zero footprint is not supported.")
+ if footprint.all():
+ size = footprint.shape
+ footprint = None
+ separable = True
+ else:
+ separable = False
+ else:
+ structure = np.asarray(structure, dtype=np.float64)
+ separable = False
+ if footprint is None:
+ footprint = np.ones(structure.shape, bool)
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError("Complex type not supported")
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if separable:
+ origins = _ni_support._normalize_sequence(origin, num_axes)
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ modes = _ni_support._normalize_sequence(mode, num_axes)
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+ for ii in range(len(axes)) if sizes[ii] > 1]
+ if minimum:
+ filter_ = minimum_filter1d
+ else:
+ filter_ = maximum_filter1d
+ if len(axes) > 0:
+ for axis, size, origin, mode in axes:
+ filter_(input, int(size), axis, output, mode, cval, origin)
+ input = output
+ else:
+ output[...] = input[...]
+ else:
+ # expand origins and footprint if num_axes < input.ndim
+ footprint = _expand_footprint(input.ndim, axes, footprint)
+ origins = _expand_origin(input.ndim, axes, origin)
+
+ fshape = [ii for ii in footprint.shape if ii > 0]
+ if len(fshape) != input.ndim:
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ for origin, lenf in zip(origins, fshape):
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+ raise ValueError("invalid origin")
+ if not footprint.flags.contiguous:
+ footprint = footprint.copy()
+ if structure is not None:
+ if len(structure.shape) != num_axes:
+ raise RuntimeError("structure array has incorrect shape")
+ if num_axes != structure.ndim:
+ structure = np.expand_dims(
+ structure,
+ tuple(ax for ax in range(structure.ndim) if ax not in axes)
+ )
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ raise RuntimeError(
+ "A sequence of modes is not supported for non-separable "
+ "footprints")
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.min_or_max_filter(input, footprint, structure, output,
+ mode, cval, origins, minimum)
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter(input, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """Calculate a multidimensional minimum filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(size_foot)s
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ minimum_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ A sequence of modes (one per axis) is only supported when the footprint is
+ separable. Otherwise, a single mode string must be provided.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.minimum_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
+ cval, origin, 1, axes)
+
+
+@_ni_docstrings.docfiller
+def maximum_filter(input, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """Calculate a multidimensional maximum filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(size_foot)s
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ maximum_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ A sequence of modes (one per axis) is only supported when the footprint is
+ separable. Otherwise, a single mode string must be provided.
+
+ %(nan)s
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.maximum_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
+ cval, origin, 0, axes)
+
+
+@_ni_docstrings.docfiller
+def _rank_filter(input, rank, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, operation='rank',
+ axes=None):
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=3)
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if footprint is None:
+ if size is None:
+ raise RuntimeError("no footprint or filter size provided")
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ footprint = np.ones(sizes, dtype=bool)
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+ # expand origins, footprint and modes if num_axes < input.ndim
+ footprint = _expand_footprint(input.ndim, axes, footprint)
+ origins = _expand_origin(input.ndim, axes, origin)
+ mode = _expand_mode(input.ndim, axes, mode)
+
+ fshape = [ii for ii in footprint.shape if ii > 0]
+ if len(fshape) != input.ndim:
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ for origin, lenf in zip(origins, fshape):
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+ raise ValueError('invalid origin')
+ if not footprint.flags.contiguous:
+ footprint = footprint.copy()
+ filter_size = np.where(footprint, 1, 0).sum()
+ if operation == 'median':
+ rank = filter_size // 2
+ elif operation == 'percentile':
+ percentile = rank
+ if percentile < 0.0:
+ percentile += 100.0
+ if percentile < 0 or percentile > 100:
+ raise RuntimeError('invalid percentile')
+ if percentile == 100.0:
+ rank = filter_size - 1
+ else:
+ rank = int(float(filter_size) * percentile / 100.0)
+ if rank < 0:
+ rank += filter_size
+ if rank < 0 or rank >= filter_size:
+ raise RuntimeError('rank not within filter footprint size')
+ if rank == 0:
+ return minimum_filter(input, None, footprint, output, mode, cval,
+ origins, axes=None)
+ elif rank == filter_size - 1:
+ return maximum_filter(input, None, footprint, output, mode, cval,
+ origins, axes=None)
+ else:
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ raise RuntimeError(
+ "A sequence of modes is not supported by non-separable rank "
+ "filters")
+ mode = _ni_support._extend_mode_to_code(mode, is_filter=True)
+ # Some corner cases are currently not allowed to use the
+ # "new"/fast 1D rank filter code, including when the
+ # footprint is large compared to the array size.
+ # See discussion in gh-23293; longer-term it may be possible
+ # to allow the fast path for these corner cases as well,
+ # if algorithmic fixes are found.
+ lim2 = input.size - ((footprint.size - 1) // 2 - origin)
+ if input.ndim == 1 and ((lim2 >= 0) or (input.size == 1)):
+ if input.dtype in (np.int64, np.float64, np.float32):
+ x = input
+ x_out = output
+ elif input.dtype == np.float16:
+ x = input.astype('float32')
+ x_out = np.empty(x.shape, dtype='float32')
+ elif np.result_type(input, np.int64) == np.int64:
+ x = input.astype('int64')
+ x_out = np.empty(x.shape, dtype='int64')
+ elif input.dtype.kind in 'biu':
+ # cast any other boolean, integer or unsigned type to int64
+ x = input.astype('int64')
+ x_out = np.empty(x.shape, dtype='int64')
+ else:
+ raise RuntimeError('Unsupported array type')
+ cval = x.dtype.type(cval)
+ _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval,
+ origin)
+ if input.dtype not in (np.int64, np.float64, np.float32):
+ np.copyto(output, x_out, casting='unsafe')
+ else:
+ _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+@_ni_docstrings.docfiller
+def rank_filter(input, rank, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """Calculate a multidimensional rank filter.
+
+ Parameters
+ ----------
+ %(input)s
+ rank : int
+ The rank parameter may be less than zero, i.e., rank = -1
+ indicates the largest element.
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ rank_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ rank = operator.index(rank)
+ return _rank_filter(input, rank, size, footprint, output, mode, cval,
+ origin, 'rank', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def median_filter(input, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """
+ Calculate a multidimensional median filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ median_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ See Also
+ --------
+ scipy.signal.medfilt2d
+
+ Notes
+ -----
+ For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes
+ the specialised function `scipy.signal.medfilt2d` may be faster. It is
+ however limited to constant mode with ``cval=0``.
+
+ The filter always returns the argument that would appear at index ``n // 2`` in
+ a sorted array, where ``n`` is the number of elements in the footprint of the
+ filter. Note that this differs from the conventional definition of the median
+ when ``n`` is even. Also, this function does not support the ``float16`` dtype,
+ behavior in the presence of NaNs is undefined, and memory consumption scales with
+ ``n**4``. For ``float16`` support, greater control over the definition of the
+ filter, and to limit memory usage, consider using `vectorized_filter` with
+ NumPy functions `np.median` or `np.nanmedian`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.median_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _rank_filter(input, 0, size, footprint, output, mode, cval,
+ origin, 'median', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def percentile_filter(input, percentile, size=None, footprint=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """Calculate a multidimensional percentile filter.
+
+ Parameters
+ ----------
+ %(input)s
+ percentile : scalar
+ The percentile parameter may be less than zero, i.e.,
+ percentile = -20 equals percentile = 80
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ percentile_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _rank_filter(input, percentile, size, footprint, output, mode,
+ cval, origin, 'percentile', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def generic_filter1d(input, function, filter_size, axis=-1,
+ output=None, mode="reflect", cval=0.0, origin=0,
+ extra_arguments=(), extra_keywords=None):
+ """Calculate a 1-D filter along the given axis.
+
+ `generic_filter1d` iterates over the lines of the array, calling the
+ given function at each line. The arguments of the line are the
+ input line, and the output line. The input and output lines are 1-D
+ double arrays. The input line is extended appropriately according
+ to the filter size and origin. The output line must be modified
+ in-place with the result.
+
+ Parameters
+ ----------
+ %(input)s
+ function : {callable, scipy.LowLevelCallable}
+ Function to apply along given axis.
+ filter_size : scalar
+ Length of the filter.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+ %(extra_arguments)s
+ %(extra_keywords)s
+
+ Returns
+ -------
+ generic_filter1d : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ This function also accepts low-level callback functions with one of
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+ .. code:: c
+
+ int function(double *input_line, npy_intp input_length,
+ double *output_line, npy_intp output_length,
+ void *user_data)
+ int function(double *input_line, intptr_t input_length,
+ double *output_line, intptr_t output_length,
+ void *user_data)
+
+ The calling function iterates over the lines of the input and output
+ arrays, calling the callback function at each line. The current line
+ is extended according to the border conditions set by the calling
+ function, and the result is copied into the array that is passed
+ through ``input_line``. The length of the input line (after extension)
+ is passed through ``input_length``. The callback function should apply
+ the filter and store the result in the array passed through
+ ``output_line``. The length of the output line is passed through
+ ``output_length``. ``user_data`` is the data pointer provided
+ to `scipy.LowLevelCallable` as-is.
+
+ The callback function must return an integer error status that is zero
+ if something went wrong and one otherwise. If an error occurs, you should
+ normally set the python error status with an informative message
+ before returning, otherwise a default error message is set by the
+ calling function.
+
+ In addition, some other low-level function pointer specifications
+ are accepted, but these are for backward compatibility only and should
+ not be used in new code.
+
+ Examples
+ --------
+ This example defines and applies a custom callback function that computes
+ the range (maximum minus minimum) within a sliding window of size 3.
+ It utilizes `numpy.lib.stride_tricks.sliding_window_view` and demonstrates the
+ required in-place modification of the ``output_line`` array.
+
+ >>> import numpy as np
+ >>> from scipy.ndimage import generic_filter1d
+ >>> from numpy.lib.stride_tricks import sliding_window_view
+
+ >>> def local_range(input_line, output_line):
+ ... # input_line includes padded values according to `filter_size` and `mode`
+ ... v = sliding_window_view(input_line, 3)
+ ... # modify `output_line` in-place rather than returning the result
+ ... output_line[:] = v.max(axis=1) - v.min(axis=1)
+
+ >>> x = np.array([1, 2, 3, 4, 5], dtype=np.float64)
+ >>> generic_filter1d(x, local_range, filter_size=3)
+ array([1., 2., 2., 2., 1.])
+
+ """
+ if extra_keywords is None:
+ extra_keywords = {}
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ output = _ni_support._get_output(output, input)
+ if filter_size < 1:
+ raise RuntimeError('invalid filter size')
+ axis = normalize_axis_index(axis, input.ndim)
+ if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >=
+ filter_size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.generic_filter1d(input, function, filter_size, axis, output,
+ mode, cval, origin, extra_arguments,
+ extra_keywords)
+ return output
+
+
+@_ni_docstrings.docfiller
+def generic_filter(input, function, size=None, footprint=None,
+ output=None, mode="reflect", cval=0.0, origin=0,
+ extra_arguments=(), extra_keywords=None, *, axes=None):
+ """Calculate a multidimensional filter using the given function.
+
+ At each element the provided function is called. The input values
+ within the filter footprint at that element are passed to the function
+ as a 1-D array of double values.
+
+ Parameters
+ ----------
+ %(input)s
+ function : {callable, scipy.LowLevelCallable}
+ Function to apply at each element.
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ %(extra_arguments)s
+ %(extra_keywords)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size` or `origin` must match the length
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
+ entry in `axes`.
+
+ Returns
+ -------
+ output : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ See Also
+ --------
+ vectorized_filter : similar functionality, but optimized for vectorized callables
+
+ Notes
+ -----
+ This function is ideal for use with instances of `scipy.LowLevelCallable`;
+ for vectorized, pure-Python callables, consider `vectorized_filter` for improved
+ performance.
+
+ Low-level callback functions must have one of the following signatures:
+
+ .. code:: c
+
+ int callback(double *buffer, npy_intp filter_size,
+ double *return_value, void *user_data)
+ int callback(double *buffer, intptr_t filter_size,
+ double *return_value, void *user_data)
+
+ The calling function iterates over the elements of the input and
+ output arrays, calling the callback function at each element. The
+ elements within the footprint of the filter at the current element are
+ passed through the ``buffer`` parameter, and the number of elements
+ within the footprint through ``filter_size``. The calculated value is
+ returned in ``return_value``. ``user_data`` is the data pointer provided
+ to `scipy.LowLevelCallable` as-is.
+
+ The callback function must return an integer error status that is zero
+ if something went wrong and one otherwise. If an error occurs, you should
+ normally set the python error status with an informative message
+ before returning, otherwise a default error message is set by the
+ calling function.
+
+ In addition, some other low-level function pointer specifications
+ are accepted, but these are for backward compatibility only and should
+ not be used in new code.
+
+ Examples
+ --------
+ Import the necessary modules and load the example image used for
+ filtering.
+
+ >>> import numpy as np
+ >>> from scipy import datasets
+ >>> from scipy.ndimage import zoom, generic_filter
+ >>> import matplotlib.pyplot as plt
+ >>> ascent = zoom(datasets.ascent(), 0.5)
+
+ Compute a maximum filter with kernel size 5 by passing a simple NumPy
+ aggregation function as argument to `function`.
+
+ >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5])
+
+ While a maximum filter could also directly be obtained using
+ `maximum_filter`, `generic_filter` allows generic Python function or
+ `scipy.LowLevelCallable` to be used as a filter. Here, we compute the
+ range between maximum and minimum value as an example for a kernel size
+ of 5.
+
+ >>> def custom_filter(image):
+ ... return np.amax(image) - np.amin(image)
+ >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
+
+ Plot the original and filtered images.
+
+ >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9))
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> top, middle, bottom = axes
+ >>> for ax in axes:
+ ... ax.set_axis_off() # remove coordinate system
+ >>> top.imshow(ascent)
+ >>> top.set_title("Original image")
+ >>> middle.imshow(maximum_filter_result)
+ >>> middle.set_title("Maximum filter, Kernel: 5x5")
+ >>> bottom.imshow(custom_filter_result)
+ >>> bottom.set_title("Custom filter, Kernel: 5x5")
+ >>> fig.tight_layout()
+
+ """
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ if extra_keywords is None:
+ extra_keywords = {}
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if footprint is None:
+ if size is None:
+ raise RuntimeError("no footprint or filter size provided")
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ footprint = np.ones(sizes, dtype=bool)
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+
+ # expand origins, footprint if num_axes < input.ndim
+ footprint = _expand_footprint(input.ndim, axes, footprint)
+ origins = _expand_origin(input.ndim, axes, origin)
+
+ fshape = [ii for ii in footprint.shape if ii > 0]
+ if len(fshape) != input.ndim:
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) "
+ f"must match len(axes) ({num_axes})")
+ for origin, lenf in zip(origins, fshape):
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+ raise ValueError('invalid origin')
+ if not footprint.flags.contiguous:
+ footprint = footprint.copy()
+ output = _ni_support._get_output(output, input)
+
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.generic_filter(input, function, footprint, output, mode,
+ cval, origins, extra_arguments, extra_keywords)
+ return output
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_fourier.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_fourier.py
@@ -0,0 +1,306 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from . import _ni_support
+from . import _nd_image
+
+__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid',
+ 'fourier_shift']
+
+
+def _get_output_fourier(output, input):
+ if output is None:
+ if input.dtype.type in [np.complex64, np.complex128, np.float32]:
+ output = np.zeros(input.shape, dtype=input.dtype)
+ else:
+ output = np.zeros(input.shape, dtype=np.float64)
+ elif type(output) is type:
+ if output not in [np.complex64, np.complex128,
+ np.float32, np.float64]:
+ raise RuntimeError("output type not supported")
+ output = np.zeros(input.shape, dtype=output)
+ elif output.shape != input.shape:
+ raise RuntimeError("output shape not correct")
+ return output
+
+
+def _get_output_fourier_complex(output, input):
+ if output is None:
+ if input.dtype.type in [np.complex64, np.complex128]:
+ output = np.zeros(input.shape, dtype=input.dtype)
+ else:
+ output = np.zeros(input.shape, dtype=np.complex128)
+ elif type(output) is type:
+ if output not in [np.complex64, np.complex128]:
+ raise RuntimeError("output type not supported")
+ output = np.zeros(input.shape, dtype=output)
+ elif output.shape != input.shape:
+ raise RuntimeError("output shape not correct")
+ return output
+
+
+def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None):
+ """
+ Multidimensional Gaussian fourier filter.
+
+ The array is multiplied with the fourier transform of a Gaussian
+ kernel.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ sigma : float or sequence
+ The sigma of the Gaussian kernel. If a float, `sigma` is the same for
+ all axes. If a sequence, `sigma` has to contain one value for each
+ axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of filtering the input is placed in this array.
+
+ Returns
+ -------
+ fourier_gaussian : ndarray
+ The filtered input.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import numpy.fft
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_gaussian(input_, sigma=4)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _get_output_fourier(output, input)
+ axis = normalize_axis_index(axis, input.ndim)
+ sigmas = _ni_support._normalize_sequence(sigma, input.ndim)
+ sigmas = np.asarray(sigmas, dtype=np.float64)
+ if not sigmas.flags.contiguous:
+ sigmas = sigmas.copy()
+
+ _nd_image.fourier_filter(input, sigmas, n, axis, output, 0)
+ return output
+
+
+def fourier_uniform(input, size, n=-1, axis=-1, output=None):
+ """
+ Multidimensional uniform fourier filter.
+
+ The array is multiplied with the Fourier transform of a box of given
+ size.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ size : float or sequence
+ The size of the box used for filtering.
+ If a float, `size` is the same for all axes. If a sequence, `size` has
+ to contain one value for each axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of filtering the input is placed in this array.
+
+ Returns
+ -------
+ fourier_uniform : ndarray
+ The filtered input.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import numpy.fft
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_uniform(input_, size=20)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _get_output_fourier(output, input)
+ axis = normalize_axis_index(axis, input.ndim)
+ sizes = _ni_support._normalize_sequence(size, input.ndim)
+ sizes = np.asarray(sizes, dtype=np.float64)
+ if not sizes.flags.contiguous:
+ sizes = sizes.copy()
+ _nd_image.fourier_filter(input, sizes, n, axis, output, 1)
+ return output
+
+
+def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None):
+ """
+ Multidimensional ellipsoid Fourier filter.
+
+ The array is multiplied with the fourier transform of an ellipsoid of
+ given sizes.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ size : float or sequence
+ The size of the box used for filtering.
+ If a float, `size` is the same for all axes. If a sequence, `size` has
+ to contain one value for each axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of filtering the input is placed in this array.
+
+ Returns
+ -------
+ fourier_ellipsoid : ndarray
+ The filtered input.
+
+ Notes
+ -----
+ This function is implemented for arrays of rank 1, 2, or 3.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import numpy.fft
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_ellipsoid(input_, size=20)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ if input.ndim > 3:
+ raise NotImplementedError("Only 1d, 2d and 3d inputs are supported")
+ output = _get_output_fourier(output, input)
+ if output.size == 0:
+ # The C code has a bug that can result in a segfault with arrays
+ # that have size 0 (gh-17270), so check here.
+ return output
+ axis = normalize_axis_index(axis, input.ndim)
+ sizes = _ni_support._normalize_sequence(size, input.ndim)
+ sizes = np.asarray(sizes, dtype=np.float64)
+ if not sizes.flags.contiguous:
+ sizes = sizes.copy()
+ _nd_image.fourier_filter(input, sizes, n, axis, output, 2)
+ return output
+
+
+def fourier_shift(input, shift, n=-1, axis=-1, output=None):
+ """
+ Multidimensional Fourier shift filter.
+
+ The array is multiplied with the Fourier transform of a shift operation.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ shift : float or sequence
+ The size of the box used for filtering.
+ If a float, `shift` is the same for all axes. If a sequence, `shift`
+ has to contain one value for each axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of shifting the input is placed in this array.
+
+ Returns
+ -------
+ fourier_shift : ndarray
+ The shifted input.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy.fft
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_shift(input_, shift=200)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _get_output_fourier_complex(output, input)
+ axis = normalize_axis_index(axis, input.ndim)
+ shifts = _ni_support._normalize_sequence(shift, input.ndim)
+ shifts = np.asarray(shifts, dtype=np.float64)
+ if not shifts.flags.contiguous:
+ shifts = shifts.copy()
+ _nd_image.fourier_shift(input, shifts, n, axis, output)
+ return output
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..098ad78342a3e9adbcc7b77178bc6c25080758e5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py
@@ -0,0 +1,1033 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import itertools
+import warnings
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from scipy._external import array_api_extra as xpx
+
+from scipy import special
+from . import _ni_support
+from . import _nd_image
+from ._ni_docstrings import docfiller
+
+
+__all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform',
+ 'map_coordinates', 'affine_transform', 'shift', 'zoom', 'rotate']
+
+
+@docfiller
+def spline_filter1d(input, order=3, axis=-1, output=np.float64,
+ mode='mirror'):
+ """
+ Calculate a 1-D spline filter along the given axis.
+
+ The lines of the array along the given axis are filtered by a
+ spline filter. The order of the spline must be >= 2 and <= 5.
+
+ Parameters
+ ----------
+ %(input)s
+ order : int, optional
+ The order of the spline, default is 3.
+ axis : int, optional
+ The axis along which the spline filter is applied. Default is the last
+ axis.
+ output : ndarray or dtype, optional
+ The array in which to place the output, or the dtype of the returned
+ array. Default is ``numpy.float64``.
+ %(mode_interp_mirror)s
+
+ Returns
+ -------
+ spline_filter1d : ndarray
+ The filtered input.
+
+ See Also
+ --------
+ spline_filter : Multidimensional spline filter.
+
+ Notes
+ -----
+ All of the interpolation functions in `ndimage` do spline interpolation of
+ the input image. If using B-splines of `order > 1`, the input image
+ values have to be converted to B-spline coefficients first, which is
+ done by applying this 1-D filter sequentially along all
+ axes of the input. All functions that require B-spline coefficients
+ will automatically filter their inputs, a behavior controllable with
+ the `prefilter` keyword argument. For functions that accept a `mode`
+ parameter, the result will only be correct if it matches the `mode`
+ used when filtering.
+
+ For complex-valued `input`, this function processes the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ We can filter an image using 1-D spline along the given axis:
+
+ >>> from scipy.ndimage import spline_filter1d
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> orig_img = np.eye(20) # create an image
+ >>> orig_img[10, :] = 1.0
+ >>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0)
+ >>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1)
+ >>> f, ax = plt.subplots(1, 3, sharex=True)
+ >>> for ind, data in enumerate([[orig_img, "original image"],
+ ... [sp_filter_axis_0, "spline filter (axis=0)"],
+ ... [sp_filter_axis_1, "spline filter (axis=1)"]]):
+ ... ax[ind].imshow(data[0], cmap='gray_r')
+ ... ax[ind].set_title(data[1])
+ >>> plt.tight_layout()
+ >>> plt.show()
+
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input,
+ complex_output=complex_output)
+ if complex_output:
+ spline_filter1d(input.real, order, axis, output.real, mode)
+ spline_filter1d(input.imag, order, axis, output.imag, mode)
+ return output
+ if order in [0, 1]:
+ output[...] = np.array(input)
+ else:
+ mode = _ni_support._extend_mode_to_code(mode)
+ axis = normalize_axis_index(axis, input.ndim)
+ _nd_image.spline_filter1d(input, order, axis, output, mode)
+ return output
+
+@docfiller
+def spline_filter(input, order=3, output=np.float64, mode='mirror'):
+ """
+ Multidimensional spline filter.
+
+ Parameters
+ ----------
+ %(input)s
+ order : int, optional
+ The order of the spline, default is 3.
+ output : ndarray or dtype, optional
+ The array in which to place the output, or the dtype of the returned
+ array. Default is ``numpy.float64``.
+ %(mode_interp_mirror)s
+
+ Returns
+ -------
+ spline_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ See Also
+ --------
+ spline_filter1d : Calculate a 1-D spline filter along the given axis.
+
+ Notes
+ -----
+ The multidimensional filter is implemented as a sequence of
+ 1-D spline filters. The intermediate arrays are stored
+ in the same data type as the output. Therefore, for output types
+ with a limited precision, the results may be imprecise because
+ intermediate results may be stored with insufficient precision.
+
+ For complex-valued `input`, this function processes the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ We can filter an image using multidimensional splines:
+
+ >>> from scipy.ndimage import spline_filter
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> orig_img = np.eye(20) # create an image
+ >>> orig_img[10, :] = 1.0
+ >>> sp_filter = spline_filter(orig_img, order=3)
+ >>> f, ax = plt.subplots(1, 2, sharex=True)
+ >>> for ind, data in enumerate([[orig_img, "original image"],
+ ... [sp_filter, "spline filter"]]):
+ ... ax[ind].imshow(data[0], cmap='gray_r')
+ ... ax[ind].set_title(data[1])
+ >>> plt.tight_layout()
+ >>> plt.show()
+
+ """
+ if order < 2 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input,
+ complex_output=complex_output)
+ if complex_output:
+ spline_filter(input.real, order, output.real, mode)
+ spline_filter(input.imag, order, output.imag, mode)
+ return output
+ if order not in [0, 1] and input.ndim > 0:
+ for axis in range(input.ndim):
+ spline_filter1d(input, order, axis, output=output, mode=mode)
+ input = output
+ else:
+ output[...] = input[...]
+ return output
+
+
+def _prepad_for_spline_filter(input, mode, cval):
+ if mode in ['nearest', 'grid-constant']:
+ npad = 12
+ if mode == 'grid-constant':
+ padded = np.pad(input, npad, mode='constant',
+ constant_values=cval)
+ elif mode == 'nearest':
+ padded = np.pad(input, npad, mode='edge')
+ else:
+ # other modes have exact boundary conditions implemented so
+ # no prepadding is needed
+ npad = 0
+ padded = input
+ return padded, npad
+
+
+@docfiller
+def geometric_transform(input, mapping, output_shape=None,
+ output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True,
+ extra_arguments=(), extra_keywords=None):
+ """
+ Apply an arbitrary geometric transform.
+
+ The given mapping function is used to find, for each point in the
+ output, the corresponding coordinates in the input. The value of the
+ input at those coordinates is determined by spline interpolation of
+ the requested order.
+
+ Parameters
+ ----------
+ %(input)s
+ mapping : {callable, scipy.LowLevelCallable}
+ A callable object that accepts a tuple of length equal to the output
+ array rank, and returns the corresponding input coordinates as a tuple
+ of length equal to the input array rank.
+ output_shape : tuple of ints, optional
+ Shape tuple.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+ extra_arguments : tuple, optional
+ Extra arguments passed to `mapping`.
+ extra_keywords : dict, optional
+ Extra keywords passed to `mapping`.
+
+ Returns
+ -------
+ output : ndarray
+ The filtered input.
+
+ See Also
+ --------
+ map_coordinates, affine_transform, spline_filter1d
+
+
+ Notes
+ -----
+ This function also accepts low-level callback functions with one
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+ .. code:: c
+
+ int mapping(npy_intp *output_coordinates, double *input_coordinates,
+ int output_rank, int input_rank, void *user_data)
+ int mapping(intptr_t *output_coordinates, double *input_coordinates,
+ int output_rank, int input_rank, void *user_data)
+
+ The calling function iterates over the elements of the output array,
+ calling the callback function at each element. The coordinates of the
+ current output element are passed through ``output_coordinates``. The
+ callback function must return the coordinates at which the input must
+ be interpolated in ``input_coordinates``. The rank of the input and
+ output arrays are given by ``input_rank`` and ``output_rank``
+ respectively. ``user_data`` is the data pointer provided
+ to `scipy.LowLevelCallable` as-is.
+
+ The callback function must return an integer error status that is zero
+ if something went wrong and one otherwise. If an error occurs, you should
+ normally set the Python error status with an informative message
+ before returning, otherwise a default error message is set by the
+ calling function.
+
+ In addition, some other low-level function pointer specifications
+ are accepted, but these are for backward compatibility only and should
+ not be used in new code.
+
+ For complex-valued `input`, this function transforms the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.ndimage import geometric_transform
+ >>> a = np.arange(12.).reshape((4, 3))
+ >>> def shift_func(output_coords):
+ ... return (output_coords[0] - 0.5, output_coords[1] - 0.5)
+ ...
+ >>> geometric_transform(a, shift_func)
+ array([[ 0. , 0. , 0. ],
+ [ 0. , 1.362, 2.738],
+ [ 0. , 4.812, 6.187],
+ [ 0. , 8.263, 9.637]])
+
+ >>> b = [1, 2, 3, 4, 5]
+ >>> def shift_func(output_coords):
+ ... return (output_coords[0] - 3,)
+ ...
+ >>> geometric_transform(b, shift_func, mode='constant')
+ array([0, 0, 0, 1, 2])
+ >>> geometric_transform(b, shift_func, mode='nearest')
+ array([1, 1, 1, 1, 2])
+ >>> geometric_transform(b, shift_func, mode='reflect')
+ array([3, 2, 1, 1, 2])
+ >>> geometric_transform(b, shift_func, mode='wrap')
+ array([2, 3, 4, 1, 2])
+
+ """
+ if extra_keywords is None:
+ extra_keywords = {}
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if output_shape is None:
+ output_shape = input.shape
+ if input.ndim < 1 or len(output_shape) < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if complex_output:
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter,
+ output_shape=output_shape,
+ extra_arguments=extra_arguments,
+ extra_keywords=extra_keywords)
+ geometric_transform(input.real, mapping, output=output.real,
+ cval=np.real(cval), **kwargs)
+ geometric_transform(input.imag, mapping, output=output.imag,
+ cval=np.imag(cval), **kwargs)
+ return output
+
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64,
+ mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.geometric_transform(filtered, mapping, None, None, None, output,
+ order, mode, cval, npad, extra_arguments,
+ extra_keywords)
+ return output
+
+
+@docfiller
+def map_coordinates(input, coordinates, output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True):
+ """
+ Map the input array to new coordinates by interpolation.
+
+ The array of coordinates is used to find, for each point in the output,
+ the corresponding coordinates in the input. The value of the input at
+ those coordinates is determined by spline interpolation of the
+ requested order.
+
+ The shape of the output is derived from that of the coordinate
+ array by dropping the first axis. The values of the array along
+ the first axis are the coordinates in the input array at which the
+ output value is found.
+
+ Parameters
+ ----------
+ %(input)s
+ coordinates : array_like
+ The coordinates at which `input` is evaluated.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ map_coordinates : ndarray
+ The result of transforming the input. The shape of the output is
+ derived from that of `coordinates` by dropping the first axis.
+
+ See Also
+ --------
+ spline_filter, geometric_transform, scipy.interpolate
+
+ Notes
+ -----
+ For complex-valued `input`, this function maps the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.arange(12.).reshape((4, 3))
+ >>> a
+ array([[ 0., 1., 2.],
+ [ 3., 4., 5.],
+ [ 6., 7., 8.],
+ [ 9., 10., 11.]])
+ >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
+ array([ 2., 7.])
+
+ Above, the interpolated value of a[0.5, 0.5] gives output[0], while
+ a[2, 1] is output[1].
+
+ >>> inds = np.array([[0.5, 2], [0.5, 4]])
+ >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
+ array([ 2. , -33.3])
+ >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
+ array([ 2., 8.])
+ >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
+ array([ True, False], dtype=bool)
+
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ coordinates = np.asarray(coordinates)
+ if np.iscomplexobj(coordinates):
+ raise TypeError('Complex type not supported')
+ output_shape = coordinates.shape[1:]
+ if input.ndim < 1 or len(output_shape) < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ if coordinates.shape[0] != input.ndim:
+ raise RuntimeError('invalid shape for coordinate array')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if complex_output:
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+ map_coordinates(input.real, coordinates, output=output.real,
+ cval=np.real(cval), **kwargs)
+ map_coordinates(input.imag, coordinates, output=output.imag,
+ cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.geometric_transform(filtered, None, coordinates, None, None,
+ output, order, mode, cval, npad, None, None)
+ return output
+
+
+@docfiller
+def affine_transform(input, matrix, offset=0.0, output_shape=None,
+ output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True):
+ """
+ Apply an affine transformation.
+
+ Given an output image pixel index vector ``o``, the pixel value
+ is determined from the input image at position
+ ``np.dot(matrix, o) + offset``.
+
+ This does 'pull' (or 'backward') resampling, transforming the output space
+ to the input to locate data. Affine transformations are often described in
+ the 'push' (or 'forward') direction, transforming input to output. If you
+ have a matrix for the 'push' transformation, use its inverse
+ (:func:`numpy.linalg.inv`) in this function.
+
+ Parameters
+ ----------
+ %(input)s
+ matrix : ndarray
+ The inverse coordinate transformation matrix, mapping output
+ coordinates to input coordinates. If ``ndim`` is the number of
+ dimensions of ``input``, the given matrix must have one of the
+ following shapes:
+
+ - ``(ndim, ndim)``: the linear transformation matrix for each
+ output coordinate.
+ - ``(ndim,)``: assume that the 2-D transformation matrix is
+ diagonal, with the diagonal specified by the given value. A more
+ efficient algorithm is then used that exploits the separability
+ of the problem.
+ - ``(ndim + 1, ndim + 1)``: assume that the transformation is
+ specified using homogeneous coordinates [1]_. In this case, any
+ value passed to ``offset`` is ignored.
+ - ``(ndim, ndim + 1)``: as above, but the bottom row of a
+ homogeneous transformation matrix is always ``[0, 0, ..., 1]``,
+ and may be omitted.
+
+ offset : float or sequence, optional
+ The offset into the array where the transform is applied. If a float,
+ `offset` is the same for each axis. If a sequence, `offset` should
+ contain one value for each axis.
+ output_shape : tuple of ints, optional
+ Shape tuple.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ affine_transform : ndarray
+ The transformed input.
+
+ Examples
+ --------
+ Use `affine_transform` to stretch an image::
+
+ >>> from scipy.ndimage import affine_transform
+ >>> from scipy.datasets import face
+ >>> from matplotlib import pyplot as plt
+ >>> import numpy as np
+ >>> im = face(gray=True)
+ >>> matrix = (0.5, 2)
+ >>> im2 = affine_transform(im, matrix)
+ >>> plt.imshow(im2)
+ >>> plt.show()
+
+ Rotate an image by 90 degrees and project it onto an expanded canvas::
+
+ >>> matrix = ((0, 1), (1, 0))
+ >>> im3 = affine_transform(im, matrix, output_shape=(1024, 1024))
+ >>> plt.imshow(im3)
+ >>> plt.show()
+
+ Offset the rotation so that the image is centred::
+
+ >>> output_shape = (1200, 1200)
+ >>> offset = (np.array(im.shape) - output_shape) / 2
+ >>> im4 = affine_transform(im, matrix, offset=offset, output_shape=output_shape)
+ >>> plt.imshow(im4)
+ >>> plt.show()
+
+ Notes
+ -----
+ The given matrix and offset are used to find for each point in the
+ output the corresponding coordinates in the input by an affine
+ transformation. The value of the input at those coordinates is
+ determined by spline interpolation of the requested order. Points
+ outside the boundaries of the input are filled according to the given
+ mode.
+
+ .. versionchanged:: 0.18.0
+ Previously, the exact interpretation of the affine transformation
+ depended on whether the matrix was supplied as a 1-D or a
+ 2-D array. If a 1-D array was supplied
+ to the matrix parameter, the output pixel value at index ``o``
+ was determined from the input image at position
+ ``matrix * (o + offset)``.
+
+ For complex-valued `input`, this function transforms the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Homogeneous_coordinates
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if output_shape is None:
+ if isinstance(output, np.ndarray):
+ output_shape = output.shape
+ else:
+ output_shape = input.shape
+ if input.ndim < 1 or len(output_shape) < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if complex_output:
+ kwargs = dict(offset=offset, output_shape=output_shape, order=order,
+ mode=mode, prefilter=prefilter)
+ affine_transform(input.real, matrix, output=output.real,
+ cval=np.real(cval), **kwargs)
+ affine_transform(input.imag, matrix, output=output.imag,
+ cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ matrix = np.asarray(matrix, dtype=np.float64)
+ if matrix.ndim not in [1, 2] or matrix.shape[0] < 1:
+ raise RuntimeError('no proper affine matrix provided')
+ if (matrix.ndim == 2 and matrix.shape[1] == input.ndim + 1 and
+ (matrix.shape[0] in [input.ndim, input.ndim + 1])):
+ if matrix.shape[0] == input.ndim + 1:
+ exptd = [0] * input.ndim + [1]
+ if not np.all(matrix[input.ndim] == exptd):
+ msg = (f'Expected homogeneous transformation matrix with '
+ f'shape {matrix.shape} for image shape {input.shape}, '
+ f'but bottom row was not equal to {exptd}')
+ raise ValueError(msg)
+ # assume input is homogeneous coordinate transformation matrix
+ offset = matrix[:input.ndim, input.ndim]
+ matrix = matrix[:input.ndim, :input.ndim]
+ if matrix.shape[0] != input.ndim:
+ raise RuntimeError('affine matrix has wrong number of rows')
+ if matrix.ndim == 2 and matrix.shape[1] != output.ndim:
+ raise RuntimeError('affine matrix has wrong number of columns')
+ if not matrix.flags.contiguous:
+ matrix = matrix.copy()
+ offset = _ni_support._normalize_sequence(offset, input.ndim)
+ offset = np.asarray(offset, dtype=np.float64)
+ if offset.ndim != 1 or offset.shape[0] < 1:
+ raise RuntimeError('no proper offset provided')
+ if not offset.flags.contiguous:
+ offset = offset.copy()
+ if matrix.ndim == 1:
+ _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order,
+ mode, cval, npad, False)
+ else:
+ _nd_image.geometric_transform(filtered, None, None, matrix, offset,
+ output, order, mode, cval, npad, None,
+ None)
+ return output
+
+
+@docfiller
+def shift(input, shift, output=None, order=3, mode='constant', cval=0.0,
+ prefilter=True):
+ """
+ Shift an array.
+
+ The array is shifted using spline interpolation of the requested order.
+ Points outside the boundaries of the input are filled according to the
+ given mode.
+
+ Parameters
+ ----------
+ %(input)s
+ shift : float or sequence
+ The shift along the axes. If a float, `shift` is the same for each
+ axis. If a sequence, `shift` should contain one value for each axis.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ shift : ndarray
+ The shifted input.
+
+ See Also
+ --------
+ affine_transform : Affine transformations
+
+ Notes
+ -----
+ For complex-valued `input`, this function shifts the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ Import the necessary modules and an exemplary image.
+
+ >>> from scipy.ndimage import shift
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy import datasets
+ >>> image = datasets.ascent()
+
+ Shift the image vertically by 20 pixels.
+
+ >>> image_shifted_vertically = shift(image, (20, 0))
+
+ Shift the image vertically by -200 pixels and horizontally by 100 pixels.
+
+ >>> image_shifted_both_directions = shift(image, (-200, 100))
+
+ Plot the original and the shifted images.
+
+ >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12))
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> top, middle, bottom = axes
+ >>> for ax in axes:
+ ... ax.set_axis_off() # remove coordinate system
+ >>> top.imshow(image)
+ >>> top.set_title("Original image")
+ >>> middle.imshow(image_shifted_vertically)
+ >>> middle.set_title("Vertically shifted image")
+ >>> bottom.imshow(image_shifted_both_directions)
+ >>> bottom.set_title("Image shifted in both directions")
+ >>> fig.tight_layout()
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if input.ndim < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, complex_output=complex_output)
+ if complex_output:
+ # import under different name to avoid confusion with shift parameter
+ from scipy.ndimage._interpolation import shift as _shift
+
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+ _shift(input.real, shift, output=output.real, cval=np.real(cval), **kwargs)
+ _shift(input.imag, shift, output=output.imag, cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ shift = _ni_support._normalize_sequence(shift, input.ndim)
+ shift = [-ii for ii in shift]
+ shift = np.asarray(shift, dtype=np.float64)
+ if not shift.flags.contiguous:
+ shift = shift.copy()
+ _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval,
+ npad, False)
+ return output
+
+
+@docfiller
+def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,
+ prefilter=True, *, grid_mode=False):
+ """
+ Zoom an array.
+
+ The array is zoomed using spline interpolation of the requested order.
+
+ Parameters
+ ----------
+ %(input)s
+ zoom : float or sequence
+ The zoom factor along the axes. If a float, `zoom` is the same for each
+ axis. If a sequence, `zoom` should contain one value for each axis.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+ grid_mode : bool, optional
+ If False, the distance from the pixel centers is zoomed. Otherwise, the
+ distance including the full pixel extent is used. For example, a 1d
+ signal of length 5 is considered to have length 4 when `grid_mode` is
+ False, but length 5 when `grid_mode` is True. See the following
+ visual illustration:
+
+ .. code-block:: text
+
+ | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
+ |<-------------------------------------->|
+ vs.
+ |<----------------------------------------------->|
+
+ The starting point of the arrow in the diagram above corresponds to
+ coordinate location 0 in each mode.
+
+ Returns
+ -------
+ zoom : ndarray
+ The zoomed input.
+
+ Notes
+ -----
+ For complex-valued `input`, this function zooms the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+
+ >>> fig = plt.figure()
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.zoom(ascent, 3.0)
+ >>> ax1.imshow(ascent, vmin=0, vmax=255)
+ >>> ax2.imshow(result, vmin=0, vmax=255)
+ >>> plt.show()
+
+ >>> print(ascent.shape)
+ (512, 512)
+
+ >>> print(result.shape)
+ (1536, 1536)
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if input.ndim < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ zoom = _ni_support._normalize_sequence(zoom, input.ndim)
+ output_shape = tuple(
+ [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)])
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if all(z == 1 for z in zoom) and prefilter: # early exit for gh-20999
+ # zoom 1 means "return original image". If `prefilter=False`,
+ # `input` is *not* the original image; processing is still needed
+ # to undo the filter. So we only early exit if `prefilter`.
+ output = xpx.at(output)[...].set(input)
+ return output
+ if complex_output:
+ # import under different name to avoid confusion with zoom parameter
+ from scipy.ndimage._interpolation import zoom as _zoom
+
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+ _zoom(input.real, zoom, output=output.real, cval=np.real(cval), **kwargs)
+ _zoom(input.imag, zoom, output=output.imag, cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ if grid_mode:
+ # warn about modes that may have surprising behavior
+ suggest_mode = None
+ if mode == 'constant':
+ suggest_mode = 'grid-constant'
+ elif mode == 'wrap':
+ suggest_mode = 'grid-wrap'
+ if suggest_mode is not None:
+ warnings.warn(
+ (f"It is recommended to use mode = {suggest_mode} instead of {mode} "
+ f"when grid_mode is True."),
+ stacklevel=2
+ )
+ mode = _ni_support._extend_mode_to_code(mode)
+
+ zoom_div = np.array(output_shape)
+ zoom_nominator = np.array(input.shape)
+ if not grid_mode:
+ zoom_div -= 1
+ zoom_nominator -= 1
+
+ # Zooming to infinite values is unpredictable, so just choose
+ # zoom factor 1 instead
+ zoom = np.divide(zoom_nominator, zoom_div,
+ out=np.ones_like(input.shape, dtype=np.float64),
+ where=zoom_div != 0)
+ zoom = np.ascontiguousarray(zoom)
+ _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad,
+ grid_mode)
+ return output
+
+
+@docfiller
+def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True):
+ """
+ Rotate an array.
+
+ The array is rotated in the plane defined by the two axes given by the
+ `axes` parameter using spline interpolation of the requested order.
+
+ Parameters
+ ----------
+ %(input)s
+ angle : float
+ The rotation angle in degrees.
+ axes : tuple of 2 ints, optional
+ The two axes that define the plane of rotation. Default is the first
+ two axes.
+ reshape : bool, optional
+ If `reshape` is true, the output shape is adapted so that the input
+ array is contained completely in the output. Default is True.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ rotate : ndarray
+ The rotated input.
+
+ Notes
+ -----
+ For complex-valued `input`, this function rotates the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure(figsize=(10, 3))
+ >>> ax1, ax2, ax3 = fig.subplots(1, 3)
+ >>> img = datasets.ascent()
+ >>> img_45 = ndimage.rotate(img, 45, reshape=False)
+ >>> full_img_45 = ndimage.rotate(img, 45, reshape=True)
+ >>> ax1.imshow(img, cmap='gray')
+ >>> ax1.set_axis_off()
+ >>> ax2.imshow(img_45, cmap='gray')
+ >>> ax2.set_axis_off()
+ >>> ax3.imshow(full_img_45, cmap='gray')
+ >>> ax3.set_axis_off()
+ >>> fig.set_layout_engine('tight')
+ >>> plt.show()
+ >>> print(img.shape)
+ (512, 512)
+ >>> print(img_45.shape)
+ (512, 512)
+ >>> print(full_img_45.shape)
+ (724, 724)
+
+ """
+ input_arr = np.asarray(input)
+ ndim = input_arr.ndim
+
+ if ndim < 2:
+ raise ValueError('input array should be at least 2D')
+
+ axes = list(axes)
+
+ if len(axes) != 2:
+ raise ValueError('axes should contain exactly two values')
+
+ if not all([float(ax).is_integer() for ax in axes]):
+ raise ValueError('axes should contain only integer values')
+
+ if axes[0] < 0:
+ axes[0] += ndim
+ if axes[1] < 0:
+ axes[1] += ndim
+ if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
+ raise ValueError('invalid rotation plane specified')
+
+ axes.sort()
+
+ c, s = special.cosdg(angle), special.sindg(angle)
+
+ rot_matrix = np.array([[c, s],
+ [-s, c]])
+
+ img_shape = np.asarray(input_arr.shape)
+ in_plane_shape = img_shape[axes]
+ if reshape:
+ # Compute transformed input bounds
+ iy, ix = in_plane_shape
+ out_bounds = rot_matrix @ [[0, 0, iy, iy],
+ [0, ix, 0, ix]]
+ # Compute the shape of the transformed input plane
+ out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int)
+ else:
+ out_plane_shape = img_shape[axes]
+
+ out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
+ in_center = (in_plane_shape - 1) / 2
+ offset = in_center - out_center
+
+ output_shape = img_shape
+ output_shape[axes] = out_plane_shape
+ output_shape = tuple(output_shape)
+
+ complex_output = np.iscomplexobj(input_arr)
+ output = _ni_support._get_output(output, input_arr, shape=output_shape,
+ complex_output=complex_output)
+
+ if ndim <= 2:
+ affine_transform(input_arr, rot_matrix, offset, output_shape, output,
+ order, mode, cval, prefilter)
+ else:
+ # If ndim > 2, the rotation is applied over all the planes
+ # parallel to axes
+ planes_coord = itertools.product(
+ *[[slice(None)] if ax in axes else range(img_shape[ax])
+ for ax in range(ndim)])
+
+ out_plane_shape = tuple(out_plane_shape)
+
+ for coordinates in planes_coord:
+ ia = input_arr[coordinates]
+ oa = output[coordinates]
+ affine_transform(ia, rot_matrix, offset, out_plane_shape,
+ oa, order, mode, cval, prefilter)
+
+ return output
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_measurements.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..f764390524940b4117e1fe2ebff14ded6625b831
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_measurements.py
@@ -0,0 +1,1689 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import numpy as np
+from . import _ni_support
+from . import _ni_label
+from . import _nd_image
+from . import _morphology
+
+__all__ = ['label', 'find_objects', 'labeled_comprehension', 'sum', 'mean',
+ 'variance', 'standard_deviation', 'minimum', 'maximum', 'median',
+ 'minimum_position', 'maximum_position', 'extrema', 'center_of_mass',
+ 'histogram', 'watershed_ift', 'sum_labels', 'value_indices']
+
+
+def label(input, structure=None, output=None):
+ """
+ Label features in an array.
+
+ Parameters
+ ----------
+ input : array_like
+ An array-like object to be labeled. Any non-zero values in `input` are
+ counted as features and zero values are considered the background.
+ structure : array_like, optional
+ A structuring element that defines feature connections.
+ `structure` must be centrosymmetric
+ (see Notes).
+ If no structuring element is provided,
+ one is automatically generated with a squared connectivity equal to
+ one. That is, for a 2-D `input` array, the default structuring element
+ is::
+
+ [[0,1,0],
+ [1,1,1],
+ [0,1,0]]
+
+ output : (None, data-type, array_like), optional
+ If `output` is a data type, it specifies the type of the resulting
+ labeled feature array.
+ If `output` is an array-like object, then `output` will be updated
+ with the labeled features from this function. This function can
+ operate in-place, by passing output=input.
+ Note that the output must be able to store the largest label, or this
+ function will raise an Exception.
+
+ Returns
+ -------
+ label : ndarray or int
+ An integer ndarray where each unique feature in `input` has a unique
+ label in the returned array.
+ num_features : int
+ How many objects were found.
+
+ If `output` is None, this function returns a tuple of
+ (`labeled_array`, `num_features`).
+
+ If `output` is an ndarray, then it will be updated with values in
+ `labeled_array` and only `num_features` will be returned by this
+ function.
+
+ See Also
+ --------
+ find_objects : generate a list of slices for the labeled features (or
+ objects); useful for finding features' position or
+ dimensions
+
+ Notes
+ -----
+ A centrosymmetric matrix is a matrix that is symmetric about the center.
+ See [1]_ for more information.
+
+ The `structure` matrix must be centrosymmetric to ensure
+ two-way connections.
+ For instance, if the `structure` matrix is not centrosymmetric
+ and is defined as::
+
+ [[0,1,0],
+ [1,1,0],
+ [0,0,0]]
+
+ and the `input` is::
+
+ [[1,2],
+ [0,3]]
+
+ then the structure matrix would indicate the
+ entry 2 in the input is connected to 1,
+ but 1 is not connected to 2.
+
+ References
+ ----------
+ .. [1] James R. Weaver, "Centrosymmetric (cross-symmetric)
+ matrices, their basic properties, eigenvalues, and
+ eigenvectors." The American Mathematical Monthly 92.10
+ (1985): 711-717.
+
+ Examples
+ --------
+ Create an image with some features, then label it using the default
+ (cross-shaped) structuring element:
+
+ >>> from scipy.ndimage import label, generate_binary_structure
+ >>> import numpy as np
+ >>> a = np.array([[0,0,1,1,0,0],
+ ... [0,0,0,1,0,0],
+ ... [1,1,0,0,1,0],
+ ... [0,0,0,1,0,0]])
+ >>> labeled_array, num_features = label(a)
+
+ Each of the 4 features are labeled with a different integer:
+
+ >>> num_features
+ 4
+ >>> labeled_array
+ array([[0, 0, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0],
+ [2, 2, 0, 0, 3, 0],
+ [0, 0, 0, 4, 0, 0]], dtype=int32)
+
+ Generate a structuring element that will consider features connected even
+ if they touch diagonally:
+
+ >>> s = generate_binary_structure(2,2)
+
+ or,
+
+ >>> s = [[1,1,1],
+ ... [1,1,1],
+ ... [1,1,1]]
+
+ Label the image using the new structuring element:
+
+ >>> labeled_array, num_features = label(a, structure=s)
+
+ Show the 2 labeled features (note that features 1, 3, and 4 from above are
+ now considered a single feature):
+
+ >>> num_features
+ 2
+ >>> labeled_array
+ array([[0, 0, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0],
+ [2, 2, 0, 0, 1, 0],
+ [0, 0, 0, 1, 0, 0]], dtype=int32)
+
+ """
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ if structure is None:
+ structure = _morphology.generate_binary_structure(input.ndim, 1)
+ structure = np.asarray(structure, dtype=bool)
+ if structure.ndim != input.ndim:
+ raise RuntimeError('structure and input must have equal rank')
+ for ii in structure.shape:
+ if ii != 3:
+ raise ValueError('structure dimensions must be equal to 3')
+
+ # Use 32 bits if it's large enough for this image.
+ # _ni_label.label() needs two entries for background and
+ # foreground tracking
+ need_64bits = input.size >= (2**31 - 2)
+
+ if isinstance(output, np.ndarray):
+ if output.shape != input.shape:
+ raise ValueError("output shape not correct")
+ caller_provided_output = True
+ else:
+ caller_provided_output = False
+ if output is None:
+ output = np.empty(input.shape, np.intp if need_64bits else np.int32)
+ else:
+ output = np.empty(input.shape, output)
+
+ # handle scalars, 0-D arrays
+ if input.ndim == 0 or input.size == 0:
+ if input.ndim == 0:
+ # scalar
+ maxlabel = 1 if (input != 0) else 0
+ output[...] = maxlabel
+ else:
+ # 0-D
+ maxlabel = 0
+ if caller_provided_output:
+ return maxlabel
+ else:
+ return output, maxlabel
+
+ try:
+ max_label = _ni_label._label(input, structure, output)
+ except _ni_label.NeedMoreBits as e:
+ # Make another attempt with enough bits, then try to cast to the
+ # new type.
+ tmp_output = np.empty(input.shape, np.intp if need_64bits else np.int32)
+ max_label = _ni_label._label(input, structure, tmp_output)
+ output[...] = tmp_output[...]
+ if not np.all(output == tmp_output):
+ # refuse to return bad results
+ raise RuntimeError(
+ "insufficient bit-depth in requested output type"
+ ) from e
+
+ if caller_provided_output:
+ # result was written in-place
+ return max_label
+ else:
+ return output, max_label
+
+
+def find_objects(input, max_label=0):
+ """
+ Find objects in a labeled array.
+
+ Parameters
+ ----------
+ input : ndarray of ints
+ Array containing objects defined by different labels. Labels with
+ value 0 are ignored.
+ max_label : int, optional
+ Maximum label to be searched for in `input`. If max_label is not
+ given, the positions of all objects are returned.
+
+ Returns
+ -------
+ object_slices : list of tuples
+ A list of tuples, with each tuple containing N slices (with N the
+ dimension of the input array). Slices correspond to the minimal
+ parallelepiped that contains the object. If a number is missing,
+ None is returned instead of a slice. The label ``l`` corresponds to
+ the index ``l-1`` in the returned list.
+
+ See Also
+ --------
+ label, center_of_mass
+
+ Notes
+ -----
+ This function is very useful for isolating a volume of interest inside
+ a 3-D array, that cannot be "seen through".
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((6,6), dtype=int)
+ >>> a[2:4, 2:4] = 1
+ >>> a[4, 4] = 1
+ >>> a[:2, :3] = 2
+ >>> a[0, 5] = 3
+ >>> a
+ array([[2, 2, 2, 0, 0, 3],
+ [2, 2, 2, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 0]])
+ >>> ndimage.find_objects(a)
+ [(slice(2, 5, None), slice(2, 5, None)),
+ (slice(0, 2, None), slice(0, 3, None)),
+ (slice(0, 1, None), slice(5, 6, None))]
+ >>> ndimage.find_objects(a, max_label=2)
+ [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))]
+ >>> ndimage.find_objects(a == 1, max_label=2)
+ [(slice(2, 5, None), slice(2, 5, None)), None]
+
+ >>> loc = ndimage.find_objects(a)[0]
+ >>> a[loc]
+ array([[1, 1, 0],
+ [1, 1, 0],
+ [0, 0, 1]])
+
+ """
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+
+ if max_label < 1:
+ max_label = input.max()
+
+ return _nd_image.find_objects(input, max_label)
+
+
+def value_indices(arr, *, ignore_value=None):
+ """
+ Find indices of each distinct value in given array.
+
+ Parameters
+ ----------
+ arr : ndarray of ints
+ Array containing integer values.
+ ignore_value : int, optional
+ This value will be ignored in searching the `arr` array. If not
+ given, all values found will be included in output. Default
+ is None.
+
+ Returns
+ -------
+ indices : dictionary
+ A Python dictionary of array indices for each distinct value. The
+ dictionary is keyed by the distinct values, the entries are array
+ index tuples covering all occurrences of the value within the
+ array.
+
+ This dictionary can occupy significant memory, usually several times
+ the size of the input array.
+
+ See Also
+ --------
+ label, maximum, median, minimum_position, extrema, sum, mean, variance,
+ standard_deviation, numpy.where, numpy.unique
+
+ Notes
+ -----
+ For a small array with few distinct values, one might use
+ `numpy.unique()` to find all possible values, and ``(arr == val)`` to
+ locate each value within that array. However, for large arrays,
+ with many distinct values, this can become extremely inefficient,
+ as locating each value would require a new search through the entire
+ array. Using this function, there is essentially one search, with
+ the indices saved for all distinct values.
+
+ This is useful when matching a categorical image (e.g. a segmentation
+ or classification) to an associated image of other data, allowing
+ any per-class statistic(s) to then be calculated. Provides a
+ more flexible alternative to functions like ``scipy.ndimage.mean()``
+ and ``scipy.ndimage.variance()``.
+
+ Some other closely related functionality, with different strengths and
+ weaknesses, can also be found in ``scipy.stats.binned_statistic()`` and
+ the `scikit-image `_ function
+ ``skimage.measure.regionprops()``.
+
+ Note for IDL users: this provides functionality equivalent to IDL's
+ REVERSE_INDICES option (as per the IDL documentation for the
+ `HISTOGRAM `_
+ function).
+
+ .. versionadded:: 1.10.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import ndimage
+ >>> a = np.zeros((6, 6), dtype=int)
+ >>> a[2:4, 2:4] = 1
+ >>> a[4, 4] = 1
+ >>> a[:2, :3] = 2
+ >>> a[0, 5] = 3
+ >>> a
+ array([[2, 2, 2, 0, 0, 3],
+ [2, 2, 2, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 0]])
+ >>> val_indices = ndimage.value_indices(a)
+
+ The dictionary `val_indices` will have an entry for each distinct
+ value in the input array.
+
+ >>> val_indices.keys()
+ dict_keys([np.int64(0), np.int64(1), np.int64(2), np.int64(3)])
+
+ The entry for each value is an index tuple, locating the elements
+ with that value.
+
+ >>> ndx1 = val_indices[1]
+ >>> ndx1
+ (array([2, 2, 3, 3, 4]), array([2, 3, 2, 3, 4]))
+
+ This can be used to index into the original array, or any other
+ array with the same shape.
+
+ >>> a[ndx1]
+ array([1, 1, 1, 1, 1])
+
+ If the zeros were to be ignored, then the resulting dictionary
+ would no longer have an entry for zero.
+
+ >>> val_indices = ndimage.value_indices(a, ignore_value=0)
+ >>> val_indices.keys()
+ dict_keys([np.int64(1), np.int64(2), np.int64(3)])
+
+ """
+ # Cope with ignore_value being None, without too much extra complexity
+ # in the C code. If not None, the value is passed in as a numpy array
+ # with the same dtype as arr.
+ arr = np.asarray(arr)
+ ignore_value_arr = np.zeros((1,), dtype=arr.dtype)
+ ignoreIsNone = (ignore_value is None)
+ if not ignoreIsNone:
+ ignore_value_arr[0] = ignore_value_arr.dtype.type(ignore_value)
+
+ val_indices = _nd_image.value_indices(arr, ignoreIsNone, ignore_value_arr)
+ return val_indices
+
+
+def labeled_comprehension(input, labels, index, func, out_dtype, default,
+ pass_positions=False):
+ """
+ Roughly equivalent to [func(input[labels == i]) for i in index].
+
+ Sequentially applies an arbitrary function (that works on array_like input)
+ to subsets of an N-D image array specified by `labels` and `index`.
+ The option exists to provide the function with positional parameters as the
+ second argument.
+
+ Parameters
+ ----------
+ input : array_like
+ Data from which to select `labels` to process.
+ labels : array_like or None
+ Labels to objects in `input`.
+ If not None, array must be same shape as `input`.
+ If None, `func` is applied to raveled `input`.
+ index : int, sequence of ints or None
+ Subset of `labels` to which to apply `func`.
+ If a scalar, a single value is returned.
+ If None, `func` is applied to all non-zero values of `labels`.
+ func : callable
+ Python function to apply to `labels` from `input`.
+ out_dtype : dtype
+ Dtype to use for `result`.
+ default : int, float or None
+ Default return value when an element of `index` does not exist
+ in `labels`.
+ pass_positions : bool, optional
+ If True, pass linear indices to `func` as a second argument.
+ Default is False.
+
+ Returns
+ -------
+ result : ndarray
+ Result of applying `func` to each of `labels` to `input` in `index`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> lbls = np.arange(1, nlbl+1)
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0)
+ array([ 2.75, 5.5 , 6. ])
+
+ Falling back to `default`:
+
+ >>> lbls = np.arange(1, nlbl+2)
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1)
+ array([ 2.75, 5.5 , 6. , -1. ])
+
+ Passing positions:
+
+ >>> def fn(val, pos):
+ ... print("fn says: %s : %s" % (val, pos))
+ ... return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum())
+ ...
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True)
+ fn says: [1 2 5 3] : [0 1 4 5]
+ fn says: [4 7] : [ 7 11]
+ fn says: [9 3] : [12 13]
+ array([ 11., 11., -12., 0.])
+
+ """
+
+ as_scalar = np.isscalar(index)
+ input = np.asarray(input)
+
+ if pass_positions:
+ positions = np.arange(input.size).reshape(input.shape)
+
+ if labels is None:
+ if index is not None:
+ raise ValueError("index without defined labels")
+ if not pass_positions:
+ return func(input.ravel())
+ else:
+ return func(input.ravel(), positions.ravel())
+
+ labels = np.asarray(labels)
+
+ try:
+ input, labels = np.broadcast_arrays(input, labels)
+ except ValueError as e:
+ raise ValueError("input and labels must have the same shape "
+ "(excepting dimensions with width 1)") from e
+
+ if index is None:
+ if not pass_positions:
+ return func(input[labels > 0])
+ else:
+ return func(input[labels > 0], positions[labels > 0])
+
+ index = np.atleast_1d(index)
+ if np.any(index.astype(labels.dtype).astype(index.dtype) != index):
+ raise ValueError(f"Cannot convert index values from <{index.dtype}> to "
+ f"<{labels.dtype}> (labels' type) without loss of precision")
+
+ index = index.astype(labels.dtype)
+
+ # optimization: find min/max in index,
+ # and select those parts of labels, input, and positions
+ lo = index.min()
+ hi = index.max()
+ mask = (labels >= lo) & (labels <= hi)
+
+ # this also ravels the arrays
+ labels = labels[mask]
+ input = input[mask]
+ if pass_positions:
+ positions = positions[mask]
+
+ # sort everything by labels
+ label_order = labels.argsort()
+ labels = labels[label_order]
+ input = input[label_order]
+ if pass_positions:
+ positions = positions[label_order]
+
+ index_order = index.argsort()
+ sorted_index = index[index_order]
+
+ def do_map(inputs, output):
+ """labels must be sorted"""
+ nidx = sorted_index.size
+
+ # Find boundaries for each stretch of constant labels
+ # This could be faster, but we already paid N log N to sort labels.
+ lo = np.searchsorted(labels, sorted_index, side='left')
+ hi = np.searchsorted(labels, sorted_index, side='right')
+
+ for i, l, h in zip(range(nidx), lo, hi):
+ if l == h:
+ continue
+ output[i] = func(*[inp[l:h] for inp in inputs])
+
+ temp = np.empty(index.shape, out_dtype)
+ temp[:] = default
+ if not pass_positions:
+ do_map([input], temp)
+ else:
+ do_map([input, positions], temp)
+
+ output = np.zeros(index.shape, out_dtype)
+ output[index_order] = temp
+ if as_scalar:
+ output = output[0]
+
+ return output
+
+
+def _safely_castable_to_int(dt):
+ """Test whether the NumPy data type `dt` can be safely cast to an int."""
+ int_size = np.dtype(int).itemsize
+ safe = ((np.issubdtype(dt, np.signedinteger) and dt.itemsize <= int_size) or
+ (np.issubdtype(dt, np.unsignedinteger) and dt.itemsize < int_size))
+ return safe
+
+
+def _stats(input, labels=None, index=None, centered=False):
+ """Count, sum, and optionally compute (sum - centre)^2 of input by label
+
+ Parameters
+ ----------
+ input : array_like, N-D
+ The input data to be analyzed.
+ labels : array_like (N-D), optional
+ The labels of the data in `input`. This array must be broadcast
+ compatible with `input`; typically, it is the same shape as `input`.
+ If `labels` is None, all nonzero values in `input` are treated as
+ the single labeled group.
+ index : label or sequence of labels, optional
+ These are the labels of the groups for which the stats are computed.
+ If `index` is None, the stats are computed for the single group where
+ `labels` is greater than 0.
+ centered : bool, optional
+ If True, the centered sum of squares for each labeled group is
+ also returned. Default is False.
+
+ Returns
+ -------
+ counts : int or ndarray of ints
+ The number of elements in each labeled group.
+ sums : scalar or ndarray of scalars
+ The sums of the values in each labeled group.
+ sums_c : scalar or ndarray of scalars, optional
+ The sums of mean-centered squares of the values in each labeled group.
+ This is only returned if `centered` is True.
+
+ """
+ def single_group(vals):
+ if centered:
+ vals_c = vals - vals.mean()
+ return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum()
+ else:
+ return vals.size, vals.sum()
+
+ input = np.asarray(input)
+ if labels is None:
+ return single_group(input)
+
+ labels = np.asarray(labels)
+ # ensure input and labels match sizes
+ input, labels = np.broadcast_arrays(input, labels)
+
+ if index is None:
+ return single_group(input[labels > 0])
+
+ if np.isscalar(index):
+ return single_group(input[labels == index])
+
+ def _sum_centered(labels):
+ # `labels` is expected to be an ndarray with the same shape as `input`.
+ # It must contain the label indices (which are not necessarily the labels
+ # themselves).
+ means = sums / counts
+ centered_input = input - means[labels]
+ # bincount expects 1-D inputs, so we ravel the arguments.
+ bc = np.bincount(labels.ravel(),
+ weights=(centered_input *
+ centered_input.conjugate()).ravel())
+ return bc
+
+ # Remap labels to unique integers if necessary, or if the largest
+ # label is larger than the number of values.
+
+ if (not _safely_castable_to_int(labels.dtype) or
+ labels.min() < 0 or labels.max() > labels.size):
+ # Use np.unique to generate the label indices. `new_labels` will
+ # be 1-D, but it should be interpreted as the flattened N-D array of
+ # label indices.
+ unique_labels, new_labels = np.unique(labels, return_inverse=True)
+ new_labels = np.reshape(new_labels, (-1,)) # flatten, since it may be >1-D
+ counts = np.bincount(new_labels)
+ sums = np.bincount(new_labels, weights=input.ravel())
+ if centered:
+ # Compute the sum of the mean-centered squares.
+ # We must reshape new_labels to the N-D shape of `input` before
+ # passing it _sum_centered.
+ sums_c = _sum_centered(new_labels.reshape(labels.shape))
+ idxs = np.searchsorted(unique_labels, index)
+ # make all of idxs valid
+ idxs[idxs >= unique_labels.size] = 0
+ found = (unique_labels[idxs] == index)
+ else:
+ # labels are an integer type allowed by bincount, and there aren't too
+ # many, so call bincount directly.
+ counts = np.bincount(labels.ravel())
+ sums = np.bincount(labels.ravel(), weights=input.ravel())
+ if centered:
+ sums_c = _sum_centered(labels)
+ # make sure all index values are valid
+ idxs = np.asanyarray(index, np.int_).copy()
+ found = (idxs >= 0) & (idxs < counts.size)
+ idxs[~found] = 0
+
+ counts = counts[idxs]
+ counts[~found] = 0
+ sums = sums[idxs]
+ sums[~found] = 0
+
+ if not centered:
+ return (counts, sums)
+ else:
+ sums_c = sums_c[idxs]
+ sums_c[~found] = 0
+ return (counts, sums, sums_c)
+
+
+def sum(input, labels=None, index=None):
+ """
+ Calculate the sum of the values of the array.
+
+ Notes
+ -----
+ This is an alias for `ndimage.sum_labels` kept for backwards compatibility
+ reasons, for new code please prefer `sum_labels`. See the `sum_labels`
+ docstring for more details.
+
+ """ # numpydoc ignore=RT01
+ return sum_labels(input, labels, index)
+
+
+def sum_labels(input, labels=None, index=None):
+ """
+ Calculate the sum of the values of the array.
+
+ Parameters
+ ----------
+ input : array_like
+ Values of `input` inside the regions defined by `labels`
+ are summed together.
+ labels : array_like of ints, optional
+ Assign labels to the values of the array. Has to have the same shape as
+ `input`.
+ index : array_like, optional
+ A single label number or a sequence of label numbers of
+ the objects to be measured.
+
+ Returns
+ -------
+ sum : ndarray or scalar
+ An array of the sums of values of `input` inside the regions defined
+ by `labels` with the same shape as `index`. If 'index' is None or scalar,
+ a scalar is returned.
+
+ See Also
+ --------
+ mean, median
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> input = [0,1,2,3]
+ >>> labels = [1,1,2,2]
+ >>> ndimage.sum_labels(input, labels, index=[1,2])
+ [1.0, 5.0]
+ >>> ndimage.sum_labels(input, labels, index=1)
+ 1
+ >>> ndimage.sum_labels(input, labels)
+ 6
+
+
+ """
+ count, sum = _stats(input, labels, index)
+ return sum
+
+
+def mean(input, labels=None, index=None):
+ """
+ Calculate the mean of the values of an array at labels.
+
+ Parameters
+ ----------
+ input : array_like
+ Array on which to compute the mean of elements over distinct
+ regions.
+ labels : array_like, optional
+ Array of labels of same shape, or broadcastable to the same shape as
+ `input`. All elements sharing the same label form one region over
+ which the mean of the elements is computed.
+ index : int or sequence of ints, optional
+ Labels of the objects over which the mean is to be computed.
+ Default is None, in which case the mean for all values where label is
+ greater than 0 is calculated.
+
+ Returns
+ -------
+ out : list
+ Sequence of same length as `index`, with the mean of the different
+ regions labeled by the labels in `index`.
+
+ See Also
+ --------
+ variance, standard_deviation, minimum, maximum, sum, label
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.arange(25).reshape((5,5))
+ >>> labels = np.zeros_like(a)
+ >>> labels[3:5,3:5] = 1
+ >>> index = np.unique(labels)
+ >>> labels
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1],
+ [0, 0, 0, 1, 1]])
+ >>> index
+ array([0, 1])
+ >>> ndimage.mean(a, labels=labels, index=index)
+ [10.285714285714286, 21.0]
+
+ """
+
+ count, sum = _stats(input, labels, index)
+ return sum / np.asanyarray(count).astype(np.float64)
+
+
+def variance(input, labels=None, index=None):
+ """
+ Calculate the variance of the values of an N-D image array, optionally at
+ specified sub-regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Nd-image data to process.
+ labels : array_like, optional
+ Labels defining sub-regions in `input`.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ `labels` to include in output. If None (default), all values where
+ `labels` is non-zero are used.
+
+ Returns
+ -------
+ variance : float or ndarray
+ Values of variance, for each sub-region if `labels` and `index` are
+ specified.
+
+ See Also
+ --------
+ label, standard_deviation, maximum, minimum, extrema
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.variance(a)
+ 7.609375
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1))
+ array([ 2.1875, 2.25 , 9. ])
+
+ If no index is given, all non-zero `labels` are processed:
+
+ >>> ndimage.variance(a, lbl)
+ 6.1875
+
+ """
+ count, sum, sum_c_sq = _stats(input, labels, index, centered=True)
+ return sum_c_sq / np.asanyarray(count).astype(float)
+
+
+def standard_deviation(input, labels=None, index=None):
+ """
+ Calculate the standard deviation of the values of an N-D image array,
+ optionally at specified sub-regions.
+
+ Parameters
+ ----------
+ input : array_like
+ N-D image data to process.
+ labels : array_like, optional
+ Labels to identify sub-regions in `input`.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ `labels` to include in output. If None (default), all values where
+ `labels` is non-zero are used.
+
+ Returns
+ -------
+ standard_deviation : float or ndarray
+ Values of standard deviation, for each sub-region if `labels` and
+ `index` are specified.
+
+ See Also
+ --------
+ label, variance, maximum, minimum, extrema
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.standard_deviation(a)
+ 2.7585095613392387
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1))
+ array([ 1.479, 1.5 , 3. ])
+
+ If no index is given, non-zero `labels` are processed:
+
+ >>> ndimage.standard_deviation(a, lbl)
+ 2.4874685927665499
+
+ """
+ return np.sqrt(variance(input, labels, index))
+
+
+def _select(input, labels=None, index=None, find_min=False, find_max=False,
+ find_min_positions=False, find_max_positions=False,
+ find_median=False):
+ """Returns min, max, or both, plus their positions (if requested), and
+ median."""
+
+ input = np.asanyarray(input)
+
+ find_positions = find_min_positions or find_max_positions
+ positions = None
+ if find_positions:
+ positions = np.arange(input.size).reshape(input.shape)
+
+ def single_group(vals, positions):
+ result = []
+ if find_min:
+ result += [vals.min()]
+ if find_min_positions:
+ result += [positions[vals == vals.min()][0]]
+ if find_max:
+ result += [vals.max()]
+ if find_max_positions:
+ result += [positions[vals == vals.max()][0]]
+ if find_median:
+ result += [np.median(vals)]
+ return result
+
+ if labels is None:
+ return single_group(input, positions)
+
+ labels = np.asarray(labels)
+ # ensure input and labels match sizes
+ input, labels = np.broadcast_arrays(input, labels)
+
+ if index is None:
+ mask = (labels > 0)
+ masked_positions = None
+ if find_positions:
+ masked_positions = positions[mask]
+ return single_group(input[mask], masked_positions)
+
+ if np.isscalar(index):
+ mask = (labels == index)
+ masked_positions = None
+ if find_positions:
+ masked_positions = positions[mask]
+ return single_group(input[mask], masked_positions)
+
+ index = np.asarray(index)
+
+ # remap labels to unique integers if necessary, or if the largest
+ # label is larger than the number of values.
+ if (not _safely_castable_to_int(labels.dtype) or
+ labels.min() < 0 or labels.max() > labels.size):
+ # remap labels, and indexes
+ unique_labels, labels = np.unique(labels, return_inverse=True)
+ idxs = np.searchsorted(unique_labels, index)
+
+ # make all of idxs valid
+ idxs[idxs >= unique_labels.size] = 0
+ found = (unique_labels[idxs] == index)
+ else:
+ # labels are an integer type, and there aren't too many
+ idxs = np.asanyarray(index, np.int_).copy()
+ found = (idxs >= 0) & (idxs <= labels.max())
+
+ idxs[~ found] = labels.max() + 1
+
+ if find_median:
+ order = np.lexsort((input.ravel(), labels.ravel()))
+ else:
+ order = input.ravel().argsort()
+ input = input.ravel()[order]
+ labels = labels.ravel()[order]
+ if find_positions:
+ positions = positions.ravel()[order]
+
+ result = []
+ if find_min:
+ mins = np.zeros(labels.max() + 2, input.dtype)
+ mins[labels[::-1]] = input[::-1]
+ result += [mins[idxs]]
+ if find_min_positions:
+ minpos = np.zeros(labels.max() + 2, int)
+ minpos[labels[::-1]] = positions[::-1]
+ result += [minpos[idxs]]
+ if find_max:
+ maxs = np.zeros(labels.max() + 2, input.dtype)
+ maxs[labels] = input
+ result += [maxs[idxs]]
+ if find_max_positions:
+ maxpos = np.zeros(labels.max() + 2, int)
+ maxpos[labels] = positions
+ result += [maxpos[idxs]]
+ if find_median:
+ locs = np.arange(len(labels))
+ lo = np.zeros(labels.max() + 2, np.int_)
+ lo[labels[::-1]] = locs[::-1]
+ hi = np.zeros(labels.max() + 2, np.int_)
+ hi[labels] = locs
+ lo = lo[idxs]
+ hi = hi[idxs]
+ # lo is an index to the lowest value in input for each label,
+ # hi is an index to the largest value.
+ # move them to be either the same ((hi - lo) % 2 == 0) or next
+ # to each other ((hi - lo) % 2 == 1), then average.
+ step = (hi - lo) // 2
+ lo += step
+ hi -= step
+ if (np.issubdtype(input.dtype, np.integer)
+ or np.issubdtype(input.dtype, np.bool_)):
+ # avoid integer overflow or boolean addition (gh-12836)
+ result += [(input[lo].astype('d') + input[hi].astype('d')) / 2.0]
+ else:
+ result += [(input[lo] + input[hi]) / 2.0]
+
+ return result
+
+
+def minimum(input, labels=None, index=None):
+ """
+ Calculate the minimum of the values of an array over labeled regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values. For each region specified by `labels`, the
+ minimal values of `input` over the region is computed.
+ labels : array_like, optional
+ An array_like of integers marking different regions over which the
+ minimum value of `input` is to be computed. `labels` must have the
+ same shape as `input`. If `labels` is not specified, the minimum
+ over the whole array is returned.
+ index : array_like, optional
+ A list of region labels that are taken into account for computing the
+ minima. If index is None, the minimum over all elements where `labels`
+ is non-zero is returned.
+
+ Returns
+ -------
+ output : a scalar or list of integers or floats based on input type.
+ List of minima of `input` over the regions determined by `labels` and
+ whose index is in `index`. If `index` or `labels` are not specified, a
+ float is returned: the minimal value of `input` if `labels` is None,
+ and the minimal value of elements where `labels` is greater than zero
+ if `index` is None.
+
+ See Also
+ --------
+ label, maximum, median, minimum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Notes
+ -----
+ The function returns a Python list and not a NumPy array, use
+ `np.array` to convert the list to an array.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> labels, labels_nb = ndimage.label(a)
+ >>> labels
+ array([[1, 1, 0, 0],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]], dtype=int32)
+ >>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1))
+ [1, 4, 3]
+ >>> ndimage.minimum(a)
+ 0
+ >>> ndimage.minimum(a, labels=labels)
+ 1
+
+ """
+ return _select(input, labels, index, find_min=True)[0]
+
+
+def maximum(input, labels=None, index=None):
+ """
+ Calculate the maximum of the values of an array over labeled regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values. For each region specified by `labels`, the
+ maximal values of `input` over the region is computed.
+ labels : array_like, optional
+ An array of integers marking different regions over which the
+ maximum value of `input` is to be computed. `labels` must have the
+ same shape as `input`. If `labels` is not specified, the maximum
+ over the whole array is returned.
+ index : array_like, optional
+ A list of region labels that are taken into account for computing the
+ maxima. If index is None, the maximum over all elements where `labels`
+ is non-zero is returned.
+
+ Returns
+ -------
+ output : a scalar or list of integers or floats based on input type.
+ List of maxima of `input` over the regions determined by `labels` and
+ whose index is in `index`. If `index` or `labels` are not specified, a
+ float is returned: the maximal value of `input` if `labels` is None,
+ and the maximal value of elements where `labels` is greater than zero
+ if `index` is None.
+
+ See Also
+ --------
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Notes
+ -----
+ The function returns a Python list and not a NumPy array, use
+ `np.array` to convert the list to an array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(16).reshape((4,4))
+ >>> a
+ array([[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11],
+ [12, 13, 14, 15]])
+ >>> labels = np.zeros_like(a)
+ >>> labels[:2,:2] = 1
+ >>> labels[2:, 1:3] = 2
+ >>> labels
+ array([[1, 1, 0, 0],
+ [1, 1, 0, 0],
+ [0, 2, 2, 0],
+ [0, 2, 2, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.maximum(a)
+ 15
+ >>> ndimage.maximum(a, labels=labels, index=[1,2])
+ [5, 14]
+ >>> ndimage.maximum(a, labels=labels)
+ 14
+
+ >>> b = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> labels, labels_nb = ndimage.label(b)
+ >>> labels
+ array([[1, 1, 0, 0],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]], dtype=int32)
+ >>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
+ [5, 7, 9]
+
+ """
+ return _select(input, labels, index, find_max=True)[0]
+
+
+def median(input, labels=None, index=None):
+ """
+ Calculate the median of the values of an array over labeled regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values. For each region specified by `labels`, the
+ median value of `input` over the region is computed.
+ labels : array_like, optional
+ An array_like of integers marking different regions over which the
+ median value of `input` is to be computed. `labels` must have the
+ same shape as `input`. If `labels` is not specified, the median
+ over the whole array is returned.
+ index : array_like, optional
+ A list of region labels that are taken into account for computing the
+ medians. If index is None, the median over all elements where `labels`
+ is non-zero is returned.
+
+ Returns
+ -------
+ median : float or list of floats
+ List of medians of `input` over the regions determined by `labels` and
+ whose index is in `index`. If `index` or `labels` are not specified, a
+ float is returned: the median value of `input` if `labels` is None,
+ and the median value of elements where `labels` is greater than zero
+ if `index` is None.
+
+ See Also
+ --------
+ label, minimum, maximum, extrema, sum, mean, variance, standard_deviation
+
+ Notes
+ -----
+ The function returns a Python list and not a NumPy array, use
+ `np.array` to convert the list to an array.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 1],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> labels, labels_nb = ndimage.label(a)
+ >>> labels
+ array([[1, 1, 0, 2],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]], dtype=int32)
+ >>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1))
+ [2.5, 4.0, 6.0]
+ >>> ndimage.median(a)
+ 1.0
+ >>> ndimage.median(a, labels=labels)
+ 3.0
+
+ """
+ return _select(input, labels, index, find_median=True)[0]
+
+
+def minimum_position(input, labels=None, index=None):
+ """
+ Find the positions of the minimums of the values of an array at labels.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values.
+ labels : array_like, optional
+ An array of integers marking different regions over which the
+ position of the minimum value of `input` is to be computed.
+ `labels` must have the same shape as `input`. If `labels` is not
+ specified, the location of the first minimum over the whole
+ array is returned.
+
+ The `labels` argument only works when `index` is specified.
+ index : array_like, optional
+ A list of region labels that are taken into account for finding the
+ location of the minima. If `index` is None, the ``first`` minimum
+ over all elements where `labels` is non-zero is returned.
+
+ The `index` argument only works when `labels` is specified.
+
+ Returns
+ -------
+ output : list of tuples of ints
+ Tuple of ints or list of tuples of ints that specify the location
+ of minima of `input` over the regions determined by `labels` and
+ whose index is in `index`.
+
+ If `index` or `labels` are not specified, a tuple of ints is
+ returned specifying the location of the first minimal value of `input`.
+
+ See Also
+ --------
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[10, 20, 30],
+ ... [40, 80, 100],
+ ... [1, 100, 200]])
+ >>> b = np.array([[1, 2, 0, 1],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+
+ >>> from scipy import ndimage
+
+ >>> ndimage.minimum_position(a)
+ (2, 0)
+ >>> ndimage.minimum_position(b)
+ (0, 2)
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> label, pos = ndimage.label(a)
+ >>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1))
+ [(2, 0)]
+
+ >>> label, pos = ndimage.label(b)
+ >>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1))
+ [(0, 0), (0, 3), (3, 1)]
+
+ """
+ dims = np.array(np.asarray(input).shape)
+ # see np.unravel_index to understand this line.
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+ result = _select(input, labels, index, find_min_positions=True)[0]
+
+ if np.isscalar(result):
+ return tuple((result // dim_prod) % dims)
+
+ return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def maximum_position(input, labels=None, index=None):
+ """
+ Find the positions of the maximums of the values of an array at labels.
+
+ For each region specified by `labels`, the position of the maximum
+ value of `input` within the region is returned.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values.
+ labels : array_like, optional
+ An array of integers marking different regions over which the
+ position of the maximum value of `input` is to be computed.
+ `labels` must have the same shape as `input`. If `labels` is not
+ specified, the location of the first maximum over the whole
+ array is returned.
+
+ The `labels` argument only works when `index` is specified.
+ index : array_like, optional
+ A list of region labels that are taken into account for finding the
+ location of the maxima. If `index` is None, the first maximum
+ over all elements where `labels` is non-zero is returned.
+
+ The `index` argument only works when `labels` is specified.
+
+ Returns
+ -------
+ output : list of tuples of ints
+ List of tuples of ints that specify the location of maxima of
+ `input` over the regions determined by `labels` and whose index
+ is in `index`.
+
+ If `index` or `labels` are not specified, a tuple of ints is
+ returned specifying the location of the ``first`` maximal value
+ of `input`.
+
+ See Also
+ --------
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> ndimage.maximum_position(a)
+ (3, 0)
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl = np.array([[0, 1, 2, 3],
+ ... [0, 1, 2, 3],
+ ... [0, 1, 2, 3],
+ ... [0, 1, 2, 3]])
+ >>> ndimage.maximum_position(a, lbl, 1)
+ (1, 1)
+
+ If no index is given, non-zero `labels` are processed:
+
+ >>> ndimage.maximum_position(a, lbl)
+ (2, 3)
+
+ If there are no maxima, the position of the first element is returned:
+
+ >>> ndimage.maximum_position(a, lbl, 2)
+ (0, 2)
+
+ """
+ dims = np.array(np.asarray(input).shape)
+ # see np.unravel_index to understand this line.
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+ result = _select(input, labels, index, find_max_positions=True)[0]
+
+ if np.isscalar(result):
+ return tuple((result // dim_prod) % dims)
+
+ return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def extrema(input, labels=None, index=None):
+ """
+ Calculate the minimums and maximums of the values of an array
+ at labels, along with their positions.
+
+ Parameters
+ ----------
+ input : ndarray
+ N-D image data to process.
+ labels : ndarray, optional
+ Labels of features in input.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ Labels to include in output. If None (default), all values where
+ non-zero `labels` are used.
+
+ Returns
+ -------
+ minimums, maximums : int or ndarray
+ Values of minimums and maximums in each feature.
+ min_positions, max_positions : tuple or list of tuples
+ Each tuple gives the N-D coordinates of the corresponding minimum
+ or maximum.
+
+ See Also
+ --------
+ maximum, minimum, maximum_position, minimum_position, center_of_mass
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.extrema(a)
+ (0, 9, (0, 2), (3, 0))
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1))
+ (array([1, 4, 3]),
+ array([5, 7, 9]),
+ [(0, 0), (1, 3), (3, 1)],
+ [(1, 0), (2, 3), (3, 0)])
+
+ If no index is given, non-zero `labels` are processed:
+
+ >>> ndimage.extrema(a, lbl)
+ (1, 9, (0, 0), (3, 0))
+
+ """
+ dims = np.array(np.asarray(input).shape)
+ # see np.unravel_index to understand this line.
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+ minimums, min_positions, maximums, max_positions = _select(input, labels,
+ index,
+ find_min=True,
+ find_max=True,
+ find_min_positions=True,
+ find_max_positions=True)
+
+ if np.isscalar(minimums):
+ return (minimums, maximums, tuple((min_positions // dim_prod) % dims),
+ tuple((max_positions // dim_prod) % dims))
+
+ min_positions = [
+ tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims
+ ]
+ max_positions = [
+ tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims
+ ]
+
+ return minimums, maximums, min_positions, max_positions
+
+
+def center_of_mass(input, labels=None, index=None):
+ """
+ Calculate the center of mass of the values of an array at labels.
+
+ Parameters
+ ----------
+ input : ndarray
+ Data from which to calculate center-of-mass. The masses can either
+ be positive or negative.
+ labels : ndarray, optional
+ Labels for objects in `input`, as generated by `ndimage.label`.
+ Only used with `index`. Dimensions must be the same as `input`.
+ index : int or sequence of ints, optional
+ Labels for which to calculate centers-of-mass. If not specified,
+ the combined center of mass of all labels greater than zero
+ will be calculated. Only used with `labels`.
+
+ Returns
+ -------
+ center_of_mass : tuple, or list of tuples
+ Coordinates of centers-of-mass.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(([0,0,0,0],
+ ... [0,1,1,0],
+ ... [0,1,1,0],
+ ... [0,1,1,0]))
+ >>> from scipy import ndimage
+ >>> ndimage.center_of_mass(a)
+ (2.0, 1.5)
+
+ Calculation of multiple objects in an image
+
+ >>> b = np.array(([0,1,1,0],
+ ... [0,1,0,0],
+ ... [0,0,0,0],
+ ... [0,0,1,1],
+ ... [0,0,1,1]))
+ >>> lbl = ndimage.label(b)[0]
+ >>> ndimage.center_of_mass(b, lbl, [1,2])
+ [(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)]
+
+ Negative masses are also accepted, which can occur for example when
+ bias is removed from measured data due to random noise.
+
+ >>> c = np.array(([-1,0,0,0],
+ ... [0,-1,-1,0],
+ ... [0,1,-1,0],
+ ... [0,1,1,0]))
+ >>> ndimage.center_of_mass(c)
+ (-4.0, 1.0)
+
+ If there are division by zero issues, the function does not raise an
+ error but rather issues a RuntimeWarning before returning inf and/or NaN.
+
+ >>> d = np.array([-1, 1])
+ >>> ndimage.center_of_mass(d)
+ (inf,)
+ """
+ input = np.asarray(input)
+ normalizer = sum_labels(input, labels, index)
+ grids = np.ogrid[[slice(0, i) for i in input.shape]]
+
+ results = [sum_labels(input * grids[dir].astype(float), labels, index) / normalizer
+ for dir in range(input.ndim)]
+
+ if np.isscalar(results[0]):
+ return tuple(results)
+
+ return [tuple(v) for v in np.array(results).T]
+
+
+def histogram(input, min, max, bins, labels=None, index=None):
+ """
+ Calculate the histogram of the values of an array, optionally at labels.
+
+ Histogram calculates the frequency of values in an array within bins
+ determined by `min`, `max`, and `bins`. The `labels` and `index`
+ keywords can limit the scope of the histogram to specified sub-regions
+ within the array.
+
+ Parameters
+ ----------
+ input : array_like
+ Data for which to calculate histogram.
+ min, max : int
+ Minimum and maximum values of range of histogram bins.
+ bins : int
+ Number of bins.
+ labels : array_like, optional
+ Labels for objects in `input`.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ Label or labels for which to calculate histogram. If None, all values
+ where label is greater than zero are used
+
+ Returns
+ -------
+ hist : ndarray
+ Histogram counts.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[ 0. , 0.2146, 0.5962, 0. ],
+ ... [ 0. , 0.7778, 0. , 0. ],
+ ... [ 0. , 0. , 0. , 0. ],
+ ... [ 0. , 0. , 0.7181, 0.2787],
+ ... [ 0. , 0. , 0.6573, 0.3094]])
+ >>> from scipy import ndimage
+ >>> ndimage.histogram(a, 0, 1, 10)
+ array([13, 0, 2, 1, 0, 1, 1, 2, 0, 0])
+
+ With labels and no indices, non-zero elements are counted:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.histogram(a, 0, 1, 10, lbl)
+ array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0])
+
+ Indices can be used to count only certain objects:
+
+ >>> ndimage.histogram(a, 0, 1, 10, lbl, 2)
+ array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])
+
+ """
+ _bins = np.linspace(min, max, bins + 1)
+
+ def _hist(vals):
+ return np.histogram(vals, _bins)[0]
+
+ return labeled_comprehension(input, labels, index, _hist, object, None,
+ pass_positions=False)
+
+
+def watershed_ift(input, markers, structure=None, output=None):
+ """
+ Apply watershed from markers using image foresting transform algorithm.
+
+ Parameters
+ ----------
+ input : array_like
+ Input.
+ markers : array_like
+ Markers are points within each watershed that form the beginning
+ of the process. Negative markers are considered background markers
+ which are processed after the other markers.
+ structure : structure element, optional
+ A structuring element defining the connectivity of the object can be
+ provided. If None, an element is generated with a squared
+ connectivity equal to one.
+ output : ndarray, optional
+ An output array can optionally be provided. The same shape as input.
+
+ Returns
+ -------
+ watershed_ift : ndarray
+ Output. Same shape as `input`.
+
+ References
+ ----------
+ .. [1] A.X. Falcao, J. Stolfi and R. de Alencar Lotufo, "The image
+ foresting transform: theory, algorithms, and applications",
+ Pattern Analysis and Machine Intelligence, vol. 26, pp. 19-29, 2004.
+
+ """
+ input = np.asarray(input)
+ if input.dtype.type not in [np.uint8, np.uint16]:
+ raise TypeError('only 8 and 16 unsigned inputs are supported')
+
+ if structure is None:
+ structure = _morphology.generate_binary_structure(input.ndim, 1)
+ structure = np.asarray(structure, dtype=bool)
+ if structure.ndim != input.ndim:
+ raise RuntimeError('structure and input must have equal rank')
+ for ii in structure.shape:
+ if ii != 3:
+ raise RuntimeError('structure dimensions must be equal to 3')
+
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ markers = np.asarray(markers)
+ if input.shape != markers.shape:
+ raise RuntimeError('input and markers must have equal shape')
+
+ integral_types = [np.int8,
+ np.int16,
+ np.int32,
+ np.int64,
+ np.intc,
+ np.intp]
+
+ if markers.dtype.type not in integral_types:
+ raise RuntimeError('marker should be of integer type')
+
+ if isinstance(output, np.ndarray):
+ if output.dtype.type not in integral_types:
+ raise RuntimeError('output should be of integer type')
+ else:
+ output = markers.dtype
+
+ output = _ni_support._get_output(output, input)
+ _nd_image.watershed_ift(input, markers, structure, output)
+ return output
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_morphology.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8635a10e8e6ac979fdff3eaa33a461743f12c71
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_morphology.py
@@ -0,0 +1,2633 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import warnings
+import operator
+
+import numpy as np
+from . import _ni_support
+from . import _nd_image
+from . import _filters
+
+__all__ = ['iterate_structure', 'generate_binary_structure', 'binary_erosion',
+ 'binary_dilation', 'binary_opening', 'binary_closing',
+ 'binary_hit_or_miss', 'binary_propagation', 'binary_fill_holes',
+ 'grey_erosion', 'grey_dilation', 'grey_opening', 'grey_closing',
+ 'morphological_gradient', 'morphological_laplace', 'white_tophat',
+ 'black_tophat', 'distance_transform_bf', 'distance_transform_cdt',
+ 'distance_transform_edt']
+
+
+def _center_is_true(structure, origin):
+ structure = np.asarray(structure)
+ coor = tuple([oo + ss // 2 for ss, oo in zip(structure.shape,
+ origin)])
+ return bool(structure[coor])
+
+
+def iterate_structure(structure, iterations, origin=None):
+ """
+ Iterate a structure by dilating it with itself.
+
+ Parameters
+ ----------
+ structure : array_like
+ Structuring element (an array of bools, for example), to be dilated with
+ itself.
+ iterations : int
+ number of dilations performed on the structure with itself
+ origin : optional
+ If origin is None, only the iterated structure is returned. If
+ not, a tuple of the iterated structure and the modified origin is
+ returned.
+
+ Returns
+ -------
+ iterate_structure : ndarray of bools
+ A new structuring element obtained by dilating `structure`
+ (`iterations` - 1) times with itself.
+
+ See Also
+ --------
+ generate_binary_structure
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> struct = ndimage.generate_binary_structure(2, 1)
+ >>> struct.astype(int)
+ array([[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]])
+ >>> ndimage.iterate_structure(struct, 2).astype(int)
+ array([[0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0]])
+ >>> ndimage.iterate_structure(struct, 3).astype(int)
+ array([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]])
+
+ """
+ structure = np.asarray(structure)
+ if iterations < 2:
+ return structure.copy()
+ ni = iterations - 1
+ shape = [ii + ni * (ii - 1) for ii in structure.shape]
+ pos = [ni * (structure.shape[ii] // 2) for ii in range(len(shape))]
+ slc = tuple(slice(pos[ii], pos[ii] + structure.shape[ii], None)
+ for ii in range(len(shape)))
+ out = np.zeros(shape, bool)
+ out[slc] = structure != 0
+ out = binary_dilation(out, structure, iterations=ni)
+ if origin is None:
+ return out
+ else:
+ origin = _ni_support._normalize_sequence(origin, structure.ndim)
+ origin = [iterations * o for o in origin]
+ return out, origin
+
+
+def generate_binary_structure(rank, connectivity):
+ """
+ Generate a binary structure for binary morphological operations.
+
+ Parameters
+ ----------
+ rank : int
+ Number of dimensions of the array to which the structuring element
+ will be applied, as returned by `np.ndim`.
+ connectivity : int
+ `connectivity` determines which elements of the output array belong
+ to the structure, i.e., are considered as neighbors of the central
+ element. Elements up to a squared distance of `connectivity` from
+ the center are considered neighbors. `connectivity` may range from 1
+ (no diagonal elements are neighbors) to `rank` (all elements are
+ neighbors).
+
+ Returns
+ -------
+ output : ndarray of bools
+ Structuring element which may be used for binary morphological
+ operations, with `rank` dimensions and all dimensions equal to 3.
+
+ See Also
+ --------
+ iterate_structure, binary_dilation, binary_erosion
+
+ Notes
+ -----
+ `generate_binary_structure` can only create structuring elements with
+ dimensions equal to 3, i.e., minimal dimensions. For larger structuring
+ elements, that are useful e.g., for eroding large objects, one may either
+ use `iterate_structure`, or create directly custom arrays with
+ numpy functions such as `numpy.ones`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> struct = ndimage.generate_binary_structure(2, 1)
+ >>> struct
+ array([[False, True, False],
+ [ True, True, True],
+ [False, True, False]], dtype=bool)
+ >>> a = np.zeros((5,5))
+ >>> a[2, 2] = 1
+ >>> a
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
+ >>> b
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
+ array([[ 0., 0., 1., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 1., 1., 1., 1., 1.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 1., 0., 0.]])
+ >>> struct = ndimage.generate_binary_structure(2, 2)
+ >>> struct
+ array([[ True, True, True],
+ [ True, True, True],
+ [ True, True, True]], dtype=bool)
+ >>> struct = ndimage.generate_binary_structure(3, 1)
+ >>> struct # no diagonal elements
+ array([[[False, False, False],
+ [False, True, False],
+ [False, False, False]],
+ [[False, True, False],
+ [ True, True, True],
+ [False, True, False]],
+ [[False, False, False],
+ [False, True, False],
+ [False, False, False]]], dtype=bool)
+
+ """
+ if connectivity < 1:
+ connectivity = 1
+ if rank < 1:
+ return np.array(True, dtype=bool)
+ output = np.fabs(np.indices([3] * rank) - 1)
+ output = np.add.reduce(output, 0)
+ return output <= connectivity
+
+
+def _binary_erosion(input, structure, iterations, mask, output,
+ border_value, origin, invert, brute_force, axes):
+ try:
+ iterations = operator.index(iterations)
+ except TypeError as e:
+ raise TypeError('iterations parameter should be an integer') from e
+
+ input = np.asarray(input)
+ # The Cython code can't cope with broadcasted inputs
+ if not input.flags.c_contiguous and not input.flags.f_contiguous:
+ input = np.ascontiguousarray(input)
+
+ ndim = input.ndim
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if structure is None:
+ structure = generate_binary_structure(num_axes, 1)
+ else:
+ structure = np.asarray(structure, dtype=bool)
+ if ndim > num_axes:
+ structure = _filters._expand_footprint(ndim, axes, structure,
+ footprint_name="structure")
+
+ if structure.ndim != input.ndim:
+ raise RuntimeError('structure and input must have same dimensionality')
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ if structure.size < 1:
+ raise RuntimeError('structure must not be empty')
+ if mask is not None:
+ mask = np.asarray(mask)
+ if mask.shape != input.shape:
+ raise RuntimeError('mask and input must have equal sizes')
+ origin = _ni_support._normalize_sequence(origin, num_axes)
+ origin = _filters._expand_origin(ndim, axes, origin)
+ cit = _center_is_true(structure, origin)
+ if isinstance(output, np.ndarray):
+ if np.iscomplexobj(output):
+ raise TypeError('Complex output type not supported')
+ else:
+ output = bool
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ if iterations == 1:
+ _nd_image.binary_erosion(input, structure, mask, output,
+ border_value, origin, invert, cit, 0)
+ elif cit and not brute_force:
+ changed, coordinate_list = _nd_image.binary_erosion(
+ input, structure, mask, output,
+ border_value, origin, invert, cit, 1)
+ structure = structure[tuple([slice(None, None, -1)] *
+ structure.ndim)]
+ for ii in range(len(origin)):
+ origin[ii] = -origin[ii]
+ if not structure.shape[ii] & 1:
+ origin[ii] -= 1
+ if mask is not None:
+ mask = np.asarray(mask, dtype=np.int8)
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ _nd_image.binary_erosion2(output, structure, mask, iterations - 1,
+ origin, invert, coordinate_list)
+ else:
+ tmp_in = np.empty_like(input, dtype=bool)
+ tmp_out = output
+ if iterations >= 1 and not iterations & 1:
+ tmp_in, tmp_out = tmp_out, tmp_in
+ changed = _nd_image.binary_erosion(
+ input, structure, mask, tmp_out,
+ border_value, origin, invert, cit, 0)
+ ii = 1
+ while ii < iterations or (iterations < 1 and changed):
+ tmp_in, tmp_out = tmp_out, tmp_in
+ changed = _nd_image.binary_erosion(
+ tmp_in, structure, mask, tmp_out,
+ border_value, origin, invert, cit, 0)
+ ii += 1
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+def binary_erosion(input, structure=None, iterations=1, mask=None, output=None,
+ border_value=0, origin=0, brute_force=False, *, axes=None):
+ """
+ Multidimensional binary erosion with a given structuring element.
+
+ Binary erosion is a mathematical morphology operation used for image
+ processing.
+
+ Parameters
+ ----------
+ input : array_like
+ Binary image to be eroded. Non-zero (True) elements form
+ the subset to be eroded.
+ structure : array_like, optional
+ Structuring element used for the erosion. Non-zero elements are
+ considered True. If no structuring element is provided, an element
+ is generated with a square connectivity equal to one.
+ iterations : int, optional
+ The erosion is repeated `iterations` times (one, by default).
+ If iterations is less than 1, the erosion is repeated until the
+ result does not change anymore.
+ mask : array_like, optional
+ If a mask is given, only those elements with a True value at
+ the corresponding mask element are modified at each iteration.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ border_value : int (cast to 0 or 1), optional
+ Value at the border in the output array.
+ origin : int or tuple of ints, optional
+ Placement of the filter, by default 0.
+ brute_force : bool, optional
+ Memory condition: if False, only the pixels whose value was changed in
+ the last iteration are tracked as candidates to be updated (eroded) in
+ the current iteration; if True all pixels are considered as candidates
+ for erosion, regardless of what happened in the previous iteration.
+ False by default.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ binary_erosion : ndarray of bools
+ Erosion of the input by the structuring element.
+
+ See Also
+ --------
+ grey_erosion, binary_dilation, binary_closing, binary_opening,
+ generate_binary_structure
+
+ Notes
+ -----
+ Erosion [1]_ is a mathematical morphology operation [2]_ that uses a
+ structuring element for shrinking the shapes in an image. The binary
+ erosion of an image by a structuring element is the locus of the points
+ where a superimposition of the structuring element centered on the point
+ is entirely contained in the set of non-zero elements of the image.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
+ .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((7,7), dtype=int)
+ >>> a[1:6, 2:5] = 1
+ >>> a
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.binary_erosion(a).astype(a.dtype)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> #Erosion removes objects smaller than the structure
+ >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+
+ """
+ return _binary_erosion(input, structure, iterations, mask,
+ output, border_value, origin, 0, brute_force, axes)
+
+
+def binary_dilation(input, structure=None, iterations=1, mask=None,
+ output=None, border_value=0, origin=0,
+ brute_force=False, *, axes=None):
+ """
+ Multidimensional binary dilation with the given structuring element.
+
+ Parameters
+ ----------
+ input : array_like
+ Binary array_like to be dilated. Non-zero (True) elements form
+ the subset to be dilated.
+ structure : array_like, optional
+ Structuring element used for the dilation. Non-zero elements are
+ considered True. If no structuring element is provided an element
+ is generated with a square connectivity equal to one.
+ iterations : int, optional
+ The dilation is repeated `iterations` times (one, by default).
+ If iterations is less than 1, the dilation is repeated until the
+ result does not change anymore. Only an integer of iterations is
+ accepted.
+ mask : array_like, optional
+ If a mask is given, only those elements with a True value at
+ the corresponding mask element are modified at each iteration.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ border_value : int (cast to 0 or 1), optional
+ Value at the border in the output array.
+ origin : int or tuple of ints, optional
+ Placement of the filter, by default 0.
+ brute_force : bool, optional
+ Memory condition: if False, only the pixels whose value was changed in
+ the last iteration are tracked as candidates to be updated (dilated)
+ in the current iteration; if True all pixels are considered as
+ candidates for dilation, regardless of what happened in the previous
+ iteration. False by default.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ binary_dilation : ndarray of bools
+ Dilation of the input by the structuring element.
+
+ See Also
+ --------
+ grey_dilation, binary_erosion, binary_closing, binary_opening,
+ generate_binary_structure
+
+ Notes
+ -----
+ Dilation [1]_ is a mathematical morphology operation [2]_ that uses a
+ structuring element for expanding the shapes in an image. The binary
+ dilation of an image by a structuring element is the locus of the points
+ covered by the structuring element, when its center lies within the
+ non-zero points of the image.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
+ .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((5, 5))
+ >>> a[2, 2] = 1
+ >>> a
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> ndimage.binary_dilation(a)
+ array([[False, False, False, False, False],
+ [False, False, True, False, False],
+ [False, True, True, True, False],
+ [False, False, True, False, False],
+ [False, False, False, False, False]], dtype=bool)
+ >>> ndimage.binary_dilation(a).astype(a.dtype)
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> # 3x3 structuring element with connectivity 1, used by default
+ >>> struct1 = ndimage.generate_binary_structure(2, 1)
+ >>> struct1
+ array([[False, True, False],
+ [ True, True, True],
+ [False, True, False]], dtype=bool)
+ >>> # 3x3 structuring element with connectivity 2
+ >>> struct2 = ndimage.generate_binary_structure(2, 2)
+ >>> struct2
+ array([[ True, True, True],
+ [ True, True, True],
+ [ True, True, True]], dtype=bool)
+ >>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype)
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype)
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> ndimage.binary_dilation(a, structure=struct1,\\
+ ... iterations=2).astype(a.dtype)
+ array([[ 0., 0., 1., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 1., 1., 1., 1., 1.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 1., 0., 0.]])
+
+ """
+ input = np.asarray(input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if structure is None:
+ structure = generate_binary_structure(num_axes, 1)
+ origin = _ni_support._normalize_sequence(origin, num_axes)
+ structure = np.asarray(structure)
+ structure = structure[tuple([slice(None, None, -1)] *
+ structure.ndim)]
+ for ii in range(len(origin)):
+ origin[ii] = -origin[ii]
+ if not structure.shape[ii] & 1:
+ origin[ii] -= 1
+
+ return _binary_erosion(input, structure, iterations, mask,
+ output, border_value, origin, 1, brute_force, axes)
+
+
+def binary_opening(input, structure=None, iterations=1, output=None,
+ origin=0, mask=None, border_value=0, brute_force=False, *,
+ axes=None):
+ """
+ Multidimensional binary opening with the given structuring element.
+
+ The *opening* of an input image by a structuring element is the
+ *dilation* of the *erosion* of the image by the structuring element.
+
+ Parameters
+ ----------
+ input : array_like
+ Binary array_like to be opened. Non-zero (True) elements form
+ the subset to be opened.
+ structure : array_like, optional
+ Structuring element used for the opening. Non-zero elements are
+ considered True. If no structuring element is provided an element
+ is generated with a square connectivity equal to one (i.e., only
+ nearest neighbors are connected to the center, diagonally-connected
+ elements are not considered neighbors).
+ iterations : int, optional
+ The erosion step of the opening, then the dilation step are each
+ repeated `iterations` times (one, by default). If `iterations` is
+ less than 1, each operation is repeated until the result does
+ not change anymore. Only an integer of iterations is accepted.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ origin : int or tuple of ints, optional
+ Placement of the filter, by default 0.
+ mask : array_like, optional
+ If a mask is given, only those elements with a True value at
+ the corresponding mask element are modified at each iteration.
+
+ .. versionadded:: 1.1.0
+ border_value : int (cast to 0 or 1), optional
+ Value at the border in the output array.
+
+ .. versionadded:: 1.1.0
+ brute_force : bool, optional
+ Memory condition: if False, only the pixels whose value was changed in
+ the last iteration are tracked as candidates to be updated in the
+ current iteration; if True all pixels are considered as candidates for
+ update, regardless of what happened in the previous iteration.
+ False by default.
+
+ .. versionadded:: 1.1.0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ binary_opening : ndarray of bools
+ Opening of the input by the structuring element.
+
+ See Also
+ --------
+ grey_opening, binary_closing, binary_erosion, binary_dilation,
+ generate_binary_structure
+
+ Notes
+ -----
+ *Opening* [1]_ is a mathematical morphology operation [2]_ that
+ consists in the succession of an erosion and a dilation of the
+ input with the same structuring element. Opening, therefore, removes
+ objects smaller than the structuring element.
+
+ Together with *closing* (`binary_closing`), opening can be used for
+ noise removal.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Opening_%28morphology%29
+ .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((5,5), dtype=int)
+ >>> a[1:4, 1:4] = 1; a[4, 4] = 1
+ >>> a
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 1]])
+ >>> # Opening removes small objects
+ >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]])
+ >>> # Opening can also smooth corners
+ >>> ndimage.binary_opening(a).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]])
+ >>> # Opening is the dilation of the erosion of the input
+ >>> ndimage.binary_erosion(a).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]])
+ >>> ndimage.binary_dilation(ndimage.binary_erosion(a)).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if structure is None:
+ structure = generate_binary_structure(num_axes, 1)
+
+ tmp = binary_erosion(input, structure, iterations, mask, None,
+ border_value, origin, brute_force, axes=axes)
+ return binary_dilation(tmp, structure, iterations, mask, output,
+ border_value, origin, brute_force, axes=axes)
+
+
+def binary_closing(input, structure=None, iterations=1, output=None,
+ origin=0, mask=None, border_value=0, brute_force=False, *,
+ axes=None):
+ """
+ Multidimensional binary closing with the given structuring element.
+
+ The *closing* of an input image by a structuring element is the
+ *erosion* of the *dilation* of the image by the structuring element.
+
+ Parameters
+ ----------
+ input : array_like
+ Binary array_like to be closed. Non-zero (True) elements form
+ the subset to be closed.
+ structure : array_like, optional
+ Structuring element used for the closing. Non-zero elements are
+ considered True. If no structuring element is provided an element
+ is generated with a square connectivity equal to one (i.e., only
+ nearest neighbors are connected to the center, diagonally-connected
+ elements are not considered neighbors).
+ iterations : int, optional
+ The dilation step of the closing, then the erosion step are each
+ repeated `iterations` times (one, by default). If iterations is
+ less than 1, each operations is repeated until the result does
+ not change anymore. Only an integer of iterations is accepted.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ origin : int or tuple of ints, optional
+ Placement of the filter, by default 0.
+ mask : array_like, optional
+ If a mask is given, only those elements with a True value at
+ the corresponding mask element are modified at each iteration.
+
+ .. versionadded:: 1.1.0
+ border_value : int (cast to 0 or 1), optional
+ Value at the border in the output array.
+
+ .. versionadded:: 1.1.0
+ brute_force : bool, optional
+ Memory condition: if False, only the pixels whose value was changed in
+ the last iteration are tracked as candidates to be updated in the
+ current iteration; if True all pixels are considered as candidates for
+ update, regardless of what happened in the previous iteration.
+ False by default.
+
+ .. versionadded:: 1.1.0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ binary_closing : ndarray of bools
+ Closing of the input by the structuring element.
+
+ See Also
+ --------
+ grey_closing, binary_opening, binary_dilation, binary_erosion,
+ generate_binary_structure
+
+ Notes
+ -----
+ *Closing* [1]_ is a mathematical morphology operation [2]_ that
+ consists in the succession of a dilation and an erosion of the
+ input with the same structuring element. Closing therefore fills
+ holes smaller than the structuring element.
+
+ Together with *opening* (`binary_opening`), closing can be used for
+ noise removal.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29
+ .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((5,5), dtype=int)
+ >>> a[1:-1, 1:-1] = 1; a[2,2] = 0
+ >>> a
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]])
+ >>> # Closing removes small holes
+ >>> ndimage.binary_closing(a).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]])
+ >>> # Closing is the erosion of the dilation of the input
+ >>> ndimage.binary_dilation(a).astype(int)
+ array([[0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 0]])
+ >>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]])
+
+
+ >>> a = np.zeros((7,7), dtype=int)
+ >>> a[1:6, 2:5] = 1; a[1:3,3] = 0
+ >>> a
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> # In addition to removing holes, closing can also
+ >>> # coarsen boundaries with fine hollows.
+ >>> ndimage.binary_closing(a).astype(int)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if structure is None:
+ structure = generate_binary_structure(num_axes, 1)
+
+ tmp = binary_dilation(input, structure, iterations, mask, None,
+ border_value, origin, brute_force, axes=axes)
+ return binary_erosion(tmp, structure, iterations, mask, output,
+ border_value, origin, brute_force, axes=axes)
+
+
+def binary_hit_or_miss(input, structure1=None, structure2=None,
+ output=None, origin1=0, origin2=None, *, axes=None):
+ """
+ Multidimensional binary hit-or-miss transform.
+
+ The hit-or-miss transform finds the locations of a given pattern
+ inside the input image.
+
+ Parameters
+ ----------
+ input : array_like (cast to booleans)
+ Binary image where a pattern is to be detected.
+ structure1 : array_like (cast to booleans), optional
+ Part of the structuring element to be fitted to the foreground
+ (non-zero elements) of `input`. If no value is provided, a
+ structure of square connectivity 1 is chosen.
+ structure2 : array_like (cast to booleans), optional
+ Second part of the structuring element that has to miss completely
+ the foreground. If no value is provided, the complementary of
+ `structure1` is taken.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ origin1 : int or tuple of ints, optional
+ Placement of the first part of the structuring element `structure1`,
+ by default 0 for a centered structure.
+ origin2 : int or tuple of ints, optional
+ Placement of the second part of the structuring element `structure2`,
+ by default 0 for a centered structure. If a value is provided for
+ `origin1` and not for `origin2`, then `origin2` is set to `origin1`.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If `origin1` or `origin2` tuples are provided, their
+ length must match the number of axes.
+
+ Returns
+ -------
+ binary_hit_or_miss : ndarray
+ Hit-or-miss transform of `input` with the given structuring
+ element (`structure1`, `structure2`).
+
+ See Also
+ --------
+ binary_erosion
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Hit-or-miss_transform
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((7,7), dtype=int)
+ >>> a[1, 1] = 1; a[2:4, 2:4] = 1; a[4:6, 4:6] = 1
+ >>> a
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> structure1 = np.array([[1, 0, 0], [0, 1, 1], [0, 1, 1]])
+ >>> structure1
+ array([[1, 0, 0],
+ [0, 1, 1],
+ [0, 1, 1]])
+ >>> # Find the matches of structure1 in the array a
+ >>> ndimage.binary_hit_or_miss(a, structure1=structure1).astype(int)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> # Change the origin of the filter
+ >>> # origin1=1 is equivalent to origin1=(1,1) here
+ >>> ndimage.binary_hit_or_miss(a, structure1=structure1,\\
+ ... origin1=1).astype(int)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if structure1 is None:
+ structure1 = generate_binary_structure(num_axes, 1)
+ else:
+ structure1 = np.asarray(structure1)
+ if structure2 is None:
+ structure2 = np.logical_not(structure1)
+ origin1 = _ni_support._normalize_sequence(origin1, num_axes)
+ if origin2 is None:
+ origin2 = origin1
+ else:
+ origin2 = _ni_support._normalize_sequence(origin2, num_axes)
+
+ tmp1 = _binary_erosion(input, structure1, 1, None, None, 0, origin1,
+ 0, False, axes)
+ inplace = isinstance(output, np.ndarray)
+ result = _binary_erosion(input, structure2, 1, None, output, 0,
+ origin2, 1, False, axes)
+ if inplace:
+ np.logical_not(output, output)
+ np.logical_and(tmp1, output, output)
+ else:
+ np.logical_not(result, result)
+ return np.logical_and(tmp1, result)
+
+
+def binary_propagation(input, structure=None, mask=None,
+ output=None, border_value=0, origin=0, *, axes=None):
+ """
+ Multidimensional binary propagation with the given structuring element.
+
+ Parameters
+ ----------
+ input : array_like
+ Binary image to be propagated inside `mask`.
+ structure : array_like, optional
+ Structuring element used in the successive dilations. The output
+ may depend on the structuring element, especially if `mask` has
+ several connex components. If no structuring element is
+ provided, an element is generated with a squared connectivity equal
+ to one.
+ mask : array_like, optional
+ Binary mask defining the region into which `input` is allowed to
+ propagate.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ border_value : int (cast to 0 or 1), optional
+ Value at the border in the output array.
+ origin : int or tuple of ints, optional
+ Placement of the filter, by default 0.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ binary_propagation : ndarray
+ Binary propagation of `input` inside `mask`.
+
+ Notes
+ -----
+ This function is functionally equivalent to calling binary_dilation
+ with the number of iterations less than one: iterative dilation until
+ the result does not change anymore.
+
+ The succession of an erosion and propagation inside the original image
+ can be used instead of an *opening* for deleting small objects while
+ keeping the contours of larger objects untouched.
+
+ References
+ ----------
+ .. [1] http://cmm.ensmp.fr/~serra/cours/pdf/en/ch6en.pdf, slide 15.
+ .. [2] I.T. Young, J.J. Gerbrands, and L.J. van Vliet, "Fundamentals of
+ image processing", 1998
+ ftp://qiftp.tudelft.nl/DIPimage/docs/FIP2.3.pdf
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> input = np.zeros((8, 8), dtype=int)
+ >>> input[2, 2] = 1
+ >>> mask = np.zeros((8, 8), dtype=int)
+ >>> mask[1:4, 1:4] = mask[4, 4] = mask[6:8, 6:8] = 1
+ >>> input
+ array([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]])
+ >>> mask
+ array([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 0, 1, 1]])
+ >>> ndimage.binary_propagation(input, mask=mask).astype(int)
+ array([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.binary_propagation(input, mask=mask,\\
+ ... structure=np.ones((3,3))).astype(int)
+ array([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]])
+
+ >>> # Comparison between opening and erosion+propagation
+ >>> a = np.zeros((6,6), dtype=int)
+ >>> a[2:5, 2:5] = 1; a[0, 0] = 1; a[5, 5] = 1
+ >>> a
+ array([[1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 1]])
+ >>> ndimage.binary_opening(a).astype(int)
+ array([[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0]])
+ >>> b = ndimage.binary_erosion(a)
+ >>> b.astype(int)
+ array([[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0]])
+ >>> ndimage.binary_propagation(b, mask=a).astype(int)
+ array([[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0]])
+
+ """
+ return binary_dilation(input, structure, -1, mask, output,
+ border_value, origin, axes=axes)
+
+
+def binary_fill_holes(input, structure=None, output=None, origin=0, *,
+ axes=None):
+ """
+ Fill the holes in binary objects.
+
+
+ Parameters
+ ----------
+ input : array_like
+ N-D binary array with holes to be filled
+ structure : array_like, optional
+ Structuring element used in the computation; large-size elements
+ make computations faster but may miss holes separated from the
+ background by thin regions. The default element (with a square
+ connectivity equal to one) yields the intuitive result where all
+ holes in the input have been filled.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ origin : int, tuple of ints, optional
+ Position of the structuring element.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ out : ndarray
+ Transformation of the initial image `input` where holes have been
+ filled.
+
+ See Also
+ --------
+ binary_dilation, binary_propagation, label
+
+ Notes
+ -----
+ The algorithm used in this function consists in invading the complementary
+ of the shapes in `input` from the outer boundary of the image,
+ using binary dilations. Holes are not connected to the boundary and are
+ therefore not invaded. The result is the complementary subset of the
+ invaded region.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((5, 5), dtype=int)
+ >>> a[1:4, 1:4] = 1
+ >>> a[2,2] = 0
+ >>> a
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]])
+ >>> ndimage.binary_fill_holes(a).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]])
+ >>> # Too big structuring element
+ >>> ndimage.binary_fill_holes(a, structure=np.ones((5,5))).astype(int)
+ array([[0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+ mask = np.logical_not(input)
+ tmp = np.zeros(mask.shape, bool)
+ inplace = isinstance(output, np.ndarray)
+ if inplace:
+ binary_dilation(tmp, structure, -1, mask, output, 1, origin, axes=axes)
+ np.logical_not(output, output)
+ else:
+ output = binary_dilation(tmp, structure, -1, mask, None, 1,
+ origin, axes=axes)
+ np.logical_not(output, output)
+ return output
+
+
+def grey_erosion(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Calculate a greyscale erosion, using either a structuring element,
+ or a footprint corresponding to a flat structuring element.
+
+ Grayscale erosion is a mathematical morphology operation. For the
+ simple case of a full and flat structuring element, it can be viewed
+ as a minimum filter over a sliding window.
+
+ Parameters
+ ----------
+ input : array_like
+ Array over which the grayscale erosion is to be computed.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the grayscale
+ erosion. Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the grayscale erosion. Non-zero values give the set of
+ neighbors of the center over which the minimum is chosen.
+ structure : array of ints, optional
+ Structuring element used for the grayscale erosion. `structure`
+ may be a non-flat structuring element. The `structure` array applies a
+ subtractive offset for each pixel in the neighborhood.
+ output : array, optional
+ An array used for storing the output of the erosion may be provided.
+ mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default 0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ output : ndarray
+ Grayscale erosion of `input`.
+
+ See Also
+ --------
+ binary_erosion, grey_dilation, grey_opening, grey_closing
+ generate_binary_structure, minimum_filter
+
+ Notes
+ -----
+ The grayscale erosion of an image input by a structuring element s defined
+ over a domain E is given by:
+
+ (input+s)(x) = min {input(y) - s(x-y), for y in E}
+
+ In particular, for structuring elements defined as
+ s(y) = 0 for y in E, the grayscale erosion computes the minimum of the
+ input image inside a sliding window defined by E.
+
+ Grayscale erosion [1]_ is a *mathematical morphology* operation [2]_.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
+ .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((7,7), dtype=int)
+ >>> a[1:6, 1:6] = 3
+ >>> a[4,4] = 2; a[2,3] = 1
+ >>> a
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 3, 3, 3, 3, 3, 0],
+ [0, 3, 3, 1, 3, 3, 0],
+ [0, 3, 3, 3, 3, 3, 0],
+ [0, 3, 3, 3, 2, 3, 0],
+ [0, 3, 3, 3, 3, 3, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.grey_erosion(a, size=(3,3))
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 3, 2, 2, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> footprint = ndimage.generate_binary_structure(2, 1)
+ >>> footprint
+ array([[False, True, False],
+ [ True, True, True],
+ [False, True, False]], dtype=bool)
+ >>> # Diagonally-connected elements are not considered neighbors
+ >>> ndimage.grey_erosion(a, footprint=footprint)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 3, 1, 2, 0, 0],
+ [0, 0, 3, 2, 2, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+
+ """
+ if size is None and footprint is None and structure is None:
+ raise ValueError("size, footprint, or structure must be specified")
+
+ return _filters._min_or_max_filter(input, size, footprint, structure,
+ output, mode, cval, origin, 1,
+ axes=axes)
+
+
+def grey_dilation(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Calculate a greyscale dilation, using either a structuring element,
+ or a footprint corresponding to a flat structuring element.
+
+ Grayscale dilation is a mathematical morphology operation. For the
+ simple case of a full and flat structuring element, it can be viewed
+ as a maximum filter over a sliding window.
+
+ Parameters
+ ----------
+ input : array_like
+ Array over which the grayscale dilation is to be computed.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the grayscale
+ dilation. Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the grayscale dilation. Non-zero values give the set of
+ neighbors of the center over which the maximum is chosen.
+ structure : array of ints, optional
+ Structuring element used for the grayscale dilation. `structure`
+ may be a non-flat structuring element. The `structure` array applies an
+ additive offset for each pixel in the neighborhood.
+ output : array, optional
+ An array used for storing the output of the dilation may be provided.
+ mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default 0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ grey_dilation : ndarray
+ Grayscale dilation of `input`.
+
+ See Also
+ --------
+ binary_dilation, grey_erosion, grey_closing, grey_opening
+ generate_binary_structure, maximum_filter
+
+ Notes
+ -----
+ The grayscale dilation of an image input by a structuring element s defined
+ over a domain E is given by:
+
+ (input+s)(x) = max {input(y) + s(x-y), for y in E}
+
+ In particular, for structuring elements defined as
+ s(y) = 0 for y in E, the grayscale dilation computes the maximum of the
+ input image inside a sliding window defined by E.
+
+ Grayscale dilation [1]_ is a *mathematical morphology* operation [2]_.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
+ .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((7,7), dtype=int)
+ >>> a[2:5, 2:5] = 1
+ >>> a[4,4] = 2; a[2,3] = 3
+ >>> a
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 3, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 2, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.grey_dilation(a, size=(3,3))
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 3, 3, 3, 1, 0],
+ [0, 1, 3, 3, 3, 1, 0],
+ [0, 1, 3, 3, 3, 2, 0],
+ [0, 1, 1, 2, 2, 2, 0],
+ [0, 1, 1, 2, 2, 2, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.grey_dilation(a, footprint=np.ones((3,3)))
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 3, 3, 3, 1, 0],
+ [0, 1, 3, 3, 3, 1, 0],
+ [0, 1, 3, 3, 3, 2, 0],
+ [0, 1, 1, 2, 2, 2, 0],
+ [0, 1, 1, 2, 2, 2, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> s = ndimage.generate_binary_structure(2,1)
+ >>> s
+ array([[False, True, False],
+ [ True, True, True],
+ [False, True, False]], dtype=bool)
+ >>> ndimage.grey_dilation(a, footprint=s)
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 3, 1, 0, 0],
+ [0, 1, 3, 3, 3, 1, 0],
+ [0, 1, 1, 3, 2, 1, 0],
+ [0, 1, 1, 2, 2, 2, 0],
+ [0, 0, 1, 1, 2, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.grey_dilation(a, size=(3,3), structure=np.ones((3,3)))
+ array([[1, 1, 1, 1, 1, 1, 1],
+ [1, 2, 4, 4, 4, 2, 1],
+ [1, 2, 4, 4, 4, 2, 1],
+ [1, 2, 4, 4, 4, 3, 1],
+ [1, 2, 2, 3, 3, 3, 1],
+ [1, 2, 2, 3, 3, 3, 1],
+ [1, 1, 1, 1, 1, 1, 1]])
+
+ """
+ if size is None and footprint is None and structure is None:
+ raise ValueError("size, footprint, or structure must be specified")
+ if structure is not None:
+ structure = np.asarray(structure)
+ structure = structure[tuple([slice(None, None, -1)] *
+ structure.ndim)]
+ if footprint is not None:
+ footprint = np.asarray(footprint)
+ footprint = footprint[tuple([slice(None, None, -1)] *
+ footprint.ndim)]
+
+ input = np.asarray(input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ origin = _ni_support._normalize_sequence(origin, len(axes))
+ for ii in range(len(origin)):
+ origin[ii] = -origin[ii]
+ if footprint is not None:
+ sz = footprint.shape[ii]
+ elif structure is not None:
+ sz = structure.shape[ii]
+ elif np.isscalar(size):
+ sz = size
+ else:
+ sz = size[ii]
+ if not sz & 1:
+ origin[ii] -= 1
+
+ return _filters._min_or_max_filter(input, size, footprint, structure,
+ output, mode, cval, origin, 0,
+ axes=axes)
+
+
+def grey_opening(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Multidimensional grayscale opening.
+
+ A grayscale opening consists in the succession of a grayscale erosion,
+ and a grayscale dilation.
+
+ Parameters
+ ----------
+ input : array_like
+ Array over which the grayscale opening is to be computed.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the grayscale
+ opening. Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the grayscale opening.
+ structure : array of ints, optional
+ Structuring element used for the grayscale opening. `structure`
+ may be a non-flat structuring element. The `structure` array applies
+ offsets to the pixels in a neighborhood (the offset is additive during
+ dilation and subtractive during erosion).
+ output : array, optional
+ An array used for storing the output of the opening may be provided.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default 0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ grey_opening : ndarray
+ Result of the grayscale opening of `input` with `structure`.
+
+ See Also
+ --------
+ binary_opening, grey_dilation, grey_erosion, grey_closing
+ generate_binary_structure
+
+ Notes
+ -----
+ The action of a grayscale opening with a flat structuring element amounts
+ to smoothen high local maxima, whereas binary opening erases small objects.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.arange(36).reshape((6,6))
+ >>> a[3, 3] = 50
+ >>> a
+ array([[ 0, 1, 2, 3, 4, 5],
+ [ 6, 7, 8, 9, 10, 11],
+ [12, 13, 14, 15, 16, 17],
+ [18, 19, 20, 50, 22, 23],
+ [24, 25, 26, 27, 28, 29],
+ [30, 31, 32, 33, 34, 35]])
+ >>> ndimage.grey_opening(a, size=(3,3))
+ array([[ 0, 1, 2, 3, 4, 4],
+ [ 6, 7, 8, 9, 10, 10],
+ [12, 13, 14, 15, 16, 16],
+ [18, 19, 20, 22, 22, 22],
+ [24, 25, 26, 27, 28, 28],
+ [24, 25, 26, 27, 28, 28]])
+ >>> # Note that the local maximum a[3,3] has disappeared
+
+ """
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ tmp = grey_erosion(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ return grey_dilation(tmp, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+
+
+def grey_closing(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Multidimensional grayscale closing.
+
+ A grayscale closing consists in the succession of a grayscale dilation,
+ and a grayscale erosion.
+
+ Parameters
+ ----------
+ input : array_like
+ Array over which the grayscale closing is to be computed.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the grayscale
+ closing. Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the grayscale closing.
+ structure : array of ints, optional
+ Structuring element used for the grayscale closing. `structure`
+ may be a non-flat structuring element. The `structure` array applies
+ offsets to the pixels in a neighborhood (the offset is additive during
+ dilation and subtractive during erosion)
+ output : array, optional
+ An array used for storing the output of the closing may be provided.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default 0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ grey_closing : ndarray
+ Result of the grayscale closing of `input` with `structure`.
+
+ See Also
+ --------
+ binary_closing, grey_dilation, grey_erosion, grey_opening,
+ generate_binary_structure
+
+ Notes
+ -----
+ The action of a grayscale closing with a flat structuring element amounts
+ to smoothen deep local minima, whereas binary closing fills small holes.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.arange(36).reshape((6,6))
+ >>> a[3,3] = 0
+ >>> a
+ array([[ 0, 1, 2, 3, 4, 5],
+ [ 6, 7, 8, 9, 10, 11],
+ [12, 13, 14, 15, 16, 17],
+ [18, 19, 20, 0, 22, 23],
+ [24, 25, 26, 27, 28, 29],
+ [30, 31, 32, 33, 34, 35]])
+ >>> ndimage.grey_closing(a, size=(3,3))
+ array([[ 7, 7, 8, 9, 10, 11],
+ [ 7, 7, 8, 9, 10, 11],
+ [13, 13, 14, 15, 16, 17],
+ [19, 19, 20, 20, 22, 23],
+ [25, 25, 26, 27, 28, 29],
+ [31, 31, 32, 33, 34, 35]])
+ >>> # Note that the local minimum a[3,3] has disappeared
+
+ """
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ tmp = grey_dilation(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ return grey_erosion(tmp, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+
+
+def morphological_gradient(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Multidimensional morphological gradient.
+
+ The morphological gradient is calculated as the difference between a
+ dilation and an erosion of the input with a given structuring element.
+
+ Parameters
+ ----------
+ input : array_like
+ Array over which to compute the morphological gradient.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the mathematical
+ morphology operations. Optional if `footprint` or `structure` is
+ provided. A larger `size` yields a more blurred gradient.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the morphology operations. Larger footprints
+ give a more blurred morphological gradient.
+ structure : array of ints, optional
+ Structuring element used for the morphology operations. `structure` may
+ be a non-flat structuring element. The `structure` array applies
+ offsets to the pixels in a neighborhood (the offset is additive during
+ dilation and subtractive during erosion)
+ output : array, optional
+ An array used for storing the output of the morphological gradient
+ may be provided.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default 0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ morphological_gradient : ndarray
+ Morphological gradient of `input`.
+
+ See Also
+ --------
+ grey_dilation, grey_erosion, gaussian_gradient_magnitude
+
+ Notes
+ -----
+ For a flat structuring element, the morphological gradient
+ computed at a given point corresponds to the maximal difference
+ between elements of the input among the elements covered by the
+ structuring element centered on the point.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.zeros((7,7), dtype=int)
+ >>> a[2:5, 2:5] = 1
+ >>> ndimage.morphological_gradient(a, size=(3,3))
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> # The morphological gradient is computed as the difference
+ >>> # between a dilation and an erosion
+ >>> ndimage.grey_dilation(a, size=(3,3)) -\\
+ ... ndimage.grey_erosion(a, size=(3,3))
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> a = np.zeros((7,7), dtype=int)
+ >>> a[2:5, 2:5] = 1
+ >>> a[4,4] = 2; a[2,3] = 3
+ >>> a
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 3, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 2, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+ >>> ndimage.morphological_gradient(a, size=(3,3))
+ array([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 3, 3, 3, 1, 0],
+ [0, 1, 3, 3, 3, 1, 0],
+ [0, 1, 3, 2, 3, 2, 0],
+ [0, 1, 1, 2, 2, 2, 0],
+ [0, 1, 1, 2, 2, 2, 0],
+ [0, 0, 0, 0, 0, 0, 0]])
+
+ """
+ tmp = grey_dilation(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ if isinstance(output, np.ndarray):
+ grey_erosion(input, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+ return np.subtract(tmp, output, output)
+ else:
+ return (tmp - grey_erosion(input, size, footprint, structure,
+ None, mode, cval, origin, axes=axes))
+
+
+def morphological_laplace(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Multidimensional morphological laplace.
+
+ Parameters
+ ----------
+ input : array_like
+ Input.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the mathematical
+ morphology operations. Optional if `footprint` or `structure` is
+ provided.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the morphology operations.
+ structure : array of ints, optional
+ Structuring element used for the morphology operations. `structure` may
+ be a non-flat structuring element. The `structure` array applies
+ offsets to the pixels in a neighborhood (the offset is additive during
+ dilation and subtractive during erosion)
+ output : ndarray, optional
+ An output array can optionally be provided.
+ mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+ The mode parameter determines how the array borders are handled.
+ For 'constant' mode, values beyond borders are set to be `cval`.
+ Default is 'reflect'.
+ cval : scalar, optional
+ Value to fill past edges of input if mode is 'constant'.
+ Default is 0.0
+ origin : origin, optional
+ The origin parameter controls the placement of the filter.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ morphological_laplace : ndarray
+ Output
+
+ """
+ input = np.asarray(input)
+ tmp1 = grey_dilation(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ if isinstance(output, np.ndarray):
+ grey_erosion(input, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+ np.add(tmp1, output, output)
+ np.subtract(output, input, output)
+ return np.subtract(output, input, output)
+ else:
+ tmp2 = grey_erosion(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ np.add(tmp1, tmp2, tmp2)
+ np.subtract(tmp2, input, tmp2)
+ np.subtract(tmp2, input, tmp2)
+ return tmp2
+
+
+def white_tophat(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Multidimensional white tophat filter.
+
+ Parameters
+ ----------
+ input : array_like
+ Input.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the filter.
+ Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of elements of a flat structuring element
+ used for the white tophat filter.
+ structure : array of ints, optional
+ Structuring element used for the filter. `structure` may be a non-flat
+ structuring element. The `structure` array applies offsets to the
+ pixels in a neighborhood (the offset is additive during dilation and
+ subtractive during erosion)
+ output : array, optional
+ An array used for storing the output of the filter may be provided.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'.
+ Default is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default is 0.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ output : ndarray
+ Result of the filter of `input` with `structure`.
+
+ See Also
+ --------
+ black_tophat
+
+ Examples
+ --------
+ Subtract gray background from a bright peak.
+
+ >>> from scipy.ndimage import generate_binary_structure, white_tophat
+ >>> import numpy as np
+ >>> square = generate_binary_structure(rank=2, connectivity=3)
+ >>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
+ ... [3, 4, 5, 4, 3],
+ ... [3, 5, 9, 5, 3],
+ ... [3, 4, 5, 4, 3],
+ ... [2, 3, 3, 3, 2]])
+ >>> white_tophat(input=bright_on_gray, structure=square)
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 1, 5, 1, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ tmp = grey_erosion(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ tmp = grey_dilation(tmp, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+ if tmp is None:
+ tmp = output
+
+ if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+ np.bitwise_xor(input, tmp, out=tmp)
+ else:
+ np.subtract(input, tmp, out=tmp)
+ return tmp
+
+
+def black_tophat(input, size=None, footprint=None, structure=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """
+ Multidimensional black tophat filter.
+
+ Parameters
+ ----------
+ input : array_like
+ Input.
+ size : tuple of ints, optional
+ Shape of a flat and full structuring element used for the filter.
+ Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the black tophat filter.
+ structure : array of ints, optional
+ Structuring element used for the filter. `structure` may be a non-flat
+ structuring element. The `structure` array applies offsets to the
+ pixels in a neighborhood (the offset is additive during dilation and
+ subtractive during erosion)
+ output : array, optional
+ An array used for storing the output of the filter may be provided.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default 0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ black_tophat : ndarray
+ Result of the filter of `input` with `structure`.
+
+ See Also
+ --------
+ white_tophat, grey_opening, grey_closing
+
+ Examples
+ --------
+ Change dark peak to bright peak and subtract background.
+
+ >>> from scipy.ndimage import generate_binary_structure, black_tophat
+ >>> import numpy as np
+ >>> square = generate_binary_structure(rank=2, connectivity=3)
+ >>> dark_on_gray = np.array([[7, 6, 6, 6, 7],
+ ... [6, 5, 4, 5, 6],
+ ... [6, 4, 0, 4, 6],
+ ... [6, 5, 4, 5, 6],
+ ... [7, 6, 6, 6, 7]])
+ >>> black_tophat(input=dark_on_gray, structure=square)
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 1, 5, 1, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ tmp = grey_dilation(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ tmp = grey_erosion(tmp, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+ if tmp is None:
+ tmp = output
+
+ if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+ np.bitwise_xor(tmp, input, out=tmp)
+ else:
+ np.subtract(tmp, input, out=tmp)
+ return tmp
+
+
+def distance_transform_bf(input, metric="euclidean", sampling=None,
+ return_distances=True, return_indices=False,
+ distances=None, indices=None):
+ """
+ Distance transform function by a brute force algorithm.
+
+ This function calculates the distance transform of the `input`, by
+ replacing each foreground (non-zero) element, with its
+ shortest distance to the background (any zero-valued element).
+
+ In addition to the distance transform, the feature transform can
+ be calculated. In this case the index of the closest background
+ element to each foreground element is returned in a separate array.
+
+ Parameters
+ ----------
+ input : array_like
+ Input
+ metric : {'euclidean', 'taxicab', 'chessboard'}, optional
+ 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+ The default is 'euclidean'.
+ sampling : float, or sequence of float, optional
+ This parameter is only used when `metric` is 'euclidean'.
+ Spacing of elements along each dimension. If a sequence, must be of
+ length equal to the input rank; if a single number, this is used for
+ all axes. If not specified, a grid spacing of unity is implied.
+ return_distances : bool, optional
+ Whether to calculate the distance transform.
+ Default is True.
+ return_indices : bool, optional
+ Whether to calculate the feature transform.
+ Default is False.
+ distances : ndarray, optional
+ An output array to store the calculated distance transform, instead of
+ returning it.
+ `return_distances` must be True.
+ It must be the same shape as `input`, and of type float64 if `metric`
+ is 'euclidean', uint32 otherwise.
+ indices : int32 ndarray, optional
+ An output array to store the calculated feature transform, instead of
+ returning it.
+ `return_indices` must be True.
+ Its shape must be ``(input.ndim,) + input.shape``.
+
+ Returns
+ -------
+ distances : ndarray, optional
+ The calculated distance transform. Returned only when
+ `return_distances` is True and `distances` is not supplied.
+ It will have the same shape as the input array.
+ indices : int32 ndarray, optional
+ The calculated feature transform. It has an input-shaped array for each
+ dimension of the input. See distance_transform_edt documentation for an
+ example.
+ Returned only when `return_indices` is True and `indices` is not
+ supplied.
+
+ See Also
+ --------
+ distance_transform_cdt : Faster distance transform for taxicab and
+ chessboard metrics
+ distance_transform_edt : Faster distance transform for euclidean metric
+
+ Notes
+ -----
+ This function employs a slow brute force algorithm. See also the
+ function `distance_transform_cdt` for more efficient taxicab [1]_ and
+ chessboard algorithms [2]_.
+
+ References
+ ----------
+ .. [1] Taxicab distance. Wikipedia, 2023.
+ https://en.wikipedia.org/wiki/Taxicab_geometry
+ .. [2] Chessboard distance. Wikipedia, 2023.
+ https://en.wikipedia.org/wiki/Chebyshev_distance
+
+ Examples
+ --------
+ Import the necessary modules.
+
+ >>> import numpy as np
+ >>> from scipy.ndimage import distance_transform_bf
+ >>> import matplotlib.pyplot as plt
+ >>> from mpl_toolkits.axes_grid1 import ImageGrid
+
+ First, we create a toy binary image.
+
+ >>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
+ ... # fill circular area with 1
+ ... xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
+ ... circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
+ ... circle_shape = np.sqrt(circle) < radius
+ ... image[circle_shape] = fillvalue
+ ... return image
+ >>> image = np.zeros((100, 100), dtype=np.uint8)
+ >>> image[35:65, 20:80] = 1
+ >>> image = add_circle(28, 65, 10, image)
+ >>> image = add_circle(37, 30, 10, image)
+ >>> image = add_circle(70, 45, 20, image)
+ >>> image = add_circle(45, 80, 10, image)
+
+ Next, we set up the figure.
+
+ >>> fig = plt.figure(figsize=(8, 8)) # set up the figure structure
+ >>> grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=(0.4, 0.3),
+ ... label_mode="1", share_all=True,
+ ... cbar_location="right", cbar_mode="each",
+ ... cbar_size="7%", cbar_pad="2%")
+ >>> for ax in grid:
+ ... ax.axis('off') # remove axes from images
+
+ The top left image is the original binary image.
+
+ >>> binary_image = grid[0].imshow(image, cmap='gray')
+ >>> cbar_binary_image = grid.cbar_axes[0].colorbar(binary_image)
+ >>> cbar_binary_image.set_ticks([0, 1])
+ >>> grid[0].set_title("Binary image: foreground in white")
+
+ The distance transform calculates the distance between foreground pixels
+ and the image background according to a distance metric. Available metrics
+ in `distance_transform_bf` are: ``euclidean`` (default), ``taxicab``
+ and ``chessboard``. The top right image contains the distance transform
+ based on the ``euclidean`` metric.
+
+ >>> distance_transform_euclidean = distance_transform_bf(image)
+ >>> euclidean_transform = grid[1].imshow(distance_transform_euclidean,
+ ... cmap='gray')
+ >>> cbar_euclidean = grid.cbar_axes[1].colorbar(euclidean_transform)
+ >>> colorbar_ticks = [0, 10, 20]
+ >>> cbar_euclidean.set_ticks(colorbar_ticks)
+ >>> grid[1].set_title("Euclidean distance")
+
+ The lower left image contains the distance transform using the ``taxicab``
+ metric.
+
+ >>> distance_transform_taxicab = distance_transform_bf(image,
+ ... metric='taxicab')
+ >>> taxicab_transformation = grid[2].imshow(distance_transform_taxicab,
+ ... cmap='gray')
+ >>> cbar_taxicab = grid.cbar_axes[2].colorbar(taxicab_transformation)
+ >>> cbar_taxicab.set_ticks(colorbar_ticks)
+ >>> grid[2].set_title("Taxicab distance")
+
+ Finally, the lower right image contains the distance transform using the
+ ``chessboard`` metric.
+
+ >>> distance_transform_cb = distance_transform_bf(image,
+ ... metric='chessboard')
+ >>> chessboard_transformation = grid[3].imshow(distance_transform_cb,
+ ... cmap='gray')
+ >>> cbar_taxicab = grid.cbar_axes[3].colorbar(chessboard_transformation)
+ >>> cbar_taxicab.set_ticks(colorbar_ticks)
+ >>> grid[3].set_title("Chessboard distance")
+ >>> plt.show()
+
+ """
+ ft_inplace = isinstance(indices, np.ndarray)
+ dt_inplace = isinstance(distances, np.ndarray)
+ _distance_transform_arg_check(
+ dt_inplace, ft_inplace, return_distances, return_indices
+ )
+
+ tmp1 = np.asarray(input) != 0
+ struct = generate_binary_structure(tmp1.ndim, tmp1.ndim)
+ tmp2 = binary_dilation(tmp1, struct)
+ tmp2 = np.logical_xor(tmp1, tmp2)
+ tmp1 = tmp1.astype(np.int8) - tmp2.astype(np.int8)
+ metric = metric.lower()
+ if metric == 'euclidean':
+ metric = 1
+ elif metric in ['taxicab', 'cityblock', 'manhattan']:
+ metric = 2
+ elif metric == 'chessboard':
+ metric = 3
+ else:
+ raise RuntimeError('distance metric not supported')
+ if sampling is not None:
+ sampling = _ni_support._normalize_sequence(sampling, tmp1.ndim)
+ sampling = np.asarray(sampling, dtype=np.float64)
+ if not sampling.flags.contiguous:
+ sampling = sampling.copy()
+ if return_indices:
+ ft = np.zeros(tmp1.shape, dtype=np.int32)
+ else:
+ ft = None
+ if return_distances:
+ if distances is None:
+ if metric == 1:
+ dt = np.zeros(tmp1.shape, dtype=np.float64)
+ else:
+ dt = np.zeros(tmp1.shape, dtype=np.uint32)
+ else:
+ if distances.shape != tmp1.shape:
+ raise RuntimeError('distances array has wrong shape')
+ if metric == 1:
+ if distances.dtype.type != np.float64:
+ raise RuntimeError('distances array must be float64')
+ else:
+ if distances.dtype.type != np.uint32:
+ raise RuntimeError('distances array must be uint32')
+ dt = distances
+ else:
+ dt = None
+
+ _nd_image.distance_transform_bf(tmp1, metric, sampling, dt, ft)
+ if return_indices:
+ if isinstance(indices, np.ndarray):
+ if indices.dtype.type != np.int32:
+ raise RuntimeError('indices array must be int32')
+ if indices.shape != (tmp1.ndim,) + tmp1.shape:
+ raise RuntimeError('indices array has wrong shape')
+ tmp2 = indices
+ else:
+ tmp2 = np.indices(tmp1.shape, dtype=np.int32)
+ ft = np.ravel(ft)
+ for ii in range(tmp2.shape[0]):
+ rtmp = np.ravel(tmp2[ii, ...])[ft]
+ rtmp = rtmp.reshape(tmp1.shape)
+ tmp2[ii, ...] = rtmp
+ ft = tmp2
+
+ # construct and return the result
+ result = []
+ if return_distances and not dt_inplace:
+ result.append(dt)
+ if return_indices and not ft_inplace:
+ result.append(ft)
+
+ if len(result) == 2:
+ return tuple(result)
+ elif len(result) == 1:
+ return result[0]
+ else:
+ return None
+
+
+def distance_transform_cdt(input, metric='chessboard', return_distances=True,
+ return_indices=False, distances=None, indices=None):
+ """
+ Distance transform for chamfer type of transforms.
+
+ This function calculates the distance transform of the `input`, by
+ replacing each foreground (non-zero) element, with its
+ shortest distance to the background (any zero-valued element).
+
+ In addition to the distance transform, the feature transform can
+ be calculated. In this case the index of the closest background
+ element to each foreground element is returned in a separate array.
+
+ Parameters
+ ----------
+ input : array_like
+ Input. Values of 0 are treated as background.
+ metric : {'chessboard', 'taxicab'} or array_like, optional
+ The `metric` determines the type of chamfering that is done. If the
+ `metric` is equal to 'taxicab' a structure is generated using
+ `generate_binary_structure` with a squared distance equal to 1. If
+ the `metric` is equal to 'chessboard', a `metric` is generated
+ using `generate_binary_structure` with a squared distance equal to
+ the dimensionality of the array. These choices correspond to the
+ common interpretations of the 'taxicab' and the 'chessboard'
+ distance metrics in two dimensions.
+ A custom metric may be provided, in the form of a matrix where
+ each dimension has a length of three.
+ 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+ The default is 'chessboard'.
+ return_distances : bool, optional
+ Whether to calculate the distance transform.
+ Default is True.
+ return_indices : bool, optional
+ Whether to calculate the feature transform.
+ Default is False.
+ distances : int32 ndarray, optional
+ An output array to store the calculated distance transform, instead of
+ returning it.
+ `return_distances` must be True.
+ It must be the same shape as `input`.
+ indices : int32 ndarray, optional
+ An output array to store the calculated feature transform, instead of
+ returning it.
+ `return_indices` must be True.
+ Its shape must be ``(input.ndim,) + input.shape``.
+
+ Returns
+ -------
+ distances : int32 ndarray, optional
+ The calculated distance transform. Returned only when
+ `return_distances` is True, and `distances` is not supplied.
+ It will have the same shape as the input array.
+ indices : int32 ndarray, optional
+ The calculated feature transform. It has an input-shaped array for each
+ dimension of the input. See distance_transform_edt documentation for an
+ example.
+ Returned only when `return_indices` is True, and `indices` is not
+ supplied.
+
+ See Also
+ --------
+ distance_transform_edt : Fast distance transform for euclidean metric
+ distance_transform_bf : Distance transform for different metrics using
+ a slower brute force algorithm
+
+ Examples
+ --------
+ Import the necessary modules.
+
+ >>> import numpy as np
+ >>> from scipy.ndimage import distance_transform_cdt
+ >>> import matplotlib.pyplot as plt
+ >>> from mpl_toolkits.axes_grid1 import ImageGrid
+
+ First, we create a toy binary image.
+
+ >>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
+ ... # fill circular area with 1
+ ... xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
+ ... circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
+ ... circle_shape = np.sqrt(circle) < radius
+ ... image[circle_shape] = fillvalue
+ ... return image
+ >>> image = np.zeros((100, 100), dtype=np.uint8)
+ >>> image[35:65, 20:80] = 1
+ >>> image = add_circle(28, 65, 10, image)
+ >>> image = add_circle(37, 30, 10, image)
+ >>> image = add_circle(70, 45, 20, image)
+ >>> image = add_circle(45, 80, 10, image)
+
+ Next, we set up the figure.
+
+ >>> fig = plt.figure(figsize=(5, 15))
+ >>> grid = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=(0.5, 0.3),
+ ... label_mode="1", share_all=True,
+ ... cbar_location="right", cbar_mode="each",
+ ... cbar_size="7%", cbar_pad="2%")
+ >>> for ax in grid:
+ ... ax.axis('off')
+ >>> top, middle, bottom = grid
+ >>> colorbar_ticks = [0, 10, 20]
+
+ The top image contains the original binary image.
+
+ >>> binary_image = top.imshow(image, cmap='gray')
+ >>> cbar_binary_image = top.cax.colorbar(binary_image)
+ >>> cbar_binary_image.set_ticks([0, 1])
+ >>> top.set_title("Binary image: foreground in white")
+
+ The middle image contains the distance transform using the ``taxicab``
+ metric.
+
+ >>> distance_taxicab = distance_transform_cdt(image, metric="taxicab")
+ >>> taxicab_transform = middle.imshow(distance_taxicab, cmap='gray')
+ >>> cbar_taxicab = middle.cax.colorbar(taxicab_transform)
+ >>> cbar_taxicab.set_ticks(colorbar_ticks)
+ >>> middle.set_title("Taxicab metric")
+
+ The bottom image contains the distance transform using the ``chessboard``
+ metric.
+
+ >>> distance_chessboard = distance_transform_cdt(image,
+ ... metric="chessboard")
+ >>> chessboard_transform = bottom.imshow(distance_chessboard, cmap='gray')
+ >>> cbar_chessboard = bottom.cax.colorbar(chessboard_transform)
+ >>> cbar_chessboard.set_ticks(colorbar_ticks)
+ >>> bottom.set_title("Chessboard metric")
+ >>> plt.tight_layout()
+ >>> plt.show()
+
+ """
+ ft_inplace = isinstance(indices, np.ndarray)
+ dt_inplace = isinstance(distances, np.ndarray)
+ _distance_transform_arg_check(
+ dt_inplace, ft_inplace, return_distances, return_indices
+ )
+ input = np.asarray(input)
+ if isinstance(metric, str):
+ if metric in ['taxicab', 'cityblock', 'manhattan']:
+ rank = input.ndim
+ metric = generate_binary_structure(rank, 1)
+ elif metric == 'chessboard':
+ rank = input.ndim
+ metric = generate_binary_structure(rank, rank)
+ else:
+ raise ValueError('invalid metric provided')
+ else:
+ try:
+ metric = np.asarray(metric)
+ except Exception as e:
+ raise ValueError('invalid metric provided') from e
+ for s in metric.shape:
+ if s != 3:
+ raise ValueError('metric sizes must be equal to 3')
+
+ if not metric.flags.contiguous:
+ metric = metric.copy()
+ if dt_inplace:
+ if distances.dtype.type != np.int32:
+ raise ValueError('distances must be of int32 type')
+ if distances.shape != input.shape:
+ raise ValueError('distances has wrong shape')
+ dt = distances
+ dt[...] = np.where(input, -1, 0).astype(np.int32)
+ else:
+ dt = np.where(input, -1, 0).astype(np.int32)
+
+ rank = dt.ndim
+ if return_indices:
+ ft = np.arange(dt.size, dtype=np.int32).reshape(dt.shape)
+ else:
+ ft = None
+
+ _nd_image.distance_transform_op(metric, dt, ft)
+ dt = dt[tuple([slice(None, None, -1)] * rank)]
+ if return_indices:
+ ft = ft[tuple([slice(None, None, -1)] * rank)]
+ _nd_image.distance_transform_op(metric, dt, ft)
+ dt = dt[tuple([slice(None, None, -1)] * rank)]
+ if return_indices:
+ ft = ft[tuple([slice(None, None, -1)] * rank)]
+ ft = np.ravel(ft)
+ if ft_inplace:
+ if indices.dtype.type != np.int32:
+ raise ValueError('indices array must be int32')
+ if indices.shape != (dt.ndim,) + dt.shape:
+ raise ValueError('indices array has wrong shape')
+ tmp = indices
+ else:
+ tmp = np.indices(dt.shape, dtype=np.int32)
+ for ii in range(tmp.shape[0]):
+ rtmp = np.ravel(tmp[ii, ...])[ft]
+ rtmp = rtmp.reshape(dt.shape)
+ tmp[ii, ...] = rtmp
+ ft = tmp
+
+ # construct and return the result
+ result = []
+ if return_distances and not dt_inplace:
+ result.append(dt)
+ if return_indices and not ft_inplace:
+ result.append(ft)
+
+ if len(result) == 2:
+ return tuple(result)
+ elif len(result) == 1:
+ return result[0]
+ else:
+ return None
+
+
+def distance_transform_edt(input, sampling=None, return_distances=True,
+ return_indices=False, distances=None, indices=None):
+ """
+ Exact Euclidean distance transform.
+
+ This function calculates the distance transform of the `input`, by
+ replacing each foreground (non-zero) element, with its
+ shortest distance to the background (any zero-valued element).
+
+ In addition to the distance transform, the feature transform can
+ be calculated. In this case the index of the closest background
+ element to each foreground element is returned in a separate array.
+
+ Parameters
+ ----------
+ input : array_like
+ Input data to transform. Can be any type but will be converted
+ into binary: 1 wherever input equates to True, 0 elsewhere.
+ sampling : float, or sequence of float, optional
+ Spacing of elements along each dimension. If a sequence, must be of
+ length equal to the input rank; if a single number, this is used for
+ all axes. If not specified, a grid spacing of unity is implied.
+ return_distances : bool, optional
+ Whether to calculate the distance transform.
+ Default is True.
+ return_indices : bool, optional
+ Whether to calculate the feature transform.
+ Default is False.
+ distances : float64 ndarray, optional
+ An output array to store the calculated distance transform, instead of
+ returning it.
+ `return_distances` must be True.
+ It must be the same shape as `input`.
+ indices : int32 ndarray, optional
+ An output array to store the calculated feature transform, instead of
+ returning it.
+ `return_indices` must be True.
+ Its shape must be ``(input.ndim,) + input.shape``.
+
+ Returns
+ -------
+ distances : float64 ndarray, optional
+ The calculated distance transform. Returned only when
+ `return_distances` is True and `distances` is not supplied.
+ It will have the same shape as the input array.
+ indices : int32 ndarray, optional
+ The calculated feature transform. It has an input-shaped array for each
+ dimension of the input. See example below.
+ Returned only when `return_indices` is True and `indices` is not
+ supplied.
+
+ Notes
+ -----
+ The Euclidean distance transform gives values of the Euclidean
+ distance::
+
+ n
+ y_i = sqrt(sum (x[i]-b[i])**2)
+ i
+
+ where b[i] is the background point (value 0) with the smallest
+ Euclidean distance to input points x[i], and n is the
+ number of dimensions.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array(([0,1,1,1,1],
+ ... [0,0,1,1,1],
+ ... [0,1,1,1,1],
+ ... [0,1,1,1,0],
+ ... [0,1,1,0,0]))
+ >>> ndimage.distance_transform_edt(a)
+ array([[ 0. , 1. , 1.4142, 2.2361, 3. ],
+ [ 0. , 0. , 1. , 2. , 2. ],
+ [ 0. , 1. , 1.4142, 1.4142, 1. ],
+ [ 0. , 1. , 1.4142, 1. , 0. ],
+ [ 0. , 1. , 1. , 0. , 0. ]])
+
+ With a sampling of 2 units along x, 1 along y:
+
+ >>> ndimage.distance_transform_edt(a, sampling=[2,1])
+ array([[ 0. , 1. , 2. , 2.8284, 3.6056],
+ [ 0. , 0. , 1. , 2. , 3. ],
+ [ 0. , 1. , 2. , 2.2361, 2. ],
+ [ 0. , 1. , 2. , 1. , 0. ],
+ [ 0. , 1. , 1. , 0. , 0. ]])
+
+ Asking for indices as well:
+
+ >>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True)
+ >>> inds
+ array([[[0, 0, 1, 1, 3],
+ [1, 1, 1, 1, 3],
+ [2, 2, 1, 3, 3],
+ [3, 3, 4, 4, 3],
+ [4, 4, 4, 4, 4]],
+ [[0, 0, 1, 1, 4],
+ [0, 1, 1, 1, 4],
+ [0, 0, 1, 4, 4],
+ [0, 0, 3, 3, 4],
+ [0, 0, 3, 3, 4]]], dtype=int32)
+
+ With arrays provided for inplace outputs:
+
+ >>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32)
+ >>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices)
+ array([[ 0. , 1. , 1.4142, 2.2361, 3. ],
+ [ 0. , 0. , 1. , 2. , 2. ],
+ [ 0. , 1. , 1.4142, 1.4142, 1. ],
+ [ 0. , 1. , 1.4142, 1. , 0. ],
+ [ 0. , 1. , 1. , 0. , 0. ]])
+ >>> indices
+ array([[[0, 0, 1, 1, 3],
+ [1, 1, 1, 1, 3],
+ [2, 2, 1, 3, 3],
+ [3, 3, 4, 4, 3],
+ [4, 4, 4, 4, 4]],
+ [[0, 0, 1, 1, 4],
+ [0, 1, 1, 1, 4],
+ [0, 0, 1, 4, 4],
+ [0, 0, 3, 3, 4],
+ [0, 0, 3, 3, 4]]], dtype=int32)
+
+ """
+ ft_inplace = isinstance(indices, np.ndarray)
+ dt_inplace = isinstance(distances, np.ndarray)
+ _distance_transform_arg_check(
+ dt_inplace, ft_inplace, return_distances, return_indices
+ )
+
+ # calculate the feature transform
+ input = np.atleast_1d(np.where(input, 1, 0).astype(np.int8))
+ if sampling is not None:
+ sampling = _ni_support._normalize_sequence(sampling, input.ndim)
+ sampling = np.asarray(sampling, dtype=np.float64)
+ if not sampling.flags.contiguous:
+ sampling = sampling.copy()
+
+ if ft_inplace:
+ ft = indices
+ if ft.shape != (input.ndim,) + input.shape:
+ raise RuntimeError('indices array has wrong shape')
+ if ft.dtype.type != np.int32:
+ raise RuntimeError('indices array must be int32')
+ else:
+ ft = np.zeros((input.ndim,) + input.shape, dtype=np.int32)
+
+ _nd_image.euclidean_feature_transform(input, sampling, ft)
+ # if requested, calculate the distance transform
+ if return_distances:
+ dt = ft - np.indices(input.shape, dtype=ft.dtype)
+ dt = dt.astype(np.float64)
+ if sampling is not None:
+ for ii in range(len(sampling)):
+ dt[ii, ...] *= sampling[ii]
+ np.multiply(dt, dt, dt)
+ if dt_inplace:
+ dt = np.add.reduce(dt, axis=0)
+ if distances.shape != dt.shape:
+ raise RuntimeError('distances array has wrong shape')
+ if distances.dtype.type != np.float64:
+ raise RuntimeError('distances array must be float64')
+ np.sqrt(dt, distances)
+ else:
+ dt = np.add.reduce(dt, axis=0)
+ dt = np.sqrt(dt)
+
+ # construct and return the result
+ result = []
+ if return_distances and not dt_inplace:
+ result.append(dt)
+ if return_indices and not ft_inplace:
+ result.append(ft)
+
+ if len(result) == 2:
+ return tuple(result)
+ elif len(result) == 1:
+ return result[0]
+ else:
+ return None
+
+
+def _distance_transform_arg_check(distances_out, indices_out,
+ return_distances, return_indices):
+ """Raise a RuntimeError if the arguments are invalid"""
+ error_msgs = []
+ if (not return_distances) and (not return_indices):
+ error_msgs.append(
+ 'at least one of return_distances/return_indices must be True')
+ if distances_out and not return_distances:
+ error_msgs.append(
+ 'return_distances must be True if distances is supplied'
+ )
+ if indices_out and not return_indices:
+ error_msgs.append('return_indices must be True if indices is supplied')
+ if error_msgs:
+ raise RuntimeError(', '.join(error_msgs))
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e164b5436c7c5a8743eb5d3e33010c90137fbdd9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:100424b75cdc0e0d0a42ef8a9df2f205597706c3567100bfe929f246b2a33df0
+size 175576
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1673391726a4070af4814d04be16e29e01d9f29b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py
@@ -0,0 +1,16 @@
+"""This is the 'bare' ndimage API.
+
+This --- private! --- module only collects implementations of public ndimage API
+for _support_alternative_backends.
+The latter --- also private! --- module adds delegation to CuPy etc and
+re-exports decorated names to __init__.py
+"""
+
+from ._filters import * # noqa: F403
+from ._fourier import * # noqa: F403
+from ._interpolation import * # noqa: F403
+from ._measurements import * # noqa: F403
+from ._morphology import * # noqa: F403
+
+# '@' due to pytest bug, scipy/scipy#22236
+__all__ = [s for s in dir() if not s.startswith(('_', '@'))]
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba84c7a21a5c642ffa2b89ccc94f8ad8d053e7c4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py
@@ -0,0 +1,220 @@
+"""Docstring components common to several ndimage functions."""
+from typing import Final
+
+from scipy._lib import doccer
+
+__all__ = ['docfiller']
+
+
+_input_doc = (
+"""input : array_like
+ The input array.""")
+_axis_doc = (
+"""axis : int, optional
+ The axis of `input` along which to calculate. Default is -1.""")
+_output_doc = (
+"""output : array or dtype, optional
+ The array in which to place the output, or the dtype of the
+ returned array. By default an array of the same dtype as input
+ will be created.""")
+_nan_doc = (
+"""The behavior of this function with NaN elements is undefined. To control
+behavior in the presence of NaNs, consider using `vectorized_filter`.""")
+_size_foot_doc = (
+"""size : scalar or tuple, optional
+ See footprint, below. Ignored if footprint is given.
+footprint : array, optional
+ Either `size` or `footprint` must be defined. `size` gives
+ the shape that is taken from the input array, at every element
+ position, to define the input to the filter function.
+ `footprint` is a boolean array that specifies (implicitly) a
+ shape, but also which of the elements within this shape will get
+ passed to the filter function. Thus ``size=(n,m)`` is equivalent
+ to ``footprint=np.ones((n,m))``. We adjust `size` to the number
+ of dimensions of the input array, so that, if the input array is
+ shape (10,10,10), and `size` is 2, then the actual size used is
+ (2,2,2). When `footprint` is given, `size` is ignored.""")
+_mode_reflect_doc = (
+"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the input array is extended
+ beyond its boundaries. Default is 'reflect'. Behavior for each valid
+ value is as follows:
+
+ 'reflect' (`d c b a | a b c d | d c b a`)
+ The input is extended by reflecting about the edge of the last
+ pixel. This mode is also sometimes referred to as half-sample
+ symmetric.
+
+ 'constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter.
+
+ 'nearest' (`a a a a | a b c d | d d d d`)
+ The input is extended by replicating the last pixel.
+
+ 'mirror' (`d c b | a b c d | c b a`)
+ The input is extended by reflecting about the center of the last
+ pixel. This mode is also sometimes referred to as whole-sample
+ symmetric.
+
+ 'wrap' (`a b c d | a b c d | a b c d`)
+ The input is extended by wrapping around to the opposite edge.
+
+ For consistency with the interpolation functions, the following mode
+ names can also be used:
+
+ 'grid-mirror'
+ This is a synonym for 'reflect'.
+
+ 'grid-constant'
+ This is a synonym for 'constant'.
+
+ 'grid-wrap'
+ This is a synonym for 'wrap'.""")
+
+_mode_interp_constant_doc = (
+"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \
+'mirror', 'grid-wrap', 'wrap'}, optional
+ The `mode` parameter determines how the input array is extended
+ beyond its boundaries. Default is 'constant'. Behavior for each valid
+ value is as follows (see additional plots and details on
+ :ref:`boundary modes `):
+
+ 'reflect' (`d c b a | a b c d | d c b a`)
+ The input is extended by reflecting about the edge of the last
+ pixel. This mode is also sometimes referred to as half-sample
+ symmetric.
+
+ 'grid-mirror'
+ This is a synonym for 'reflect'.
+
+ 'constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter. No
+ interpolation is performed beyond the edges of the input.
+
+ 'grid-constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter. Interpolation
+ occurs for samples outside the input's extent as well.
+
+ 'nearest' (`a a a a | a b c d | d d d d`)
+ The input is extended by replicating the last pixel.
+
+ 'mirror' (`d c b | a b c d | c b a`)
+ The input is extended by reflecting about the center of the last
+ pixel. This mode is also sometimes referred to as whole-sample
+ symmetric.
+
+ 'grid-wrap' (`a b c d | a b c d | a b c d`)
+ The input is extended by wrapping around to the opposite edge.
+
+ 'wrap' (`b c d b c | a b c d | b c a b c`)
+ The input is extended by wrapping around to the opposite edge, but in a
+ way such that the last point and initial point exactly overlap. In this
+ case it is not well defined which sample will be chosen at the point of
+ overlap.
+
+
+ For the example illustrated above, the edge values ``a`` and ``d`` overlap,
+ while the inner pattern ``b c`` repeats. The example demonstrates one
+ possible output, while ``b c a b c | a b c d | b c d b c`` is another,
+ since either ``a`` or ``d`` may occur at each point of overlap.""")
+_mode_interp_mirror_doc = (
+ _mode_interp_constant_doc.replace("Default is 'constant'",
+ "Default is 'mirror'")
+)
+assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \
+ 'Default not replaced'
+
+_mode_multiple_doc = (
+"""mode : str or sequence, optional
+ The `mode` parameter determines how the input array is extended
+ when the filter overlaps a border. By passing a sequence of modes
+ with length equal to the number of dimensions of the input array,
+ different modes can be specified along each axis. Default value is
+ 'reflect'. The valid values and their behavior is as follows:
+
+ 'reflect' (`d c b a | a b c d | d c b a`)
+ The input is extended by reflecting about the edge of the last
+ pixel. This mode is also sometimes referred to as half-sample
+ symmetric.
+
+ 'constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter.
+
+ 'nearest' (`a a a a | a b c d | d d d d`)
+ The input is extended by replicating the last pixel.
+
+ 'mirror' (`d c b | a b c d | c b a`)
+ The input is extended by reflecting about the center of the last
+ pixel. This mode is also sometimes referred to as whole-sample
+ symmetric.
+
+ 'wrap' (`a b c d | a b c d | a b c d`)
+ The input is extended by wrapping around to the opposite edge.
+
+ For consistency with the interpolation functions, the following mode
+ names can also be used:
+
+ 'grid-constant'
+ This is a synonym for 'constant'.
+
+ 'grid-mirror'
+ This is a synonym for 'reflect'.
+
+ 'grid-wrap'
+ This is a synonym for 'wrap'.""")
+_cval_doc = (
+"""cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.""")
+_origin_doc = (
+"""origin : int, optional
+ Controls the placement of the filter on the input array's pixels.
+ A value of 0 (the default) centers the filter over the pixel, with
+ positive values shifting the filter to the left, and negative ones
+ to the right.""")
+_origin_multiple_doc = (
+"""origin : int or sequence, optional
+ Controls the placement of the filter on the input array's pixels.
+ A value of 0 (the default) centers the filter over the pixel, with
+ positive values shifting the filter to the left, and negative ones
+ to the right. By passing a sequence of origins with length equal to
+ the number of dimensions of the input array, different shifts can
+ be specified along each axis.""")
+_extra_arguments_doc = (
+"""extra_arguments : sequence, optional
+ Sequence of extra positional arguments to pass to passed function.""")
+_extra_keywords_doc = (
+"""extra_keywords : dict, optional
+ dict of extra keyword arguments to pass to passed function.""")
+_prefilter_doc = (
+"""prefilter : bool, optional
+ Determines if the input array is prefiltered with `spline_filter`
+ before interpolation. The default is True, which will create a
+ temporary `float64` array of filtered values if ``order > 1``. If
+ setting this to False, the output will be slightly blurred if
+ ``order > 1``, unless the input is prefiltered, i.e. it is the result
+ of calling `spline_filter` on the original input.""")
+
+docdict = {
+ 'input': _input_doc,
+ 'axis': _axis_doc,
+ 'output': _output_doc,
+ 'size_foot': _size_foot_doc,
+ 'mode_interp_constant': _mode_interp_constant_doc,
+ 'mode_interp_mirror': _mode_interp_mirror_doc,
+ 'mode_reflect': _mode_reflect_doc,
+ 'mode_multiple': _mode_multiple_doc,
+ 'cval': _cval_doc,
+ 'origin': _origin_doc,
+ 'origin_multiple': _origin_multiple_doc,
+ 'extra_arguments': _extra_arguments_doc,
+ 'extra_keywords': _extra_keywords_doc,
+ 'prefilter': _prefilter_doc,
+ 'nan': _nan_doc,
+ }
+
+docfiller: Final = doccer.filldoc(docdict)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..9127c2c80fb5fad8674eb12de2f678011e144070
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:639e113aee21ad4d53663fa9023f66aaff72c9706ed093aaf2f18c8cde8e4908
+size 228496
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..52c526347653b214480f845ec96ab0d9fc72af5d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py
@@ -0,0 +1,139 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+from collections.abc import Iterable
+import operator
+import warnings
+import numpy as np
+
+
+def _extend_mode_to_code(mode, is_filter=False):
+ """Convert an extension mode to the corresponding integer code.
+ """
+ if mode == 'nearest':
+ return 0
+ elif mode == 'wrap':
+ return 1
+ elif mode in ['reflect', 'grid-mirror']:
+ return 2
+ elif mode == 'mirror':
+ return 3
+ elif mode == 'constant':
+ return 4
+ elif mode == 'grid-wrap' and is_filter:
+ return 1
+ elif mode == 'grid-wrap':
+ return 5
+ elif mode == 'grid-constant' and is_filter:
+ return 4
+ elif mode == 'grid-constant':
+ return 6
+ else:
+ raise RuntimeError('boundary mode not supported')
+
+
+def _normalize_sequence(input, rank):
+ """If input is a scalar, create a sequence of length equal to the
+ rank by duplicating the input. If input is a sequence,
+ check if its length is equal to the length of array.
+ """
+ is_str = isinstance(input, str)
+ if not is_str and np.iterable(input):
+ normalized = list(input)
+ if len(normalized) != rank:
+ err = "sequence argument must have length equal to input rank"
+ raise RuntimeError(err)
+ else:
+ normalized = [input] * rank
+ return normalized
+
+
+def _get_output(output, input, shape=None, complex_output=False):
+ if shape is None:
+ shape = input.shape
+ if output is None:
+ if not complex_output:
+ output = np.zeros(shape, dtype=input.dtype.name)
+ else:
+ complex_type = np.promote_types(input.dtype, np.complex64)
+ output = np.zeros(shape, dtype=complex_type)
+ elif isinstance(output, type | np.dtype):
+ # Classes (like `np.float32`) and dtypes are interpreted as dtype
+ if complex_output and np.dtype(output).kind != 'c':
+ warnings.warn("promoting specified output dtype to complex", stacklevel=3)
+ output = np.promote_types(output, np.complex64)
+ output = np.zeros(shape, dtype=output)
+ elif isinstance(output, str):
+ output = np.dtype(output)
+ if complex_output and output.kind != 'c':
+ raise RuntimeError("output must have complex dtype")
+ elif not issubclass(output.type, np.number):
+ raise RuntimeError("output must have numeric dtype")
+ output = np.zeros(shape, dtype=output)
+ else:
+ # output was supplied as an array
+ output = np.asarray(output)
+ if output.shape != shape:
+ raise RuntimeError("output shape not correct")
+ elif complex_output and output.dtype.kind != 'c':
+ raise RuntimeError("output must have complex dtype")
+ return output
+
+
+def _check_axes(axes, ndim):
+ if axes is None:
+ return tuple(range(ndim))
+ elif np.isscalar(axes):
+ axes = (operator.index(axes),)
+ elif isinstance(axes, Iterable):
+ for ax in axes:
+ axes = tuple(operator.index(ax) for ax in axes)
+ if ax < -ndim or ax > ndim - 1:
+ raise ValueError(f"specified axis: {ax} is out of range")
+ axes = tuple(ax % ndim if ax < 0 else ax for ax in axes)
+ else:
+ message = "axes must be an integer, iterable of integers, or None"
+ raise ValueError(message)
+ if len(tuple(set(axes))) != len(axes):
+ raise ValueError("axes must be unique")
+ return axes
+
+def _skip_if_dtype(arg):
+ """'array or dtype' polymorphism.
+
+ Return None for np.int8, dtype('float32') or 'f' etc
+ arg for np.empty(3) etc
+ """
+ if isinstance(arg, str):
+ return None
+ if type(arg) is type:
+ return None if issubclass(arg, np.generic) else arg
+ else:
+ return None if isinstance(arg, np.dtype) else arg
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..dd6bb25a04160e2aa38ad8082a3befc0dcdccf82
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..70afa13356a553177fe45b5ab5f877096ca97278
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py
@@ -0,0 +1,122 @@
+import functools
+from scipy._lib._array_api import (
+ is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API, xp_capabilities
+)
+
+import numpy as np
+from ._ndimage_api import * # noqa: F403
+from . import _ndimage_api
+from . import _delegators
+__all__ = _ndimage_api.__all__
+
+
+MODULE_NAME = 'ndimage'
+
+
+def _maybe_convert_arg(arg, xp):
+ """Convert arrays/scalars hiding in the sequence `arg`."""
+ if isinstance(arg, np.ndarray | np.generic):
+ return xp.asarray(arg)
+ elif isinstance(arg, list | tuple):
+ return type(arg)(_maybe_convert_arg(x, xp) for x in arg)
+ else:
+ return arg
+
+
+# Some cupyx.scipy.ndimage functions don't exist or are incompatible with
+# their SciPy counterparts
+CUPY_BLOCKLIST = [
+ 'distance_transform_bf',
+ 'distance_transform_cdt',
+ 'find_objects',
+ 'geometric_transform',
+ 'vectorized_filter',
+]
+
+
+def delegate_xp(delegator, module_name):
+ def inner(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwds):
+ xp = delegator(*args, **kwds)
+
+ # try delegating to a cupyx/jax namesake
+ if is_cupy(xp) and func.__name__ not in CUPY_BLOCKLIST:
+ # https://github.com/cupy/cupy/issues/8336
+ import importlib
+ cupyx_module = importlib.import_module(f"cupyx.scipy.{module_name}")
+ cupyx_func = getattr(cupyx_module, func.__name__)
+ return cupyx_func(*args, **kwds)
+ elif is_jax(xp) and func.__name__ == "map_coordinates":
+ spx = scipy_namespace_for(xp)
+ jax_module = getattr(spx, module_name)
+ jax_func = getattr(jax_module, func.__name__)
+ return jax_func(*args, **kwds)
+ else:
+ # the original function (does all np.asarray internally)
+ # XXX: output arrays
+ result = func(*args, **kwds)
+
+ if isinstance(result, np.ndarray | np.generic):
+ # XXX: np.int32->np.array_0D
+ return xp.asarray(result)
+ elif isinstance(result, int):
+ return result
+ elif isinstance(result, dict):
+ # value_indices:
+ # result is {np.int64(1): (array(0), array(1))} etc
+ return {
+ k.item(): tuple(xp.asarray(vv) for vv in v)
+ for k,v in result.items()
+ }
+ elif result is None:
+ # inplace operations
+ return result
+ else:
+ # lists/tuples
+ return _maybe_convert_arg(result, xp)
+ return wrapper
+ return inner
+
+default_capabilities = xp_capabilities(
+ cpu_only=True, exceptions=["cupy"], allow_dask_compute=True, jax_jit=False
+)
+
+capabilities_dict = {
+ "geometric_transform": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "find_objects": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "distance_transform_bf": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "distance_transform_cdt": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "vectorized_filter": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "generate_binary_structure": xp_capabilities(out_of_scope=True),
+ "map_coordinates": xp_capabilities(
+ cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True, jax_jit=True
+ ),
+ "labeled_comprehension": xp_capabilities(np_only=True),
+}
+
+# ### decorate ###
+for func_name in _ndimage_api.__all__:
+ bare_func = getattr(_ndimage_api, func_name)
+ delegator = getattr(_delegators, func_name + "_signature")
+
+ capabilities = capabilities_dict.get(func_name, default_capabilities)
+
+ # pyrefly:ignore[not-callable]
+ f = capabilities(
+ delegate_xp(delegator, MODULE_NAME)(bare_func)
+ if SCIPY_ARRAY_API else bare_func
+ )
+ # add the decorated function to the namespace, to be imported in __init__.py
+ vars()[func_name] = f
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/filters.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/filters.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'correlate1d', 'convolve1d', 'gaussian_filter1d',
+ 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace',
+ 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude',
+ 'gaussian_gradient_magnitude', 'correlate', 'convolve',
+ 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+ 'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+ 'rank_filter', 'median_filter', 'percentile_filter',
+ 'generic_filter1d', 'generic_filter'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='filters',
+ private_modules=['_filters'], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/fourier.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c49bd52d9a446ce0fe25d9e15b8de68fbd46fb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/fourier.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'fourier_gaussian', 'fourier_uniform',
+ 'fourier_ellipsoid', 'fourier_shift'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='fourier',
+ private_modules=['_fourier'], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/interpolation.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2739c60c51037487ae8892c407e2f3d7870d5da
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/interpolation.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'spline_filter1d', 'spline_filter',
+ 'geometric_transform', 'map_coordinates',
+ 'affine_transform', 'shift', 'zoom', 'rotate',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='interpolation',
+ private_modules=['_interpolation'], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/measurements.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f76b01840ffb829205bd1d28a7ad1f9ac5db61
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/measurements.py
@@ -0,0 +1,24 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'label', 'find_objects', 'labeled_comprehension',
+ 'sum', 'mean', 'variance', 'standard_deviation',
+ 'minimum', 'maximum', 'median', 'minimum_position',
+ 'maximum_position', 'extrema', 'center_of_mass',
+ 'histogram', 'watershed_ift', 'sum_labels'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='measurements',
+ private_modules=['_measurements'], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/morphology.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..e522e7df3a4b06b7e04ed8c2d0ecaff2a98b951d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/morphology.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'iterate_structure', 'generate_binary_structure',
+ 'binary_erosion', 'binary_dilation', 'binary_opening',
+ 'binary_closing', 'binary_hit_or_miss', 'binary_propagation',
+ 'binary_fill_holes', 'grey_erosion', 'grey_dilation',
+ 'grey_opening', 'grey_closing', 'morphological_gradient',
+ 'morphological_laplace', 'white_tophat', 'black_tophat',
+ 'distance_transform_bf', 'distance_transform_cdt',
+ 'distance_transform_edt'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='morphology',
+ private_modules=['_morphology'], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d8fd292b537a84fe48d0c8ae8bee75bab2b3353
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py
@@ -0,0 +1,12 @@
+import numpy as np
+
+# list of numarray data types
+integer_types: list[str] = [
+ "int8", "uint8", "int16", "uint16",
+ "int32", "uint32", "int64", "uint64"]
+
+float_types: list[str] = ["float32", "float64"]
+
+complex_types: list[str] = ["complex64", "complex128"]
+
+types: list[str] = integer_types + float_types
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6c3cff3b12cec4ad050b31cc5d5c327f32784447
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt
@@ -0,0 +1,21 @@
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 0 1 1 1 0 1
+0 0 0 1 0 0 0
+1 0 0 1 0 0 1
+1 1 1 1 1 1 1
+1 0 0 1 0 0 1
+0 0 0 1 0 0 0
+1 0 1 1 1 0 1
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c239b0369c9df3e06df9a2fbf048faec2f84941f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt
@@ -0,0 +1,294 @@
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+2 2 2 2 2 2 2
+3 3 3 3 3 3 3
+4 4 4 4 4 4 4
+5 5 5 5 5 5 5
+6 6 6 6 6 6 6
+7 7 7 7 7 7 7
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 3 4 5 6 7
+8 9 10 11 12 13 14
+15 16 17 18 19 20 21
+22 23 24 25 26 27 28
+29 30 31 32 33 34 35
+36 37 38 39 40 41 42
+43 44 45 46 47 48 49
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 3 4 5 6 7
+8 1 2 3 4 5 6
+9 8 1 2 3 4 5
+10 9 8 1 2 3 4
+11 10 9 8 1 2 3
+12 11 10 9 8 1 2
+13 12 11 10 9 8 1
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+1 2 3 4 5 6 7
+2 3 4 5 6 7 8
+3 4 5 6 7 8 9
+4 5 6 7 8 9 10
+5 6 7 8 9 10 11
+6 7 8 9 10 11 12
+7 8 9 10 11 12 13
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 4
+0 0 0 2 0 0 0
+5 0 2 0 6 0 7
+2 2 0 0 0 7 7
+2 2 2 0 7 7 7
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+3 0 1 0 4 0 2
+0 0 0 1 0 0 0
+5 0 6 0 1 0 7
+5 5 0 0 0 1 1
+5 5 5 0 1 1 1
+1 1 1 0 2 2 2
+3 3 0 0 0 4 4
+5 0 6 0 7 0 8
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+14 14 0 0 0 15 15
+16 16 16 0 17 17 17
+1 1 1 0 2 3 3
+1 1 0 0 0 3 3
+1 0 4 0 3 0 3
+0 0 0 3 0 0 0
+3 0 3 0 5 0 6
+3 3 0 0 0 6 6
+3 3 7 0 6 6 6
+1 2 3 0 4 5 6
+7 8 0 0 0 9 10
+11 0 12 0 13 0 14
+0 0 0 15 0 0 0
+16 0 17 0 18 0 19
+20 21 0 0 0 22 23
+24 25 26 0 27 28 29
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 2
+0 0 0 2 0 0 0
+2 0 2 0 4 0 5
+2 2 0 0 0 5 5
+2 2 2 0 5 5 5
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 4 0 2
+0 0 0 5 0 0 0
+6 0 7 0 8 0 9
+6 6 0 0 0 9 9
+6 6 6 0 9 9 9
+1 2 3 0 4 5 6
+7 1 0 0 0 4 5
+8 0 1 0 9 0 4
+0 0 0 1 0 0 0
+10 0 11 0 1 0 12
+13 10 0 0 0 1 14
+15 13 10 0 16 17 1
+1 2 3 0 4 5 6
+1 2 0 0 0 5 6
+1 0 7 0 8 0 6
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+10 14 0 0 0 15 13
+10 14 16 0 17 15 13
+1 1 1 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 1 2 0 3 3 3
+1 1 0 0 0 3 3
+1 0 1 0 4 0 3
+0 0 0 1 0 0 0
+5 0 6 0 1 0 1
+5 5 0 0 0 1 1
+5 5 5 0 7 1 1
+1 2 1 0 1 3 1
+2 1 0 0 0 1 3
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+4 1 0 0 0 1 5
+1 4 1 0 1 5 1
+1 2 3 0 4 5 6
+2 3 0 0 0 6 7
+3 0 8 0 6 0 9
+0 0 0 6 0 0 0
+10 0 6 0 11 0 12
+13 6 0 0 0 12 14
+6 15 16 0 12 14 17
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 1 0 3 0 2
+0 0 0 1 0 0 0
+4 0 5 0 1 0 1
+4 4 0 0 0 1 1
+4 4 4 0 1 1 1
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 5 0 0 5
+5 5 5 5 5 5 5
+5 0 0 5 0 0 6
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 4 0 0 5
+4 4 4 4 4 4 4
+6 0 0 4 0 0 4
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 4 0 0 0
+5 0 0 6 0 0 7
+8 8 8 8 8 8 8
+9 0 0 10 0 0 11
+0 0 0 12 0 0 0
+13 0 14 14 14 0 15
+1 0 2 3 3 0 4
+0 0 0 3 0 0 0
+5 0 0 3 0 0 6
+5 5 3 3 3 6 6
+5 0 0 3 0 0 6
+0 0 0 3 0 0 0
+7 0 3 3 8 0 9
+1 0 2 3 4 0 5
+0 0 0 6 0 0 0
+7 0 0 8 0 0 9
+10 11 12 13 14 15 16
+17 0 0 18 0 0 19
+0 0 0 20 0 0 0
+21 0 22 23 24 0 25
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 3 4 0 5
+0 0 0 2 0 0 0
+6 0 0 7 0 0 8
+9 6 10 11 7 12 13
+14 0 0 10 0 0 12
+0 0 0 15 0 0 0
+16 0 17 18 15 0 19
+1 0 2 3 4 0 5
+0 0 0 3 0 0 0
+6 0 0 3 0 0 7
+6 8 9 3 10 11 7
+6 0 0 3 0 0 7
+0 0 0 3 0 0 0
+12 0 13 3 14 0 15
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 3 0 4
+0 0 0 2 0 0 0
+5 0 0 2 0 0 6
+5 5 2 2 2 6 6
+5 0 0 2 0 0 6
+0 0 0 2 0 0 0
+7 0 8 2 2 0 9
+1 0 2 3 2 0 4
+0 0 0 2 0 0 0
+5 0 0 6 0 0 7
+8 5 6 9 6 7 10
+5 0 0 6 0 0 7
+0 0 0 11 0 0 0
+12 0 11 13 11 0 14
+1 0 2 3 4 0 5
+0 0 0 4 0 0 0
+6 0 0 7 0 0 8
+9 10 7 11 12 8 13
+10 0 0 12 0 0 14
+0 0 0 15 0 0 0
+16 0 15 17 18 0 19
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..35ae8121364d4fb3292c11f2a72333f456fa9c0a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt
@@ -0,0 +1,42 @@
+0 0 1
+1 1 1
+1 0 0
+1 0 0
+1 1 1
+0 0 1
+0 0 0
+1 1 1
+0 0 0
+0 1 1
+0 1 0
+1 1 0
+0 0 0
+0 0 0
+0 0 0
+0 1 1
+1 1 1
+1 1 0
+0 1 0
+1 1 1
+0 1 0
+1 0 0
+0 1 0
+0 0 1
+0 1 0
+0 1 0
+0 1 0
+1 1 1
+1 1 1
+1 1 1
+1 1 0
+0 1 0
+0 1 1
+1 0 1
+0 1 0
+1 0 1
+0 0 1
+0 1 0
+1 0 0
+1 1 0
+1 1 1
+0 1 1
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png
new file mode 100644
index 0000000000000000000000000000000000000000..2cb593b8e1cf68e429cc8402838c31f70be59afc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b20b56fadc7471c0694d3e8148d9e28a83d7967bac16bf8852094afea3950414
+size 2114
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..61a5a0f70262ef9f21fe8593a64f155bd583cab1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py
@@ -0,0 +1,102 @@
+import numpy as np
+from scipy._lib._array_api import xp_assert_close
+
+from scipy import ndimage
+from scipy.ndimage import _ctest
+from scipy.ndimage import _cytest
+from scipy._lib._ccallback import LowLevelCallable
+
+FILTER1D_FUNCTIONS = [
+ lambda filter_size: _ctest.filter1d(filter_size),
+ lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
+ lambda filter_size: LowLevelCallable(
+ _cytest.filter1d(filter_size, with_signature=True)
+ ),
+ lambda filter_size: LowLevelCallable.from_cython(
+ _cytest, "_filter1d",
+ _cytest.filter1d_capsule(filter_size),
+ ),
+]
+
+FILTER2D_FUNCTIONS = [
+ lambda weights: _ctest.filter2d(weights),
+ lambda weights: _cytest.filter2d(weights, with_signature=False),
+ lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
+ lambda weights: LowLevelCallable.from_cython(_cytest,
+ "_filter2d",
+ _cytest.filter2d_capsule(weights),),
+]
+
+TRANSFORM_FUNCTIONS = [
+ lambda shift: _ctest.transform(shift),
+ lambda shift: _cytest.transform(shift, with_signature=False),
+ lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
+ lambda shift: LowLevelCallable.from_cython(_cytest,
+ "_transform",
+ _cytest.transform_capsule(shift),),
+]
+
+
+def test_generic_filter():
+ def filter2d(footprint_elements, weights):
+ return (weights*footprint_elements).sum()
+
+ def check(j):
+ func = FILTER2D_FUNCTIONS[j]
+
+ im = np.ones((20, 20))
+ im[:10,:10] = 0
+ footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
+ footprint_size = np.count_nonzero(footprint)
+ weights = np.ones(footprint_size)/footprint_size
+
+ res = ndimage.generic_filter(im, func(weights),
+ footprint=footprint)
+ std = ndimage.generic_filter(im, filter2d, footprint=footprint,
+ extra_arguments=(weights,))
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+ for j, func in enumerate(FILTER2D_FUNCTIONS):
+ check(j)
+
+
+def test_generic_filter1d():
+ def filter1d(input_line, output_line, filter_size):
+ for i in range(output_line.size):
+ output_line[i] = 0
+ for j in range(filter_size):
+ output_line[i] += input_line[i+j]
+ output_line /= filter_size
+
+ def check(j):
+ func = FILTER1D_FUNCTIONS[j]
+
+ im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
+ filter_size = 3
+
+ res = ndimage.generic_filter1d(im, func(filter_size),
+ filter_size)
+ std = ndimage.generic_filter1d(im, filter1d, filter_size,
+ extra_arguments=(filter_size,))
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+ for j, func in enumerate(FILTER1D_FUNCTIONS):
+ check(j)
+
+
+def test_geometric_transform():
+ def transform(output_coordinates, shift):
+ return output_coordinates[0] - shift, output_coordinates[1] - shift
+
+ def check(j):
+ func = TRANSFORM_FUNCTIONS[j]
+
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
+ shift = 0.5
+
+ res = ndimage.geometric_transform(im, func(shift))
+ std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+ for j, func in enumerate(TRANSFORM_FUNCTIONS):
+ check(j)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..a82de456bb92c96d5b9a599d4b33c987e134fdc8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py
@@ -0,0 +1,67 @@
+""" Testing data types for ndimage calls
+"""
+import numpy as np
+
+from scipy._lib._array_api import assert_array_almost_equal
+import pytest
+
+from scipy import ndimage
+
+
+def test_map_coordinates_dts():
+ # check that ndimage accepts different data types for interpolation
+ data = np.array([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ shifted_data = np.array([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]])
+ idx = np.indices(data.shape)
+ dts = (np.uint8, np.uint16, np.uint32, np.uint64,
+ np.int8, np.int16, np.int32, np.int64,
+ np.intp, np.uintp, np.float32, np.float64)
+ for order in range(0, 6):
+ for data_dt in dts:
+ these_data = data.astype(data_dt)
+ for coord_dt in dts:
+ # affine mapping
+ mat = np.eye(2, dtype=coord_dt)
+ off = np.zeros((2,), dtype=coord_dt)
+ out = ndimage.affine_transform(these_data, mat, off)
+ assert_array_almost_equal(these_data, out)
+ # map coordinates
+ coords_m1 = idx.astype(coord_dt) - 1
+ coords_p10 = idx.astype(coord_dt) + 10
+ out = ndimage.map_coordinates(these_data, coords_m1, order=order)
+ assert_array_almost_equal(out, shifted_data)
+ # check constant fill works
+ out = ndimage.map_coordinates(these_data, coords_p10, order=order)
+ assert_array_almost_equal(out, np.zeros((3,4)))
+ # check shift and zoom
+ out = ndimage.shift(these_data, 1)
+ assert_array_almost_equal(out, shifted_data)
+ out = ndimage.zoom(these_data, 1)
+ assert_array_almost_equal(these_data, out)
+
+
+@pytest.mark.xfail(True, reason="Broken on many platforms")
+def test_uint64_max():
+ # Test interpolation respects uint64 max. Reported to fail at least on
+ # win32 (due to the 32 bit visual C compiler using signed int64 when
+ # converting between uint64 to double) and Debian on s390x.
+ # Interpolation is always done in double precision floating point, so
+ # we use the largest uint64 value for which int(float(big)) still fits
+ # in a uint64.
+ # This test was last enabled on macOS only, and there it started failing
+ # on arm64 as well (see gh-19117).
+ big = 2**64 - 1025
+ arr = np.array([big, big, big], dtype=np.uint64)
+ # Tests geometric transform (map_coordinates, affine_transform)
+ inds = np.indices(arr.shape) - 0.1
+ x = ndimage.map_coordinates(arr, inds)
+ assert x[1] == int(float(big))
+ assert x[2] == int(float(big))
+ # Tests zoom / shift
+ x = ndimage.shift(arr, 0.1)
+ assert x[1] == int(float(big))
+ assert x[2] == int(float(big))
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d3f3ae06f50137a40f7df78d186271cce8ceb82
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py
@@ -0,0 +1,3381 @@
+''' Some tests for filters '''
+import functools
+import itertools
+import re
+import contextlib
+import warnings
+import importlib
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose, assert_array_equal
+from hypothesis import strategies as st
+from hypothesis import given
+import hypothesis.extra.numpy as npst
+from pytest import raises as assert_raises
+from scipy import ndimage
+from scipy._lib._array_api import (
+ assert_almost_equal,
+ assert_array_almost_equal,
+ xp_assert_close,
+ xp_assert_equal,
+ make_xp_test_case,
+ make_xp_pytest_param,
+)
+from scipy._lib._array_api import (is_cupy, is_torch, is_dask, is_jax, array_namespace,
+ is_array_api_strict, xp_copy)
+from scipy.ndimage._filters import _gaussian_kernel1d
+
+from . import types, float_types, complex_types
+
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+uses_output_dtype = skip_xp_backends(
+ np_only=True, exceptions=["cupy"],
+ reason="output=dtype is numpy-specific"
+)
+
+try:
+ CUPY_VERSION = importlib.metadata.version('cupy')
+except ImportError:
+ CUPY_VERSION = None
+
+
+def uses_output_array(f):
+ return skip_xp_backends("dask.array", reason="output=array requires buffer view")(
+ skip_xp_backends("jax.numpy", reason="output=array requires buffer view")(f))
+
+
+
+def sumsq(a, b, xp=None):
+ xp = array_namespace(a, b) if xp is None else xp
+ return xp.sqrt(xp.sum((a - b)**2))
+
+
+def _complex_correlate(xp, array, kernel, real_dtype, convolve=False,
+ mode="reflect", cval=0, ):
+ """Utility to perform a reference complex-valued convolutions.
+
+ When convolve==False, correlation is performed instead
+ """
+ array = xp.asarray(array)
+ kernel = xp.asarray(kernel)
+ complex_array = xp.isdtype(array.dtype, 'complex floating')
+ complex_kernel = xp.isdtype(kernel.dtype, 'complex floating')
+ if array.ndim == 1:
+ func = ndimage.convolve1d if convolve else ndimage.correlate1d
+ else:
+ func = ndimage.convolve if convolve else ndimage.correlate
+ if not convolve:
+ kernel = xp.conj(kernel)
+ if complex_array and complex_kernel:
+ # use: real(cval) for array.real component
+ # imag(cval) for array.imag component
+ re_cval = cval.real if isinstance(cval, complex) else xp.real(cval)
+ im_cval = cval.imag if isinstance(cval, complex) else xp.imag(cval)
+
+ output = (
+ func(xp.real(array), xp.real(kernel), output=real_dtype,
+ mode=mode, cval=re_cval) -
+ func(xp.imag(array), xp.imag(kernel), output=real_dtype,
+ mode=mode, cval=im_cval) +
+ 1j * func(xp.imag(array), xp.real(kernel), output=real_dtype,
+ mode=mode, cval=im_cval) +
+ 1j * func(xp.real(array), xp.imag(kernel), output=real_dtype,
+ mode=mode, cval=re_cval)
+ )
+ elif complex_array:
+ re_cval = xp.real(cval)
+ re_cval = re_cval.item() if isinstance(re_cval, xp.ndarray) else re_cval
+ im_cval = xp.imag(cval)
+ im_cval = im_cval.item() if isinstance(im_cval, xp.ndarray) else im_cval
+
+ output = (
+ func(xp.real(array), kernel, output=real_dtype, mode=mode,
+ cval=re_cval) +
+ 1j * func(xp.imag(array), kernel, output=real_dtype, mode=mode,
+ cval=im_cval)
+ )
+ elif complex_kernel:
+ # real array so cval is real too
+ output = (
+ func(array, xp.real(kernel), output=real_dtype, mode=mode, cval=cval) +
+ 1j * func(array, xp.imag(kernel), output=real_dtype, mode=mode,
+ cval=cval)
+ )
+ return output
+
+
+def _cases_axes_tuple_length_mismatch():
+ # Generate combinations of filter function, valid kwargs, and
+ # keyword-value pairs for which the value will become with mismatched
+ # (invalid) size
+ filter_func = ndimage.gaussian_filter
+ kwargs = dict(radius=3, mode='constant', sigma=1.0, order=0)
+ for key, val in kwargs.items():
+ yield make_xp_pytest_param(filter_func, kwargs, key, val)
+
+ filter_funcs = [ndimage.uniform_filter, ndimage.minimum_filter,
+ ndimage.maximum_filter]
+ kwargs = dict(size=3, mode='constant', origin=0)
+ for filter_func in filter_funcs:
+ for key, val in kwargs.items():
+ yield make_xp_pytest_param(filter_func, kwargs, key, val)
+
+ filter_funcs = [ndimage.correlate, ndimage.convolve]
+ # sequence of mode not supported for correlate or convolve
+ kwargs = dict(origin=0)
+ for filter_func in filter_funcs:
+ for key, val in kwargs.items():
+ yield make_xp_pytest_param(filter_func, kwargs, key, val)
+
+
+class TestNdimageFilters:
+ def _validate_complex(self, xp, array, kernel, type2, mode='reflect',
+ cval=0, check_warnings=True):
+ # utility for validating complex-valued correlations
+ real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype
+ expected = _complex_correlate(
+ xp, array, kernel, real_dtype, convolve=False, mode=mode, cval=cval
+ )
+
+ if array.ndim == 1:
+ correlate = functools.partial(ndimage.correlate1d, axis=-1,
+ mode=mode, cval=cval)
+ convolve = functools.partial(ndimage.convolve1d, axis=-1,
+ mode=mode, cval=cval)
+ else:
+ correlate = functools.partial(ndimage.correlate, mode=mode,
+ cval=cval)
+ convolve = functools.partial(ndimage.convolve, mode=mode,
+ cval=cval)
+
+ # test correlate output dtype
+ output = correlate(array, kernel, output=type2)
+ assert_array_almost_equal(expected, output)
+ assert output.dtype.type == type2
+
+ # test correlate with pre-allocated output
+ output = xp.zeros_like(array, dtype=type2)
+ correlate(array, kernel, output=output)
+ assert_array_almost_equal(expected, output)
+
+ # test convolve output dtype
+ output = convolve(array, kernel, output=type2)
+ expected = _complex_correlate(
+ xp, array, kernel, real_dtype, convolve=True, mode=mode, cval=cval,
+ )
+ assert_array_almost_equal(expected, output)
+ assert output.dtype.type == type2
+
+ # convolve with pre-allocated output
+ convolve(array, kernel, output=output)
+ assert_array_almost_equal(expected, output)
+ assert output.dtype.type == type2
+
+ if check_warnings:
+ # warns if the output is not a complex dtype
+ with pytest.warns(UserWarning,
+ match="promoting specified output dtype to "
+ "complex"):
+ correlate(array, kernel, output=real_dtype)
+
+ with pytest.warns(UserWarning,
+ match="promoting specified output dtype to "
+ "complex"):
+ convolve(array, kernel, output=real_dtype)
+
+ # raises if output array is provided, but is not complex-valued
+ output_real = xp.zeros_like(array, dtype=real_dtype)
+ with assert_raises(RuntimeError):
+ correlate(array, kernel, output=output_real)
+
+ with assert_raises(RuntimeError):
+ convolve(array, kernel, output=output_real)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate01(self, xp):
+ array = xp.asarray([1, 2])
+ weights = xp.asarray([2])
+ expected = xp.asarray([2, 4])
+
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ @xfail_xp_backends('cupy', reason="Differs by a factor of two?")
+ @uses_output_array
+ @make_xp_test_case(ndimage.correlate1d)
+ def test_correlate01_overlap(self, xp):
+ array = xp.reshape(xp.arange(256), (16, 16))
+ weights = xp.asarray([2])
+ expected = 2 * array
+
+ ndimage.correlate1d(array, weights, output=array)
+ assert_array_almost_equal(array, expected)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate02(self, xp):
+ array = xp.asarray([1, 2, 3])
+ kernel = xp.asarray([1])
+
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ output = ndimage.correlate1d(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ output = ndimage.convolve1d(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate03(self, xp):
+ array = xp.asarray([1])
+ weights = xp.asarray([1, 1])
+ expected = xp.asarray([2])
+
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate04(self, xp):
+ array = xp.asarray([1, 2])
+ tcor = xp.asarray([2, 3])
+ tcov = xp.asarray([3, 4])
+ weights = xp.asarray([1, 1])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, tcov)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, tcov)
+
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate05(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([2, 3, 5])
+ tcov = xp.asarray([3, 5, 6])
+ kernel = xp.asarray([1, 1])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(tcov, output)
+ output = ndimage.correlate1d(array, kernel)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve1d(array, kernel)
+ assert_array_almost_equal(tcov, output)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate06(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([9, 14, 17])
+ tcov = xp.asarray([7, 10, 15])
+ weights = xp.asarray([1, 2, 3])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, tcov)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, tcov)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate07(self, xp):
+ array = xp.asarray([1, 2, 3])
+ expected = xp.asarray([5, 8, 11])
+ weights = xp.asarray([1, 2, 1])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate08(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([1, 2, 5])
+ tcov = xp.asarray([3, 6, 7])
+ weights = xp.asarray([1, 2, -1])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, tcov)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, tcov)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate09(self, xp):
+ array = xp.asarray([])
+ kernel = xp.asarray([1, 1])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.correlate1d(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.convolve1d(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate10(self, xp):
+ array = xp.asarray([[]])
+ kernel = xp.asarray([[1, 1]])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate11(self, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]])
+ kernel = xp.asarray([[1, 1],
+ [1, 1]])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(xp.asarray([[12, 16, 18], [18, 22, 24]]), output)
+
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate12(self, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]])
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_kernel', types)
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate13(self, dtype_array, dtype_kernel, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_kernel = getattr(xp, dtype_kernel)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel, output=dtype_kernel)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype.type == dtype_kernel
+
+ output = ndimage.convolve(array, kernel,
+ output=dtype_kernel)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype.type == dtype_kernel
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate14(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = xp.zeros(array.shape, dtype=dtype_output)
+ ndimage.correlate(array, kernel, output=output)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype == dtype_output
+
+ ndimage.convolve(array, kernel, output=output)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype == dtype_output
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate15(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype.type == xp.float32
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate16(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[0.5, 0],
+ [0, 0.5]])
+ array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[1, 1.5, 2.5], [2.5, 3, 4]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[3, 4, 4.5], [4.5, 5.5, 6]]), output)
+ assert output.dtype.type == xp.float32
+
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate17(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([3, 5, 6])
+ tcov = xp.asarray([2, 3, 5])
+ kernel = xp.asarray([1, 1])
+ output = ndimage.correlate(array, kernel, origin=-1)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve(array, kernel, origin=-1)
+ assert_array_almost_equal(tcov, output)
+ output = ndimage.correlate1d(array, kernel, origin=-1)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve1d(array, kernel, origin=-1)
+ assert_array_almost_equal(tcov, output)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate18(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=-1)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=-1)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype.type == xp.float32
+
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ @xfail_xp_backends(
+ "cupy", CUPY_VERSION and CUPY_VERSION >= "14",
+ reason="multiple modes work in CuPy 14"
+ )
+ def test_correlate_mode_sequence(self, xp):
+
+ kernel = xp.ones((2, 2))
+ array = xp.ones((3, 3), dtype=xp.float64)
+ with assert_raises(RuntimeError):
+ ndimage.correlate(array, kernel, mode=['nearest', 'reflect'])
+ with assert_raises(RuntimeError):
+ ndimage.convolve(array, kernel, mode=['nearest', 'reflect'])
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @make_xp_test_case(ndimage.correlate, ndimage.convolve)
+ def test_correlate19(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[5, 6, 8], [8, 9, 11]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[3, 5, 6], [6, 8, 9]]), output)
+ assert output.dtype.type == xp.float32
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.convolve1d)
+ def test_correlate20(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0, output=output)
+ assert_array_almost_equal(output, expected)
+ ndimage.convolve1d(array, weights, axis=0, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.correlate1d, ndimage.convolve1d)
+ def test_correlate21(self, xp):
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]])
+ expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+ weights = xp.asarray([1, 2, 1])
+ output = ndimage.correlate1d(array, weights, axis=0)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.convolve1d(array, weights, axis=0)
+ assert_array_almost_equal(output, expected)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.convolve1d)
+ def test_correlate22(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ expected = xp.asarray([[6, 12, 18], [6, 12, 18]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='wrap', output=output)
+ assert_array_almost_equal(output, expected)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='wrap', output=output)
+ assert_array_almost_equal(output, expected)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.convolve1d)
+ def test_correlate23(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='nearest', output=output)
+ assert_array_almost_equal(output, expected)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='nearest', output=output)
+ assert_array_almost_equal(output, expected)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.convolve1d)
+ def test_correlate24(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ tcor = xp.asarray([[7, 14, 21], [8, 16, 24]])
+ tcov = xp.asarray([[4, 8, 12], [5, 10, 15]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=-1)
+ assert_array_almost_equal(output, tcor)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=-1)
+ assert_array_almost_equal(output, tcov)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.convolve1d)
+ def test_correlate25(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ tcor = xp.asarray([[4, 8, 12], [5, 10, 15]])
+ tcov = xp.asarray([[7, 14, 21], [8, 16, 24]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=1)
+ assert_array_almost_equal(output, tcor)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=1)
+ assert_array_almost_equal(output, tcov)
+
+ @make_xp_test_case(ndimage.correlate1d, ndimage.convolve1d)
+ def test_correlate26(self, xp):
+ # test fix for gh-11661 (mirror extension of a length 1 signal)
+ y = ndimage.convolve1d(xp.ones(1), xp.ones(5), mode='mirror')
+ xp_assert_equal(y, xp.asarray([5.]))
+
+ y = ndimage.correlate1d(xp.ones(1), xp.ones(5), mode='mirror')
+ xp_assert_equal(y, xp.asarray([5.]))
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate_complex_kernel(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ @pytest.mark.parametrize('mode', ['grid-constant', 'constant'])
+ def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel,
+ dtype_output, mode, xp,
+ num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ if is_cupy(xp) and mode == 'grid-constant':
+ pytest.xfail('cupy/cupy#8404')
+
+ # test use of non-zero cval with complex inputs
+ # also verifies that mode 'grid-constant' does not segfault
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output, mode=mode,
+ cval=5.0,
+ check_warnings=num_parallel_threads == 1)
+
+ @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate_complex_kernel_invalid_cval(self, dtype_input,
+ dtype_kernel, xp):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+
+ # cannot give complex cval with a real image
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_input)
+ for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d,
+ ndimage.correlate1d]:
+ with pytest.raises((ValueError, TypeError)):
+ func(array, kernel, mode='constant', cval=5.0 + 1.0j,
+ output=xp.complex64)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+ array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel,
+ dtype_output, xp,
+ num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+ array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5.0,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', types)
+ @pytest.mark.parametrize('dtype_input', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate_complex_input(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2j, 3],
+ [1 + 4j, 5, 6j]], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', types)
+ @pytest.mark.parametrize('dtype_input', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate1d_complex_input(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype_kernel', types)
+ @pytest.mark.parametrize('dtype_input', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel,
+ dtype_output, xp,
+ num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5 - 3j,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate_complex_input_and_kernel(self, dtype, dtype_output, xp,
+ num_parallel_threads):
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype)
+ array = xp.asarray([[1, 2j, 3],
+ [1 + 4j, 5, 6j]], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate_complex_input_and_kernel_cval(self, dtype,
+ dtype_output, xp,
+ num_parallel_threads):
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5.0 + 2.0j,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output, xp,
+ num_parallel_threads):
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+ def test_correlate1d_complex_input_and_kernel_cval(self, dtype,
+ dtype_output, xp,
+ num_parallel_threads):
+
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5.0 + 2.0j,
+ check_warnings=num_parallel_threads == 1)
+
+ @make_xp_test_case(ndimage.gaussian_filter)
+ def test_gauss01(self, xp):
+ input = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=xp.float32)
+ output = ndimage.gaussian_filter(input, 0)
+ assert_array_almost_equal(output, input)
+
+ @make_xp_test_case(ndimage.gaussian_filter)
+ def test_gauss02(self, xp):
+ input = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=xp.float32)
+ output = ndimage.gaussian_filter(input, 1.0)
+ assert input.dtype == output.dtype
+ assert input.shape == output.shape
+
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8403")
+ @make_xp_test_case(ndimage.gaussian_filter)
+ def test_gauss03(self, xp):
+ # single precision data
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ output = ndimage.gaussian_filter(input, [1.0, 1.0])
+
+ assert input.dtype == output.dtype
+ assert input.shape == output.shape
+
+ # input.sum() is 49995000.0. With single precision floats, we can't
+ # expect more than 8 digits of accuracy, so use decimal=0 in this test.
+ o_sum = xp.sum(output, dtype=xp.float64)
+ i_sum = xp.sum(input, dtype=xp.float64)
+ assert_almost_equal(o_sum, i_sum, decimal=0)
+ assert sumsq(input, output) > 1.0
+
+ @uses_output_dtype
+ @make_xp_test_case(ndimage.gaussian_filter)
+ def test_gauss04(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ otype = xp.float64
+ output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+ assert output.dtype.type == xp.float64
+ assert input.shape == output.shape
+ assert sumsq(input, output) > 1.0
+
+ @uses_output_dtype
+ @make_xp_test_case(ndimage.gaussian_filter)
+ def test_gauss05(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ otype = xp.float64
+ output = ndimage.gaussian_filter(input, [1.0, 1.0],
+ order=1, output=otype)
+ assert output.dtype.type == xp.float64
+ assert input.shape == output.shape
+ assert sumsq(input, output) > 1.0
+
+ @uses_output_dtype
+ @make_xp_test_case(ndimage.gaussian_filter)
+ def test_gauss06(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ otype = xp.float64
+ output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+ output2 = ndimage.gaussian_filter(input, 1.0, output=otype)
+ assert_array_almost_equal(output1, output2)
+
+ @uses_output_array
+ @make_xp_test_case(ndimage.gaussian_filter)
+ def test_gauss_memory_overlap(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ output1 = ndimage.gaussian_filter(input, 1.0)
+ ndimage.gaussian_filter(input, 1.0, output=input)
+ assert_array_almost_equal(output1, input)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ ('filter_func', 'extra_args', 'size0', 'size'),
+ [
+ make_xp_pytest_param(ndimage.gaussian_filter, (), 0, 1.0),
+ make_xp_pytest_param(ndimage.uniform_filter, (), 1, 3),
+ make_xp_pytest_param(ndimage.minimum_filter, (), 1, 3),
+ make_xp_pytest_param(ndimage.maximum_filter, (), 1, 3),
+ make_xp_pytest_param(ndimage.median_filter, (), 1, 3),
+ make_xp_pytest_param(ndimage.rank_filter, (1,), 1, 3),
+ make_xp_pytest_param(ndimage.percentile_filter, (40,), 1, 3),
+ ],
+ )
+ @pytest.mark.parametrize(
+ 'axes',
+ tuple(itertools.combinations(range(-3, 3), 1))
+ + tuple(itertools.combinations(range(-3, 3), 2))
+ + ((0, 1, 2),))
+ def test_filter_axes(self, filter_func, extra_args, size0, size, axes, xp):
+ # Note: `size` is called `sigma` in `gaussian_filter`
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ if len(set(ax % array.ndim for ax in axes)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ filter_func(array, *extra_args, size, axes=axes)
+ return
+ output = filter_func(array, *extra_args, size, axes=axes)
+
+ # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+ axes = xp.asarray(axes)
+ all_sizes = tuple(size if ax in (axes % array.ndim) else size0
+ for ax in range(array.ndim))
+ expected = filter_func(array, *extra_args, all_sizes)
+ xp_assert_close(output, expected)
+
+ @skip_xp_backends("cupy",
+ reason="these filters do not yet have axes support")
+ @pytest.mark.parametrize(
+ ('filter_func', 'kwargs'),
+ [
+ make_xp_pytest_param(ndimage.laplace, {}),
+ make_xp_pytest_param(ndimage.gaussian_gradient_magnitude, {"sigma": 1.0}),
+ make_xp_pytest_param(ndimage.gaussian_laplace, {"sigma": 0.5})
+ ],
+ )
+ def test_derivative_filter_axes(self, xp, filter_func, kwargs):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ # duplicate axes raises an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ filter_func(array, axes=(1, 1), **kwargs)
+
+ # compare results to manually looping over the non-filtered axes
+ output = filter_func(array, axes=(1, 2), **kwargs)
+ expected = xp.empty_like(output)
+ expected = []
+ for i in range(array.shape[0]):
+ expected.append(filter_func(array[i, ...], **kwargs))
+ expected = xp.stack(expected, axis=0)
+ xp_assert_close(output, expected)
+
+ output = filter_func(array, axes=(0, -1), **kwargs)
+ expected = []
+ for i in range(array.shape[1]):
+ expected.append(filter_func(array[:, i, :], **kwargs))
+ expected = xp.stack(expected, axis=1)
+ xp_assert_close(output, expected)
+
+ output = filter_func(array, axes=(1), **kwargs)
+ expected = []
+ for i in range(array.shape[0]):
+ exp_inner = []
+ for j in range(array.shape[2]):
+ exp_inner.append(filter_func(array[i, :, j], **kwargs))
+ expected.append(xp.stack(exp_inner, axis=-1))
+ expected = xp.stack(expected, axis=0)
+ xp_assert_close(output, expected)
+
+ @skip_xp_backends("cupy",
+ reason="generic_filter does not yet have axes support")
+ @pytest.mark.parametrize(
+ 'axes',
+ tuple(itertools.combinations(range(-3, 3), 1))
+ + tuple(itertools.combinations(range(-3, 3), 2))
+ + ((0, 1, 2),))
+ @make_xp_test_case(ndimage.generic_filter, ndimage.maximum_filter)
+ def test_generic_filter_axes(self, xp, axes):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ size = 3
+ if len(set(ax % array.ndim for ax in axes)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+ return
+
+ # choose np.amax as the function so we can compare to maximum_filter
+ output = ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+ expected = ndimage.maximum_filter(array, size=size, axes=axes)
+ xp_assert_close(output, expected)
+
+ @skip_xp_backends("cupy",
+ reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ 'func',
+ [
+ make_xp_pytest_param(ndimage.correlate),
+ make_xp_pytest_param(ndimage.convolve),
+ ]
+ )
+ @pytest.mark.parametrize(
+ 'dtype', [np.float32, np.float64, np.complex64, np.complex128]
+ )
+ @pytest.mark.parametrize(
+ 'axes', tuple(itertools.combinations(range(-3, 3), 2))
+ )
+ @pytest.mark.parametrize('origin', [(0, 0), (-1, 1)])
+ def test_correlate_convolve_axes(self, xp, func, dtype, axes, origin):
+ array = xp.asarray(np.arange(6 * 8 * 12, dtype=dtype).reshape(6, 8, 12))
+ weights = xp.arange(3 * 5)
+ weights = xp.reshape(weights, (3, 5))
+ axes = tuple(ax % array.ndim for ax in axes)
+ if len(tuple(set(axes))) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError):
+ func(array, weights=weights, axes=axes, origin=origin)
+ return
+ output = func(array, weights=weights, axes=axes, origin=origin)
+
+ missing_axis = tuple(set(range(3)) - set(axes))[0]
+ # module 'torch' has no attribute 'expand_dims' so use reshape instead
+ # weights_3d = xp.expand_dims(weights, axis=missing_axis)
+ shape_3d = (
+ weights.shape[:missing_axis] + (1,) + weights.shape[missing_axis:]
+ )
+ weights_3d = xp.reshape(weights, shape_3d)
+ origin_3d = [0, 0, 0]
+ for i, ax in enumerate(axes):
+ origin_3d[ax] = origin[i]
+ expected = func(array, weights=weights_3d, origin=origin_3d)
+ xp_assert_close(output, expected)
+
+ kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2],
+ mode=['reflect', 'nearest', 'constant'])
+ kwargs_other = dict(origin=(-1, 0, 1),
+ mode=['reflect', 'nearest', 'constant'])
+ kwargs_rank = dict(origin=(-1, 0, 1))
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ "filter_func, size0, size, kwargs",
+ [
+ make_xp_pytest_param(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss),
+ make_xp_pytest_param(ndimage.uniform_filter, 1, 3, kwargs_other),
+ make_xp_pytest_param(ndimage.maximum_filter, 1, 3, kwargs_other),
+ make_xp_pytest_param(ndimage.minimum_filter, 1, 3, kwargs_other),
+ make_xp_pytest_param(ndimage.median_filter, 1, 3, kwargs_rank),
+ make_xp_pytest_param(ndimage.rank_filter, 1, 3, kwargs_rank),
+ make_xp_pytest_param(ndimage.percentile_filter, 1, 3, kwargs_rank),
+ ]
+ )
+ @pytest.mark.parametrize('axes', list(itertools.combinations(range(-3, 3), 2)))
+ def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ kwargs = {key: np.array(val) for key, val in kwargs.items()}
+ axes = np.array(axes)
+ n_axes = axes.size
+
+ if filter_func == ndimage.rank_filter:
+ args = (2,) # (rank,)
+ elif filter_func == ndimage.percentile_filter:
+ args = (30,) # (percentile,)
+ else:
+ args = ()
+
+ # form kwargs that specify only the axes in `axes`
+ reduced_kwargs = {key: val[axes] for key, val in kwargs.items()}
+ if len(set(axes % array.ndim)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ filter_func(array, *args, [size]*n_axes, axes=axes,
+ **reduced_kwargs)
+ return
+
+ output = filter_func(array, *args, [size]*n_axes, axes=axes,
+ **reduced_kwargs)
+
+ # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+ size_3d = np.full(array.ndim, fill_value=size0)
+ size_3d[axes] = size
+ size_3d = [size_3d[i] for i in range(size_3d.shape[0])]
+ if 'origin' in kwargs:
+ # origin should be zero on the axis that has size 0
+ origin = np.asarray([0, 0, 0])
+ origin[axes] = reduced_kwargs['origin']
+ origin = xp.asarray(origin)
+ kwargs['origin'] = origin
+ expected = filter_func(array, *args, size_3d, **kwargs)
+ xp_assert_close(output, expected)
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ "filter_func, kwargs",
+ [
+ make_xp_pytest_param(ndimage.convolve, {}),
+ make_xp_pytest_param(ndimage.correlate, {}),
+ make_xp_pytest_param(ndimage.minimum_filter, {}),
+ make_xp_pytest_param(ndimage.maximum_filter, {}),
+ make_xp_pytest_param(ndimage.median_filter, {}),
+ make_xp_pytest_param(ndimage.rank_filter, {"rank": 1}),
+ make_xp_pytest_param(ndimage.percentile_filter, {"percentile": 30}),
+ ]
+ )
+ def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp):
+ axes = (-2, -1)
+ origins = (0, 1)
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ # weights with ndim matching len(axes)
+ footprint = np.ones((3, 5), dtype=bool)
+ footprint[0, 1] = 0 # make non-separable
+ footprint = xp.asarray(footprint)
+
+ if filter_func in (ndimage.convolve, ndimage.correlate):
+ kwargs["weights"] = footprint
+ else:
+ kwargs["footprint"] = footprint
+ kwargs["axes"] = axes
+
+ output = filter_func(array, origin=origins, **kwargs)
+
+ output0 = filter_func(array, origin=0, **kwargs)
+
+ # output has origin shift on last axis relative to output0, so
+ # expect shifted arrays to be equal.
+ if filter_func == ndimage.convolve:
+ # shift is in the opposite direction for convolve because it
+ # flips the weights array and negates the origin values.
+ xp_assert_equal(
+ output[:, :, :-origins[1]], output0[:, :, origins[1]:])
+ else:
+ xp_assert_equal(
+ output[:, :, origins[1]:], output0[:, :, :-origins[1]])
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ 'filter_func, args',
+ [
+ make_xp_pytest_param(*t) for t in
+ [
+ (ndimage.convolve, (np.ones((3, 3, 3)),)), # args = (weights,)
+ (ndimage.correlate,(np.ones((3, 3, 3)),)), # args = (weights,)
+ (ndimage.gaussian_filter, (1.0,)), # args = (sigma,)
+ (ndimage.uniform_filter, (3,)), # args = (size,)
+ (ndimage.minimum_filter, (3,)), # args = (size,)
+ (ndimage.maximum_filter, (3,)), # args = (size,)
+ (ndimage.median_filter, (3,)), # args = (size,)
+ (ndimage.rank_filter, (2, 3)), # args = (rank, size)
+ (ndimage.percentile_filter, (30, 3)), # args = (percentile, size)
+ ]
+ ]
+ )
+ @pytest.mark.parametrize(
+ 'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)]
+ )
+ def test_filter_invalid_axes(self, filter_func, args, axes, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ args = [
+ xp.asarray(arg) if isinstance(arg, np.ndarray) else arg
+ for arg in args
+ ]
+ if any(isinstance(ax, float) for ax in axes):
+ error_class = TypeError
+ match = "cannot be interpreted as an integer"
+ else:
+ error_class = ValueError
+ match = "out of range"
+ with pytest.raises(error_class, match=match):
+ filter_func(array, *args, axes=axes)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ 'filter_func, kwargs',
+ [
+ make_xp_pytest_param(ndimage.convolve, {}),
+ make_xp_pytest_param(ndimage.correlate, {}),
+ make_xp_pytest_param(ndimage.minimum_filter, {}),
+ make_xp_pytest_param(ndimage.maximum_filter, {}),
+ make_xp_pytest_param(ndimage.median_filter, {}),
+ make_xp_pytest_param(ndimage.rank_filter, dict(rank=3)),
+ make_xp_pytest_param(ndimage.percentile_filter, dict(percentile=30)),
+ ]
+ )
+ @pytest.mark.parametrize(
+ 'axes', [(0, ), (1, 2), (0, 1, 2)]
+ )
+ @pytest.mark.parametrize('separable_footprint', [False, True])
+ def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes,
+ separable_footprint, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ # create a footprint with one too many dimensions
+ footprint = np.ones((3,) * (len(axes) + 1))
+ if not separable_footprint:
+ footprint[(0,) * footprint.ndim] = 0
+ footprint = xp.asarray(footprint)
+ if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter]
+ and separable_footprint):
+ match = "sequence argument must have length equal to input rank"
+ elif filter_func in [ndimage.convolve, ndimage.correlate]:
+ match = re.escape(f"weights.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ else:
+ match = re.escape(f"footprint.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ if filter_func in [ndimage.convolve, ndimage.correlate]:
+ kwargs["weights"] = footprint
+ else:
+ kwargs["footprint"] = footprint
+ with pytest.raises(RuntimeError, match=match):
+ filter_func(array, axes=axes, **kwargs)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize('n_mismatch', [1, 3])
+ @pytest.mark.parametrize('filter_func, kwargs, key, val',
+ list(_cases_axes_tuple_length_mismatch()))
+ def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func,
+ kwargs, key, val, xp):
+ # Test for the intended RuntimeError when a kwargs has an invalid size
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ axes = (0, 1)
+ kwargs = dict(**kwargs, axes=axes)
+ kwargs[key] = (val,) * n_mismatch
+ if filter_func in [ndimage.convolve, ndimage.correlate]:
+ kwargs["weights"] = xp.ones((5,) * len(axes))
+ err_msg = "sequence argument must have length equal to input rank"
+ with pytest.raises(RuntimeError, match=err_msg):
+ filter_func(array, **kwargs)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.prewitt)
+ def test_prewitt01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+ output = ndimage.prewitt(array, 0)
+ assert_array_almost_equal(t, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.prewitt)
+ def test_prewitt02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.prewitt(array, 0, output)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.prewitt)
+ def test_prewitt03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]:
+ pytest.xfail("uint UB? XXX")
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 0)
+ output = ndimage.prewitt(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.prewitt)
+ def test_prewitt04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.prewitt(array, -1)
+ output = ndimage.prewitt(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.sobel)
+ def test_sobel01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+ output = ndimage.sobel(array, 0)
+ assert_array_almost_equal(t, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.sobel)
+ def test_sobel02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.sobel(array, 0, output)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.sobel)
+ def test_sobel03(self, dtype, xp):
+ if is_cupy(xp) and dtype in ["uint32", "uint64"]:
+ pytest.xfail("uint UB? XXX")
+
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 0)
+ output = xp.zeros(array.shape, dtype=dtype)
+ output = ndimage.sobel(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.sobel)
+ def test_sobel04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.sobel(array, -1)
+ output = ndimage.sobel(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ @make_xp_test_case(ndimage.correlate1d, ndimage.laplace)
+ def test_laplace01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+ tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+ output = ndimage.laplace(array)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ @make_xp_test_case(ndimage.correlate1d, ndimage.laplace)
+ def test_laplace02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+ tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.laplace(array, output=output)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ @make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_laplace)
+ def test_gaussian_laplace01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+ output = ndimage.gaussian_laplace(array, 1.0)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ @make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_laplace)
+ def test_gaussian_laplace02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.gaussian_laplace(array, 1.0, output)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ @make_xp_test_case(
+ ndimage.gaussian_filter,
+ ndimage.generic_laplace,
+ ndimage.gaussian_laplace,
+ )
+ def test_generic_laplace01(self, dtype, xp):
+ def derivative2(input, axis, output, mode, cval, a, b):
+ sigma = np.asarray([a, b / 2.0])
+ order = [0] * input.ndim
+ order[axis] = 2
+ return ndimage.gaussian_filter(input, sigma, order,
+ output, mode, cval)
+
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = xp.zeros(array.shape, dtype=dtype)
+ tmp = ndimage.generic_laplace(array, derivative2,
+ extra_arguments=(1.0,),
+ extra_keywords={'b': 2.0})
+ ndimage.gaussian_laplace(array, 1.0, output)
+ assert_array_almost_equal(tmp, output)
+
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ @make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_gradient_magnitude)
+ def test_gaussian_gradient_magnitude01(self, dtype, xp):
+ is_int_dtype = dtype == "int32"
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+ output = ndimage.gaussian_gradient_magnitude(array, 1.0)
+ expected = tmp1 * tmp1 + tmp2 * tmp2
+
+ expected_float = xp.astype(expected, xp.float64) if is_int_dtype else expected
+ expected = xp.astype(xp.sqrt(expected_float), dtype)
+ xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ @make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_gradient_magnitude)
+ def test_gaussian_gradient_magnitude02(self, dtype, xp):
+ is_int_dtype = dtype == 'int32'
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.gaussian_gradient_magnitude(array, 1.0, output)
+ expected = tmp1 * tmp1 + tmp2 * tmp2
+
+ fl_expected = xp.astype(expected, xp.float64) if is_int_dtype else expected
+
+ expected = xp.astype(xp.sqrt(fl_expected), dtype)
+ xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+ @make_xp_test_case(
+ ndimage.gaussian_filter,
+ ndimage.gaussian_gradient_magnitude,
+ ndimage.generic_gradient_magnitude,
+ )
+ def test_generic_gradient_magnitude01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=xp.float64)
+
+ def derivative(input, axis, output, mode, cval, a, b):
+ sigma = [a, b / 2.0]
+ order = [0] * input.ndim
+ order[axis] = 1
+ return ndimage.gaussian_filter(input, sigma, order, output, mode, cval)
+
+ tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0)
+ tmp2 = ndimage.generic_gradient_magnitude(
+ array, derivative, extra_arguments=(1.0,),
+ extra_keywords={'b': 2.0})
+ assert_array_almost_equal(tmp1, tmp2)
+
+ @make_xp_test_case(ndimage.uniform_filter1d)
+ def test_uniform01(self, xp):
+ array = xp.asarray([2, 4, 6])
+ size = 2
+ output = ndimage.uniform_filter1d(array, size, origin=-1)
+ assert_array_almost_equal(xp.asarray([3, 5, 6]), output)
+
+ @make_xp_test_case(ndimage.uniform_filter1d)
+ def test_uniform01_complex(self, xp):
+ array = xp.asarray([2 + 1j, 4 + 2j, 6 + 3j], dtype=xp.complex128)
+ size = 2
+ output = ndimage.uniform_filter1d(array, size, origin=-1)
+ assert_array_almost_equal(xp.real(output), xp.asarray([3., 5, 6]))
+ assert_array_almost_equal(xp.imag(output), xp.asarray([1.5, 2.5, 3]))
+
+ @make_xp_test_case(ndimage.uniform_filter)
+ def test_uniform02(self, xp):
+ array = xp.asarray([1, 2, 3])
+ filter_shape = [0]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(array, output)
+
+ @make_xp_test_case(ndimage.uniform_filter)
+ def test_uniform03(self, xp):
+ array = xp.asarray([1, 2, 3])
+ filter_shape = [1]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(array, output)
+
+ @make_xp_test_case(ndimage.uniform_filter)
+ def test_uniform04(self, xp):
+ array = xp.asarray([2, 4, 6])
+ filter_shape = [2]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([2, 3, 5]), output)
+
+ @make_xp_test_case(ndimage.uniform_filter)
+ def test_uniform05(self, xp):
+ array = xp.asarray([])
+ filter_shape = [1]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([]), output)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ @make_xp_test_case(ndimage.uniform_filter)
+ def test_uniform06(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ filter_shape = [2, 2]
+ array = xp.asarray([[4, 8, 12],
+ [16, 20, 24]], dtype=dtype_array)
+ output = ndimage.uniform_filter(
+ array, filter_shape, output=dtype_output)
+ assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+ assert output.dtype.type == dtype_output
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @make_xp_test_case(ndimage.uniform_filter)
+ def test_uniform06_complex(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ filter_shape = [2, 2]
+ array = xp.asarray([[4, 8 + 5j, 12],
+ [16, 20, 24]], dtype=dtype_array)
+ output = ndimage.uniform_filter(
+ array, filter_shape, output=dtype_output)
+ assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output.real)
+ assert output.dtype.type == dtype_output
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter01(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([2])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter02(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([3])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter03(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([2])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([3, 2, 2, 1, 1]), output)
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter04(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([3])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([2, 2, 1, 1, 1]), output)
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter05(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ filter_shape = xp.asarray([2, 3])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 2, 1, 1, 1],
+ [5, 3, 3, 1, 1]]), output)
+
+ @uses_output_array
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter05_overlap(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ filter_shape = xp.asarray([2, 3])
+ ndimage.minimum_filter(array, filter_shape, output=array)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 2, 1, 1, 1],
+ [5, 3, 3, 1, 1]]), array)
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter06(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.minimum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 2, 1, 1, 1],
+ [5, 3, 3, 1, 1]]), output)
+ # separable footprint should allow mode sequence
+ output2 = ndimage.minimum_filter(array, footprint=footprint,
+ mode=['reflect', 'reflect'])
+ assert_array_almost_equal(output2, output)
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ @xfail_xp_backends(
+ "cupy", CUPY_VERSION and CUPY_VERSION >= "14",
+ reason="multiple modes work in CuPy 14"
+ )
+ def test_minimum_filter07(self, xp):
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.minimum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]]), output)
+
+ with assert_raises(RuntimeError):
+ ndimage.minimum_filter(array, footprint=footprint,
+ mode=['reflect', 'constant'])
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter08(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.minimum_filter(array, footprint=footprint, origin=-1)
+ assert_array_almost_equal(xp.asarray([[3, 1, 3, 1, 1],
+ [5, 3, 3, 1, 1],
+ [3, 3, 1, 1, 1]]), output)
+
+ @make_xp_test_case(ndimage.minimum_filter)
+ def test_minimum_filter09(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.minimum_filter(array, footprint=footprint,
+ origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1],
+ [5, 3, 3, 1, 1]]), output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter01(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([2])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([1, 2, 3, 4, 5]), output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter02(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([3])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([2, 3, 4, 5, 5]), output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter03(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([2])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter04(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([3])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([3, 5, 5, 5, 4]), output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter05(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ filter_shape = xp.asarray([2, 3])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+ [7, 9, 9, 9, 5],
+ [8, 9, 9, 9, 7]]), output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter06(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.maximum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+ [7, 9, 9, 9, 5],
+ [8, 9, 9, 9, 7]]), output)
+ # separable footprint should allow mode sequence
+ output2 = ndimage.maximum_filter(array, footprint=footprint,
+ mode=['reflect', 'reflect'])
+ assert_array_almost_equal(output2, output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ @xfail_xp_backends(
+ "cupy", CUPY_VERSION and CUPY_VERSION >= "14",
+ reason="multiple modes work in CuPy 14"
+ )
+ def test_maximum_filter07(self, xp):
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.maximum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+ [7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7]]), output)
+ # non-separable footprint should not allow mode sequence
+ with assert_raises(RuntimeError):
+ ndimage.maximum_filter(array, footprint=footprint,
+ mode=['reflect', 'reflect'])
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter08(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.maximum_filter(array, footprint=footprint, origin=-1)
+ assert_array_almost_equal(xp.asarray([[7, 9, 9, 5, 5],
+ [9, 8, 9, 7, 5],
+ [8, 8, 7, 7, 7]]), output)
+
+ @make_xp_test_case(ndimage.maximum_filter)
+ def test_maximum_filter09(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.maximum_filter(array, footprint=footprint,
+ origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7],
+ [8, 8, 8, 7, 7]]), output)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ 'axes', tuple(itertools.combinations(range(-3, 3), 2))
+ )
+ @pytest.mark.parametrize(
+ 'filter_func, kwargs',
+ [
+ make_xp_pytest_param(ndimage.minimum_filter, {}),
+ make_xp_pytest_param(ndimage.maximum_filter, {}),
+ make_xp_pytest_param(ndimage.median_filter, {}),
+ make_xp_pytest_param(ndimage.rank_filter, dict(rank=3)),
+ make_xp_pytest_param(ndimage.percentile_filter, dict(percentile=60)),
+ ]
+ )
+ def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float32)
+ array = xp.reshape(array, (6, 8, 12))
+ # use 2D triangular footprint because it is non-separable
+ footprint = xp.asarray(np.tri(5))
+ axes = np.asarray(axes)
+
+ if len(set(axes % array.ndim)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError):
+ filter_func(array, footprint=footprint, axes=axes, **kwargs)
+ return
+ output = filter_func(array, footprint=footprint, axes=axes, **kwargs)
+
+ missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0]
+
+ footprint_3d = xp.expand_dims(footprint, axis=missing_axis)
+ expected = filter_func(array, footprint=footprint_3d, **kwargs)
+ xp_assert_close(output, expected)
+
+ @make_xp_test_case(
+ ndimage.rank_filter, ndimage.percentile_filter, ndimage.median_filter
+ )
+ def test_rank01(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ output = ndimage.rank_filter(array, 1, size=2)
+ xp_assert_equal(array, output)
+ output = ndimage.percentile_filter(array, 100, size=2)
+ xp_assert_equal(array, output)
+ output = ndimage.median_filter(array, 2)
+ xp_assert_equal(array, output)
+
+ @make_xp_test_case(
+ ndimage.rank_filter, ndimage.percentile_filter, ndimage.median_filter
+ )
+ def test_rank02(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ output = ndimage.rank_filter(array, 1, size=[3])
+ xp_assert_equal(array, output)
+ output = ndimage.percentile_filter(array, 50, size=3)
+ xp_assert_equal(array, output)
+ output = ndimage.median_filter(array, (3,))
+ xp_assert_equal(array, output)
+
+ @make_xp_test_case(
+ ndimage.rank_filter, ndimage.percentile_filter
+ )
+ def test_rank03(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ output = ndimage.rank_filter(array, 1, size=[2])
+ xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+ output = ndimage.percentile_filter(array, 100, size=2)
+ xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+ @make_xp_test_case(
+ ndimage.rank_filter, ndimage.percentile_filter, ndimage.median_filter
+ )
+ def test_rank04(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ expected = xp.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, 1, size=3)
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 50, size=3)
+ xp_assert_equal(expected, output)
+ output = ndimage.median_filter(array, size=3)
+ xp_assert_equal(expected, output)
+
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank05(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ expected = xp.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, -2, size=3)
+ xp_assert_equal(expected, output)
+
+ @make_xp_test_case(ndimage.rank_filter, ndimage.percentile_filter)
+ def test_rank06(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+ expected = [[2, 2, 1, 1, 1],
+ [3, 3, 2, 1, 1],
+ [5, 5, 3, 3, 1]]
+ expected = xp.asarray(expected)
+ output = ndimage.rank_filter(array, 1, size=[2, 3])
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 17, size=(2, 3))
+ xp_assert_equal(expected, output)
+
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8406")
+ @uses_output_array
+ @make_xp_test_case(ndimage.rank_filter, ndimage.percentile_filter)
+ def test_rank06_overlap(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+
+ array_copy = xp.asarray(array, copy=True)
+ expected = [[2, 2, 1, 1, 1],
+ [3, 3, 2, 1, 1],
+ [5, 5, 3, 3, 1]]
+ expected = xp.asarray(expected)
+ ndimage.rank_filter(array, 1, size=[2, 3], output=array)
+ xp_assert_equal(expected, array)
+
+ ndimage.percentile_filter(array_copy, 17, size=(2, 3),
+ output=array_copy)
+ xp_assert_equal(expected, array_copy)
+
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank07(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+ expected = [[3, 5, 5, 5, 4],
+ [5, 5, 7, 5, 4],
+ [6, 8, 8, 7, 5]]
+ expected = xp.asarray(expected)
+ output = ndimage.rank_filter(array, -2, size=[2, 3])
+ xp_assert_equal(expected, output)
+
+ @make_xp_test_case(ndimage.rank_filter, ndimage.percentile_filter)
+ def test_rank08(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+ expected = [[3, 3, 2, 4, 4],
+ [5, 5, 5, 4, 4],
+ [5, 6, 7, 5, 5]]
+ expected = xp.asarray(expected)
+ output = ndimage.percentile_filter(array, 50.0, size=(2, 3))
+ xp_assert_equal(expected, output)
+ output = ndimage.rank_filter(array, 3, size=(2, 3))
+ xp_assert_equal(expected, output)
+ output = ndimage.median_filter(array, size=(2, 3))
+ xp_assert_equal(expected, output)
+
+ @make_xp_test_case(
+ ndimage.rank_filter, ndimage.percentile_filter, ndimage.median_filter
+ )
+ @xfail_xp_backends(
+ "cupy", CUPY_VERSION and CUPY_VERSION >= "14",
+ reason="multiple modes work in CuPy 14"
+ )
+ def test_rank08_1(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+
+ # non-separable: does not allow mode sequence
+ with assert_raises(RuntimeError):
+ ndimage.percentile_filter(array, 50.0, size=(2, 3),
+ mode=['reflect', 'constant'])
+ with assert_raises(RuntimeError):
+ ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2)
+ with assert_raises(RuntimeError):
+ ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.rank_filter, ndimage.percentile_filter)
+ def test_rank09(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[3, 3, 2, 4, 4],
+ [3, 5, 2, 5, 1],
+ [5, 5, 8, 3, 5]]
+ expected = xp.asarray(expected)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint)
+ assert_array_almost_equal(expected, output)
+ output = ndimage.percentile_filter(array, 35, footprint=footprint)
+ assert_array_almost_equal(expected, output)
+
+ @make_xp_test_case(ndimage.rank_filter, ndimage.percentile_filter)
+ def test_rank10(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ expected = [[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]]
+ expected = xp.asarray(expected)
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.rank_filter(array, 0, footprint=footprint)
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 0.0, footprint=footprint)
+ xp_assert_equal(expected, output)
+
+ @make_xp_test_case(ndimage.rank_filter, ndimage.percentile_filter)
+ def test_rank11(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ expected = [[3, 5, 5, 5, 4],
+ [7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7]]
+ expected = xp.asarray(expected)
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.rank_filter(array, -1, footprint=footprint)
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 100.0, footprint=footprint)
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.rank_filter, ndimage.percentile_filter)
+ def test_rank12(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[3, 3, 2, 4, 4],
+ [3, 5, 2, 5, 1],
+ [5, 5, 8, 3, 5]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint)
+ assert_array_almost_equal(expected, output)
+ output = ndimage.percentile_filter(array, 50.0,
+ footprint=footprint)
+ xp_assert_equal(expected, output)
+ output = ndimage.median_filter(array, footprint=footprint)
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank13(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[5, 2, 5, 1, 1],
+ [5, 8, 3, 5, 5],
+ [6, 6, 5, 5, 5]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint,
+ origin=-1)
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank14(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[3, 5, 2, 5, 1],
+ [5, 5, 8, 3, 5],
+ [5, 6, 6, 5, 5]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint,
+ origin=[-1, 0])
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank15(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[2, 3, 1, 4, 1],
+ [5, 3, 7, 1, 1],
+ [5, 5, 3, 3, 3]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 0, footprint=footprint,
+ origin=[-1, 0])
+ xp_assert_equal(expected, output)
+
+ # NumPy-only because test is for list input
+ def test_rank16(self):
+ # test that lists are accepted and interpreted as numpy arrays
+ array = [3, 2, 5, 1, 4]
+ # expected values are: median(3, 2, 5) = 3, median(2, 5, 1) = 2, etc
+ expected = np.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, -2, size=3)
+ xp_assert_equal(expected, output)
+
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank17(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ if not hasattr(array, 'flags'):
+ return
+ array.flags.writeable = False
+ expected = xp.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, -2, size=3)
+ xp_assert_equal(expected, output)
+
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank18(self, xp):
+ # module 'array_api_strict' has no attribute 'float16'
+ tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+ 'uint8', 'uint16', 'uint32', 'uint64']
+ for dtype_str in tested_dtypes:
+ dtype = getattr(xp, dtype_str)
+ x = xp.asarray([3, 2, 5, 1, 4], dtype=dtype)
+ y = ndimage.rank_filter(x, -2, size=3)
+ assert y.dtype == x.dtype
+
+ @make_xp_test_case(ndimage.rank_filter)
+ def test_rank19(self, xp):
+ # module 'array_api_strict' has no attribute 'float16'
+ tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+ 'uint8', 'uint16', 'uint32', 'uint64']
+ for dtype_str in tested_dtypes:
+ dtype = getattr(xp, dtype_str)
+ x = xp.asarray([[3, 2, 5, 1, 4], [3, 2, 5, 1, 4]], dtype=dtype)
+ y = ndimage.rank_filter(x, -2, size=3)
+ assert y.dtype == x.dtype
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="off-by-ones on alt backends")
+ @xfail_xp_backends("cupy", reason="does not support extra_arguments")
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.correlate1d, ndimage.generic_filter1d)
+ def test_generic_filter1d01(self, dtype, xp):
+ weights = xp.asarray([1.1, 2.2, 3.3])
+
+ def _filter_func(input, output, fltr, total):
+ fltr = fltr / total
+ for ii in range(input.shape[0] - 2):
+ output[ii] = input[ii] * fltr[0]
+ output[ii] += input[ii + 1] * fltr[1]
+ output[ii] += input[ii + 2] * fltr[2]
+
+ a = np.arange(12, dtype=dtype).reshape(3, 4)
+ a = xp.asarray(a)
+ dtype = getattr(xp, dtype)
+
+ r1 = ndimage.correlate1d(a, weights / xp.sum(weights), 0, origin=-1)
+ r2 = ndimage.generic_filter1d(
+ a, _filter_func, 3, axis=0, origin=-1,
+ extra_arguments=(weights,),
+ extra_keywords={'total': xp.sum(weights)})
+ assert_array_almost_equal(r1, r2)
+
+ @xfail_xp_backends("cupy", reason="does not support extra_arguments")
+ @make_xp_test_case(ndimage.correlate, ndimage.generic_filter)
+ @pytest.mark.parametrize('dtype', types)
+ def test_generic_filter01(self, dtype, xp):
+ if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+ dtype_str = dtype
+ dtype = getattr(xp, dtype_str)
+
+ filter_ = xp.asarray([[1.0, 2.0], [3.0, 4.0]])
+ footprint = xp.asarray([[1.0, 0.0], [0.0, 1.0]])
+ cf = xp.asarray([1., 4.])
+
+ def _filter_func(buffer, weights, total=1.0):
+ weights = np.asarray(cf) / np.asarray(total)
+ return np.sum(buffer * weights)
+
+ a = np.arange(12, dtype=dtype_str).reshape(3, 4)
+ a = xp.asarray(a)
+ r1 = ndimage.correlate(a, filter_ * footprint)
+ if dtype_str in float_types:
+ r1 /= 5
+ else:
+ r1 //= 5
+ r2 = ndimage.generic_filter(
+ a, _filter_func, footprint=footprint, extra_arguments=(cf,),
+ extra_keywords={'total': xp.sum(cf)})
+ assert_array_almost_equal(r1, r2)
+
+ # generic_filter doesn't allow mode sequence
+ with assert_raises(RuntimeError):
+ r2 = ndimage.generic_filter(
+ a, _filter_func, mode=['reflect', 'reflect'],
+ footprint=footprint, extra_arguments=(cf,),
+ extra_keywords={'total': xp.sum(cf)})
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1, 1, 2]),
+ ('wrap', [3, 1, 2]),
+ ('reflect', [1, 1, 2]),
+ ('mirror', [2, 1, 2]),
+ ('constant', [0, 1, 2])]
+ )
+ @make_xp_test_case(ndimage.correlate1d)
+ def test_extend01(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([1, 0])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1, 1, 1]),
+ ('wrap', [3, 1, 2]),
+ ('reflect', [3, 3, 2]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ @make_xp_test_case(ndimage.correlate1d)
+ def test_extend02(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([1, 0, 0, 0, 0, 0, 0, 0])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [2, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 3, 3]),
+ ('mirror', [2, 3, 2]),
+ ('constant', [2, 3, 0])]
+ )
+ @make_xp_test_case(ndimage.correlate1d)
+ def test_extend03(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 1])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [3, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 1, 1]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ @make_xp_test_case(ndimage.correlate1d)
+ def test_extend04(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+ ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]),
+ ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+ ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]),
+ ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])]
+ )
+ @make_xp_test_case(ndimage.correlate)
+ def test_extend05(self, mode, expected_value, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]])
+ weights = xp.asarray([[1, 0], [0, 0]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+ ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]),
+ ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+ ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]),
+ ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])]
+ )
+ @make_xp_test_case(ndimage.correlate)
+ def test_extend06(self, mode, expected_value, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]])
+ weights = xp.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [3, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 1, 1]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ @make_xp_test_case(ndimage.correlate)
+ def test_extend07(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[3], [3], [3]]),
+ ('wrap', [[2], [3], [1]]),
+ ('reflect', [[2], [1], [1]]),
+ ('mirror', [[1], [2], [3]]),
+ ('constant', [[0], [0], [0]])]
+ )
+ @make_xp_test_case(ndimage.correlate)
+ def test_extend08(self, mode, expected_value, xp):
+ array = xp.asarray([[1], [2], [3]])
+ weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [3, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 1, 1]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ @make_xp_test_case(ndimage.correlate)
+ def test_extend09(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[3], [3], [3]]),
+ ('wrap', [[2], [3], [1]]),
+ ('reflect', [[2], [1], [1]]),
+ ('mirror', [[1], [2], [3]]),
+ ('constant', [[0], [0], [0]])]
+ )
+ @make_xp_test_case(ndimage.correlate)
+ def test_extend10(self, mode, expected_value, xp):
+ array = xp.asarray([[1], [2], [3]])
+ weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+
+@xfail_xp_backends("cupy", reason="TypeError")
+@make_xp_test_case(ndimage.generic_filter)
+def test_ticket_701(xp):
+ # Test generic filter sizes
+ arr = xp.asarray(np.arange(4).reshape(2, 2))
+ def func(x):
+ return np.min(x) # NB: np.min not xp.min for callables
+ res = ndimage.generic_filter(arr, func, size=(1, 1))
+ # The following raises an error unless ticket 701 is fixed
+ res2 = ndimage.generic_filter(arr, func, size=1)
+ xp_assert_equal(res, res2)
+
+
+def test_gh_5430():
+ # At least one of these raises an error unless gh-5430 is
+ # fixed. In py2k an int is implemented using a C long, so
+ # which one fails depends on your system. In py3k there is only
+ # one arbitrary precision integer type, so both should fail.
+ sigma = np.int32(1)
+ out = ndimage._ni_support._normalize_sequence(sigma, 1)
+ assert out == [sigma]
+ sigma = np.int64(1)
+ out = ndimage._ni_support._normalize_sequence(sigma, 1)
+ assert out == [sigma]
+ # This worked before; make sure it still works
+ sigma = 1
+ out = ndimage._ni_support._normalize_sequence(sigma, 1)
+ assert out == [sigma]
+ # This worked before; make sure it still works
+ sigma = [1, 1]
+ out = ndimage._ni_support._normalize_sequence(sigma, 2)
+ assert out == sigma
+ # Also include the OPs original example to make sure we fixed the issue
+ x = np.random.normal(size=(256, 256))
+ perlin = np.zeros_like(x)
+ for i in 2**np.arange(6):
+ perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2
+ # This also fixes gh-4106, show that the OPs example now runs.
+ x = np.int64(21)
+ ndimage._ni_support._normalize_sequence(x, 0)
+
+
+@skip_xp_backends("cupy", reason="tests a private scipy utility")
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+def test_gaussian_kernel1d(xp):
+ radius = 10
+ sigma = 2
+ sigma2 = sigma * sigma
+ x = np.arange(-radius, radius + 1, dtype=np.float64)
+ x = xp.asarray(x)
+ phi_x = xp.exp(-0.5 * x * x / sigma2)
+ phi_x /= xp.sum(phi_x)
+ xp_assert_close(phi_x,
+ xp.asarray(_gaussian_kernel1d(sigma, 0, radius)))
+ xp_assert_close(-phi_x * x / sigma2,
+ xp.asarray(_gaussian_kernel1d(sigma, 1, radius)))
+ xp_assert_close(phi_x * (x * x / sigma2 - 1) / sigma2,
+ xp.asarray(_gaussian_kernel1d(sigma, 2, radius)))
+ xp_assert_close(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2),
+ xp.asarray(_gaussian_kernel1d(sigma, 3, radius)))
+
+
+@make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_filter1d)
+def test_orders_gauss(xp):
+ # Check order inputs to Gaussians
+ arr = xp.zeros((1,))
+ xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=0), xp.asarray([0.]))
+ xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=3), xp.asarray([0.]))
+ assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1)
+ xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0),
+ xp.asarray([0.]))
+ xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3),
+ xp.asarray([0.]))
+ assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1)
+
+
+@xfail_xp_backends("cupy", reason="TypeError")
+@make_xp_test_case(
+ ndimage.generic_filter,
+ ndimage.generic_filter1d,
+ ndimage.percentile_filter,
+)
+def test_valid_origins1(xp):
+ """Regression test for #1311."""
+
+ def func(x):
+ return xp.mean(x)
+
+ data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64)
+ assert_raises(ValueError, ndimage.generic_filter, data, func, size=3,
+ origin=2)
+ assert_raises(ValueError, ndimage.generic_filter1d, data, func,
+ filter_size=3, origin=2)
+ assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3,
+ origin=2)
+
+
+@xfail_xp_backends("cupy", reason="TypeError")
+@pytest.mark.parametrize(
+ "filter_func",
+ [
+ make_xp_pytest_param(ndimage.uniform_filter),
+ make_xp_pytest_param(ndimage.minimum_filter),
+ make_xp_pytest_param(ndimage.maximum_filter),
+ make_xp_pytest_param(ndimage.maximum_filter1d),
+ make_xp_pytest_param(ndimage.median_filter),
+ make_xp_pytest_param(ndimage.minimum_filter1d),
+ ],
+)
+def test_valid_origins2(xp, filter_func):
+ """Regression test for #1311."""
+ data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64)
+
+ # This should work, since for size == 3, the valid range for origin is
+ # -1 to 1.
+ list(filter_func(data, 3, origin=-1))
+ list(filter_func(data, 3, origin=1))
+ # Just check this raises an error instead of silently accepting or
+ # segfaulting.
+ assert_raises(ValueError, filter_func, data, 3, origin=2)
+
+
+@make_xp_test_case(
+ ndimage.correlate1d,
+ ndimage.correlate,
+ ndimage.convolve1d,
+ ndimage.convolve,
+)
+def test_bad_convolve_and_correlate_origins(xp):
+ """Regression test for gh-822."""
+ # Before gh-822 was fixed, these would generate seg. faults or
+ # other crashes on many system.
+ assert_raises(ValueError, ndimage.correlate1d,
+ [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2)
+ assert_raises(ValueError, ndimage.correlate,
+ [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2])
+ assert_raises(ValueError, ndimage.correlate,
+ xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, 1])
+
+ assert_raises(ValueError, ndimage.convolve1d,
+ xp.arange(10), xp.ones(3), origin=-2)
+ assert_raises(ValueError, ndimage.convolve,
+ xp.arange(10), xp.ones(3), origin=[-2])
+ assert_raises(ValueError, ndimage.convolve,
+ xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, -2])
+
+
+@pytest.mark.parametrize(
+ "filter_func,args,kwargs",
+ [
+ make_xp_pytest_param(ndimage.gaussian_filter, [1], {}),
+ make_xp_pytest_param(ndimage.prewitt, [], {}),
+ make_xp_pytest_param(ndimage.sobel, [], {}),
+ make_xp_pytest_param(ndimage.laplace, [], {}),
+ make_xp_pytest_param(ndimage.gaussian_laplace, [1], {}),
+ make_xp_pytest_param(ndimage.maximum_filter, [], {"size": 5}),
+ make_xp_pytest_param(ndimage.minimum_filter, [], {"size": 5}),
+ make_xp_pytest_param(ndimage.gaussian_gradient_magnitude, [1], {}),
+ make_xp_pytest_param(ndimage.uniform_filter, [5], {}),
+ ],
+)
+def test_multiple_modes(xp, filter_func, args, kwargs):
+ # Test that the filters with multiple mode capabilities for different
+ # dimensions give the same result as applying a single mode.
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+ if is_cupy(xp) and filter_func.__name__ in ['prewitt', 'sobel']:
+ pytest.xfail("https://github.com/cupy/cupy/issues/9760")
+
+ mode1 = 'reflect'
+ mode2 = ['reflect', 'reflect']
+
+ xp_assert_equal(filter_func(arr, *args, mode=mode1, **kwargs),
+ filter_func(arr, *args, mode=mode2, **kwargs))
+
+
+@make_xp_test_case(
+ ndimage.gaussian_filter1d, ndimage.gaussian_filter,
+ ndimage.uniform_filter1d, ndimage.uniform_filter,
+ ndimage.maximum_filter1d, ndimage.maximum_filter,
+ ndimage.minimum_filter1d, ndimage.minimum_filter,
+)
+def test_multiple_modes_sequentially(xp):
+ # Test that the filters with multiple mode capabilities for different
+ # dimensions give the same result as applying the filters with
+ # different modes sequentially
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0])
+ expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.gaussian_filter(arr, 1, mode=modes))
+
+ expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0])
+ expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.uniform_filter(arr, 5, mode=modes))
+
+ expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0])
+ expected = ndimage.maximum_filter1d(expected, size=5, axis=1,
+ mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.maximum_filter(arr, size=5, mode=modes))
+
+ expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0])
+ expected = ndimage.minimum_filter1d(expected, size=5, axis=1,
+ mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.minimum_filter(arr, size=5, mode=modes))
+
+
+@make_xp_test_case(ndimage.prewitt)
+@xfail_xp_backends(
+ "cupy", CUPY_VERSION and CUPY_VERSION >= "14",
+ reason="https://github.com/cupy/cupy/issues/9760"
+)
+def test_multiple_modes_prewitt(xp):
+ # Test prewitt filter for multiple extrapolation modes
+
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[1., -3., 2.],
+ [1., -2., 1.],
+ [1., -1., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ xp_assert_equal(expected,
+ ndimage.prewitt(arr, mode=modes))
+
+
+@make_xp_test_case(ndimage.sobel)
+@xfail_xp_backends(
+ "cupy", CUPY_VERSION and CUPY_VERSION >= "14",
+ reason="https://github.com/cupy/cupy/issues/9760"
+)
+def test_multiple_modes_sobel(xp):
+ # Test sobel filter for multiple extrapolation modes
+
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[1., -4., 3.],
+ [2., -3., 1.],
+ [1., -1., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ xp_assert_equal(expected,
+ ndimage.sobel(arr, mode=modes))
+
+
+@make_xp_test_case(ndimage.laplace)
+def test_multiple_modes_laplace(xp):
+ # Test laplace filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[-2., 2., 1.],
+ [-2., -3., 2.],
+ [1., 1., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ xp_assert_equal(expected,
+ ndimage.laplace(arr, mode=modes))
+
+
+@make_xp_test_case(ndimage.gaussian_laplace)
+def test_multiple_modes_gaussian_laplace(xp):
+ # Test gaussian_laplace filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[-0.28438687, 0.01559809, 0.19773499],
+ [-0.36630503, -0.20069774, 0.07483620],
+ [0.15849176, 0.18495566, 0.21934094]])
+
+ modes = ['reflect', 'wrap']
+
+ assert_almost_equal(expected,
+ ndimage.gaussian_laplace(arr, 1, mode=modes))
+
+
+@make_xp_test_case(ndimage.gaussian_gradient_magnitude)
+def test_multiple_modes_gaussian_gradient_magnitude(xp):
+ # Test gaussian_gradient_magnitude filter for multiple
+ # extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[0.04928965, 0.09745625, 0.06405368],
+ [0.23056905, 0.14025305, 0.04550846],
+ [0.19894369, 0.14950060, 0.06796850]])
+
+ modes = ['reflect', 'wrap']
+
+ calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes)
+
+ assert_almost_equal(expected, calculated)
+
+
+@make_xp_test_case(ndimage.uniform_filter)
+def test_multiple_modes_uniform(xp):
+ # Test uniform filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[0.32, 0.40, 0.48],
+ [0.20, 0.28, 0.32],
+ [0.28, 0.32, 0.40]])
+
+ modes = ['reflect', 'wrap']
+
+ assert_almost_equal(expected,
+ ndimage.uniform_filter(arr, 5, mode=modes))
+
+
+def _count_nonzero(arr):
+ # XXX: a simplified count_nonzero replacement; replace once
+ # https://github.com/data-apis/array-api/pull/803/ is in
+
+ # this assumes arr.dtype == xp.bool
+ xp = array_namespace(arr)
+ return xp.sum(xp.astype(arr, xp.int8))
+
+
+@make_xp_test_case(
+ ndimage.gaussian_filter, ndimage.gaussian_filter1d,
+ ndimage.gaussian_laplace, ndimage.gaussian_gradient_magnitude,
+)
+def test_gaussian_truncate(xp):
+ # Test that Gaussian filters can be truncated at different widths.
+ # These tests only check that the result has the expected number
+ # of nonzero elements.
+ arr = np.zeros((100, 100), dtype=np.float64)
+ arr[50, 50] = 1
+ arr = xp.asarray(arr)
+ num_nonzeros_2 = _count_nonzero(ndimage.gaussian_filter(arr, 5, truncate=2) > 0)
+ assert num_nonzeros_2 == 21**2
+
+ num_nonzeros_5 = _count_nonzero(
+ ndimage.gaussian_filter(arr, 5, truncate=5) > 0
+ )
+ assert num_nonzeros_5 == 51**2
+
+ # Test truncate when sigma is a sequence.
+ f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5)
+ fpos = f > 0
+ n0 = _count_nonzero(xp.any(fpos, axis=0))
+ assert n0 == 19
+ n1 = _count_nonzero(xp.any(fpos, axis=1))
+ assert n1 == 5
+
+ # Test gaussian_filter1d.
+ x = np.zeros(51)
+ x[25] = 1
+ x = xp.asarray(x)
+ f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5)
+ n = _count_nonzero(f > 0)
+ assert n == 15
+
+ # Test gaussian_laplace
+ y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5)
+ nonzero_indices = xp.nonzero(y != 0)[0]
+
+ n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+ assert n == 15
+
+ # Test gaussian_gradient_magnitude
+ y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5)
+ nonzero_indices = xp.nonzero(y != 0)[0]
+ n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+ assert n == 15
+
+
+@xfail_xp_backends("cupy", reason="cupy/cupy#8402")
+@make_xp_test_case(ndimage.gaussian_filter1d, ndimage.gaussian_filter)
+def test_gaussian_radius(xp):
+ # Test that Gaussian filters with radius argument produce the same
+ # results as the filters with corresponding truncate argument.
+ # radius = int(truncate * sigma + 0.5)
+ # Test gaussian_filter1d
+ x = np.zeros(7)
+ x[3] = 1
+ x = xp.asarray(x)
+ f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5)
+ f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3)
+ xp_assert_equal(f1, f2)
+
+ # Test gaussian_filter when sigma is a number.
+ a = np.zeros((9, 9))
+ a[4, 4] = 1
+ a = xp.asarray(a)
+ f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5)
+ f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2)
+ xp_assert_equal(f1, f2)
+
+ # Test gaussian_filter when sigma is a sequence.
+ a = np.zeros((50, 50))
+ a[25, 25] = 1
+ a = xp.asarray(a)
+ f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5)
+ f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9])
+ xp_assert_equal(f1, f2)
+
+
+@xfail_xp_backends("cupy", reason="cupy/cupy#8402")
+@make_xp_test_case(ndimage.gaussian_filter1d)
+def test_gaussian_radius_invalid(xp):
+ # radius must be a nonnegative integer
+ with assert_raises(ValueError):
+ ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=-1)
+ with assert_raises(ValueError):
+ ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=1.1)
+
+
+@uses_output_array
+class TestThreading:
+ def check_func_thread(self, n, fun, args, out):
+ from threading import Thread
+ thrds = [Thread(target=fun, args=args, kwargs={'output': out[x, ...]})
+ for x in range(n)]
+ [t.start() for t in thrds]
+ [t.join() for t in thrds]
+
+ def check_func_serial(self, n, fun, args, out):
+ for i in range(n):
+ fun(*args, output=out[i, ...])
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.correlate1d)
+ def test_correlate1d(self, xp):
+ d = np.random.randn(5000)
+ os = np.empty((4, d.size))
+ ot = np.empty_like(os)
+ d = xp.asarray(d)
+ os = xp.asarray(os)
+ ot = xp.asarray(ot)
+ k = xp.arange(5)
+ self.check_func_serial(4, ndimage.correlate1d, (d, k), os)
+ self.check_func_thread(4, ndimage.correlate1d, (d, k), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.correlate)
+ def test_correlate(self, xp):
+ d = xp.asarray(np.random.randn(500, 500))
+ k = xp.asarray(np.random.randn(10, 10))
+ os = xp.empty([4] + list(d.shape))
+ ot = xp.empty_like(os)
+ self.check_func_serial(4, ndimage.correlate, (d, k), os)
+ self.check_func_thread(4, ndimage.correlate, (d, k), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.median_filter)
+ def test_median_filter(self, xp):
+ d = xp.asarray(np.random.randn(500, 500))
+ os = xp.empty([4] + list(d.shape))
+ ot = xp.empty_like(os)
+ self.check_func_serial(4, ndimage.median_filter, (d, 3), os)
+ self.check_func_thread(4, ndimage.median_filter, (d, 3), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.uniform_filter1d)
+ def test_uniform_filter1d(self, xp):
+ d = np.random.randn(5000)
+ os = np.empty((4, d.size))
+ ot = np.empty_like(os)
+ d = xp.asarray(d)
+ os = xp.asarray(os)
+ ot = xp.asarray(ot)
+ self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os)
+ self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.maximum_filter, ndimage.minimum_filter)
+ def test_minmax_filter(self, xp):
+ d = xp.asarray(np.random.randn(500, 500))
+ os = xp.empty([4] + list(d.shape))
+ ot = xp.empty_like(os)
+ self.check_func_serial(4, ndimage.maximum_filter, (d, 3), os)
+ self.check_func_thread(4, ndimage.maximum_filter, (d, 3), ot)
+ xp_assert_equal(os, ot)
+ self.check_func_serial(4, ndimage.minimum_filter, (d, 3), os)
+ self.check_func_thread(4, ndimage.minimum_filter, (d, 3), ot)
+ xp_assert_equal(os, ot)
+
+@make_xp_test_case(ndimage.maximum_filter1d, ndimage.minimum_filter1d)
+def test_minmaximum_filter1d(xp):
+ # Regression gh-3898
+ in_ = xp.arange(10)
+ out = ndimage.minimum_filter1d(in_, 1)
+ xp_assert_equal(in_, out)
+ out = ndimage.maximum_filter1d(in_, 1)
+ xp_assert_equal(in_, out)
+ # Test reflect
+ out = ndimage.minimum_filter1d(in_, 5, mode='reflect')
+ xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='reflect')
+ xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+ # Test constant
+ out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1)
+ xp_assert_equal(xp.asarray([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10)
+ xp_assert_equal(xp.asarray([10, 10, 4, 5, 6, 7, 8, 9, 10, 10]), out)
+ # Test nearest
+ out = ndimage.minimum_filter1d(in_, 5, mode='nearest')
+ xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='nearest')
+ xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+ # Test wrap
+ out = ndimage.minimum_filter1d(in_, 5, mode='wrap')
+ xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 0, 0]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='wrap')
+ xp_assert_equal(xp.asarray([9, 9, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+
+
+@xfail_xp_backends("cupy", reason="cupy/cupy#8401")
+@make_xp_test_case(ndimage.uniform_filter1d)
+def test_uniform_filter1d_roundoff_errors(xp):
+ # gh-6930
+ in_ = np.repeat([0, 1, 0], [9, 9, 9])
+ in_ = xp.asarray(in_)
+
+ for filter_size in range(3, 10):
+ out = ndimage.uniform_filter1d(in_, filter_size)
+ xp_assert_equal(xp.sum(out), xp.asarray(10 - filter_size), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum_filter)
+def test_footprint_all_zeros(xp):
+ # regression test for gh-6876: footprint of all zeros segfaults
+ arr = xp.asarray(np.random.randint(0, 100, (100, 100)))
+ kernel = xp.asarray(np.zeros((3, 3), dtype=bool))
+ with assert_raises(ValueError):
+ ndimage.maximum_filter(arr, footprint=kernel)
+
+
+@xfail_xp_backends("cupy", reason="does not raise")
+@skip_xp_backends("array_api_strict", reason="no float16")
+@skip_xp_backends("dask.array", reason="no float16")
+@make_xp_test_case(ndimage.gaussian_filter)
+def test_gaussian_filter_float16(xp):
+ # gh-8207
+ data = xp.asarray([1], dtype=xp.float16)
+ sigma = 1.0
+ with assert_raises(RuntimeError):
+ ndimage.gaussian_filter(data, sigma)
+
+
+@xfail_xp_backends("cupy", reason="does not raise")
+@make_xp_test_case(ndimage.rank_filter)
+def test_rank_filter_noninteger_rank(xp):
+ # regression test for issue 9388: ValueError for
+ # non integer rank when performing rank_filter
+ arr = xp.asarray(np.random.random((10, 20, 30)))
+ footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+ assert_raises(TypeError, ndimage.rank_filter, arr, 0.5,
+ footprint=footprint)
+
+
+@make_xp_test_case(ndimage.rank_filter)
+def test_size_footprint_both_set(xp):
+ # test for input validation, expect user warning when
+ # size and footprint is set
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ "ignoring size because footprint is set", UserWarning)
+ arr = xp.asarray(np.random.random((10, 20, 30)))
+ footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+ ndimage.rank_filter(
+ arr, 5, size=2, footprint=footprint
+ )
+
+
+# NumPy-only because 'byteorder is numpy-specific'
+def test_byte_order_median():
+ """Regression test for #413: median_filter does not handle bytes orders."""
+ a = np.arange(9, dtype='1 makes sense too
+ (3,
+ np.array([0.25266576, 0.30958242, 0.27894721, 0.27894721, 0.27894721, 0.30445588,
+ 0.31442572, 0.30445588, 0.18015438, 0.14831921, 0.18015438, 0.25754605,
+ 0.32910465, 0.25754605, 0.17736568, 0.17736568, 0.09089549, 0.22183391,
+ 0.25266576, 0.30958242]),
+ ),
+ (15,
+ np.array([0.27894721, 0.25266576, 0.25266576, 0.25266576, 0.27894721, 0.27894721,
+ 0.27894721, 0.27894721, 0.25754605, 0.25754605, 0.22183391, 0.22183391,
+ 0.25266576, 0.25266576, 0.22183391, 0.22183391, 0.25266576, 0.25266576,
+ 0.25754605, 0.25754605]),
+ ),
+])
+def test_gh_22250(filter_size, exp):
+ rng = np.random.default_rng(42)
+ image = np.zeros((20,))
+ noisy_image = image + 0.4 * rng.random(image.shape)
+ result = ndimage.median_filter(noisy_image, size=filter_size, mode='wrap')
+ assert_allclose(result, exp)
+
+
+def test_gh_22333():
+ x = np.array([272, 58, 67, 163, 463, 608, 87, 108, 1378])
+ expected = [58, 67, 87, 108, 163, 108, 108, 108, 87]
+ actual = ndimage.median_filter(x, size=9, mode='constant')
+ assert_array_equal(actual, expected)
+
+
+@pytest.mark.filterwarnings("ignore:The given NumPy array is not writable:UserWarning")
+@make_xp_test_case(ndimage.vectorized_filter)
+class TestVectorizedFilter:
+ @pytest.mark.parametrize("axes, size",
+ [(None, (3, 4, 5)), ((0, 2), (3, 4)), ((-1,), (5,))])
+ @pytest.mark.parametrize("origin", [-1, 0, 1])
+ @pytest.mark.parametrize("mode",
+ ['reflect', 'nearest', 'mirror', 'wrap', 'constant'])
+ @pytest.mark.parametrize("use_output", [False, True])
+ def test_against_generic_filter(self, axes, size, origin, mode, use_output, xp):
+ rng = np.random.default_rng(435982456983456987356)
+
+ if use_output and (is_dask(xp) or is_jax(xp)):
+ pytest.skip("Requires mutable arrays.")
+
+ input = rng.random(size=(11, 12, 13))
+ input_copy = input.copy() # check that it is not modified
+ output = xp.zeros(input.shape) if use_output else None
+
+ kwargs = dict(axes=axes, size=size, origin=origin, mode=mode)
+ ref = ndimage.generic_filter(input, np.mean, **kwargs)
+ kwargs['output'] = output
+ res = ndimage.vectorized_filter(xp.asarray(input.tolist()),
+ xp.mean, **kwargs)
+ xp_assert_close(res, xp.asarray(ref.tolist()), atol=1e-15)
+ if use_output:
+ xp_assert_equal(output, res)
+
+ if not (is_array_api_strict(xp) or is_dask(xp)):
+ # currently requires support for [..., mask] indexing
+ kwargs.pop('size')
+ kwargs.pop('output')
+ kwargs['footprint'] = rng.random(size=size or input.shape) > 0.5
+ ref = ndimage.generic_filter(input, np.mean, **kwargs)
+ kwargs['footprint'] = xp.asarray(kwargs['footprint'])
+ kwargs['output'] = output
+ res = ndimage.vectorized_filter(xp.asarray(input.tolist()),
+ xp.mean, **kwargs)
+ xp_assert_close(res, xp.asarray(ref.tolist()), atol=1e-15)
+ if use_output:
+ xp_assert_equal(output, res)
+
+ xp_assert_equal(xp.asarray(input), xp.asarray(input_copy))
+
+ @pytest.mark.parametrize("dtype",
+ ["uint8", "uint16", "uint32", "uint64",
+ "int8", "int16", "int32", "int64",
+ "float32", "float64", "complex64", "complex128"])
+ @pytest.mark.parametrize("batch_memory", [1, 16*3, np.inf])
+ @pytest.mark.parametrize("use_footprint", [False, True])
+ def test_dtype_batch_memory(self, dtype, batch_memory, use_footprint, xp):
+ rng = np.random.default_rng(435982456983456987356)
+ w = 3
+
+ if is_jax(xp) and not (batch_memory == 1):
+ pytest.skip("Requires mutable array.")
+ if is_torch(xp) and dtype in {'uint16', 'uint32', 'uint64'}:
+ pytest.skip("Needs uint support.")
+
+ dtype = getattr(xp, dtype)
+
+ if use_footprint:
+ if (is_dask(xp) or is_array_api_strict(xp)):
+ pytest.skip("Requires [..., mask] indexing.")
+ footprint = xp.asarray([True, False, True])
+ kwargs = dict(footprint=footprint, batch_memory=batch_memory)
+ else:
+ footprint = xp.asarray([True, True, True])
+ kwargs = dict(size=w, batch_memory=batch_memory)
+
+ # The intent here is to exercise all the code paths involved in `batch_memory`
+ # and `output` handling. To test the limited-memory case, `batch_memory=16*3`
+ # is chosen to be just large enough for a *single* window of `complex128` to
+ # fit, and `n` is large enough that a whole sliding window view of `uint8`s
+ # *won't* fit.
+ n = 16*3 + 1
+ input = rng.integers(0, 42, size=(n,))
+ input = input + input*1j if xp.isdtype(dtype, 'complex floating') else input
+ input_padded = xp.asarray(np.pad(input, [(1, 1)], mode='symmetric'),
+ dtype=dtype)
+ input = xp.asarray(input, dtype=dtype)
+
+ ref = [xp.sum(input_padded[i: i + w][footprint]) for i in range(n)]
+ sum_dtype = xp.sum(input_padded).dtype
+
+ message = "`batch_memory` is insufficient for minimum chunk size."
+ context = (pytest.raises(ValueError, match=message)
+ if batch_memory == 1 else contextlib.nullcontext())
+ with context:
+ res = ndimage.vectorized_filter(input, xp.sum, **kwargs)
+ xp_assert_close(res, xp.astype(xp.stack(ref), sum_dtype))
+ assert res.dtype == sum_dtype
+
+ output = xp.empty_like(input)
+ res = ndimage.vectorized_filter(
+ input,
+ lambda x, *args, **kw: xp.astype(
+ xp.sum(x, *args, **kw), x.dtype, copy=False
+ ),
+ output=output,
+ **kwargs
+ )
+ xp_assert_close(res, xp.astype(xp.stack(ref), dtype))
+ assert res.dtype == dtype
+
+ def test_mode_valid(self, xp):
+ rng = np.random.default_rng(435982456983456987356)
+ input = rng.random(size=(10, 11))
+ input_xp = xp.asarray(input)
+ input_xp_copy = xp_copy(input_xp) # check that it is not modified
+ size = (3, 5)
+
+ res = ndimage.vectorized_filter(input_xp, xp.mean, size=size, mode='valid')
+
+ view = np.lib.stride_tricks.sliding_window_view(input, size)
+ ref = np.mean(view, axis=(-2, -1))
+
+ xp_assert_close(res, xp.asarray(ref))
+ assert res.shape == tuple(input.shape - np.asarray(size) + 1)
+ xp_assert_equal(input_xp, input_xp_copy)
+
+ def test_input_validation(self, xp):
+ input = xp.ones((10, 10))
+ function = xp.mean
+ size = 2
+ footprint = xp.ones((2, 2))
+
+ message = "`function` must be a callable."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, "eggplant", size=size)
+
+ message = "Either `size` or `footprint` must be provided."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function)
+
+ message = "Either `size` or `footprint` may be provided, not both."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, footprint=footprint)
+
+ message = "All elements of `size` must be positive integers."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(1, -1))
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=0)
+
+ message = "The length of `axes` may not exceed "
+ axes = (0, 1, 2)
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(1, 2), axes=axes)
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, footprint=xp.ones((2, 2)),
+ axes=axes)
+
+ message = "`axes` must be compatible with the dimensionality..."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(1,))
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(2,), axes=(0,1))
+
+ message = "All elements of `origin` must be integers"
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, origin=(1, 1.5))
+
+ message = "`origin` must be an integer or tuple of integers with length..."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, origin=(1, 2, 3))
+
+ message = "`mode` must be one of..."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, mode='coconut')
+
+ message = "`mode='valid'` is incompatible with use of `origin`."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size,
+ mode='valid', origin=1)
+
+ message = "Use of `cval` is compatible only with `mode='constant'`."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, mode='valid', cval=1)
+
+ other_messages = "|Unsupported|The array_api_strict|new|Value 'a duck'"
+ message = "`cval` must include only numbers." + other_messages
+ with pytest.raises((ValueError, TypeError), match=message):
+ ndimage.vectorized_filter(input, function, size=size,
+ mode='constant', cval='a duck')
+
+ message = "`batch_memory` must be positive number." + other_messages
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, batch_memory=0)
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, batch_memory=(1, 2))
+ with pytest.raises((ValueError, TypeError), match=message):
+ ndimage.vectorized_filter(input, function, size=size, batch_memory="a duck")
+
+ @pytest.mark.parametrize('shape', [(0,), (1, 0), (0, 1, 0)])
+ def test_zero_size(self, shape, xp):
+ input = xp.empty(shape)
+ res = ndimage.vectorized_filter(input, xp.mean, size=1)
+ xp_assert_equal(res, input)
+
+ @pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning")
+ def test_edge_cases(self, xp):
+ rng = np.random.default_rng(4835982345234982)
+ function = xp.mean
+
+ # 0-D input
+ input = xp.asarray(1.)
+ res = ndimage.vectorized_filter(input, function, size=())
+ xp_assert_equal(res, xp.asarray(function(input, axis=())))
+
+ if not (is_array_api_strict(xp) or is_dask(xp)):
+ res = ndimage.vectorized_filter(input, function, footprint=True)
+ xp_assert_equal(res, xp.asarray(function(input[True], axis=())))
+
+ res = ndimage.vectorized_filter(input, function, footprint=False)
+ xp_assert_equal(res, xp.asarray(function(input[False], axis=())))
+
+ # 1x1 window
+ input = xp.asarray(rng.random((5, 5)))
+ res = ndimage.vectorized_filter(input, function, size=1)
+ xp_assert_equal(res, input)
+
+ # window is bigger than input shouldn't be a problem
+ res = ndimage.vectorized_filter(input, function, size=21)
+ ref = ndimage.vectorized_filter(input, function, size=21)
+ xp_assert_close(res, ref)
+
+ def test_gh23046_feature(self, xp):
+ # The intent of gh-23046 was to always allow `size` to be a scalar.
+ rng = np.random.default_rng(45982734597824)
+ img = xp.asarray(rng.random((5, 5)))
+
+ ref = ndimage.vectorized_filter(img, xp.mean, size=2)
+ res = ndimage.vectorized_filter(img, xp.mean, size=2, axes=(0, 1))
+ xp_assert_close(res, ref)
+
+ ref = ndimage.vectorized_filter(img, xp.mean, size=(2,), axes=(0,))
+ res = ndimage.vectorized_filter(img, xp.mean, size=2, axes=0)
+ xp_assert_close(res, ref)
+
+ def test_gh23046_fix(self, xp):
+ # While investigating the feasibility of gh-23046, I noticed a bug when the
+ # length of an `axes` tuple equals the dimensionality of the image.
+ rng = np.random.default_rng(45982734597824)
+ img = xp.asarray(rng.random((5, 5)))
+ size = (2, 3)
+ ref = ndimage.vectorized_filter(img.T, xp.mean, size=size).T
+ res = ndimage.vectorized_filter(img, xp.mean, size=size, axes=(1, 0))
+ xp_assert_close(res, ref)
+
+ ref = ndimage.vectorized_filter(img, xp.mean, size=size, mode='constant')
+ res = ndimage.vectorized_filter(img, xp.mean, size=size[::-1], axes=(1, 0),
+ mode='constant')
+ xp_assert_close(res, ref)
+
+
+@given(x=npst.arrays(dtype=np.float64,
+ shape=st.integers(min_value=1, max_value=1000)),
+ size=st.integers(min_value=1, max_value=50),
+ mode=st.sampled_from(["constant", "mirror", "wrap", "reflect",
+ "nearest"]),
+ )
+def test_gh_22586_crash_property(x, size, mode):
+ # property-based test for median_filter resilience to hard crashing
+ ndimage.median_filter(x, size=size, mode=mode)
+
+
+@pytest.mark.parametrize('samples, mode, size, expected', [
+ ([1, 2], "reflect", 5, [2, 1]),
+ ([2], "reflect", 5, [2]), # original failure from gh-23075
+ ([2], "nearest", 5, [2]),
+ ([2], "wrap", 5, [2]),
+ ([2], "mirror", 5, [2]),
+ ([2], "constant", 5, [0]),
+ ([2], "reflect", 1, [2]),
+ ([2], "nearest", 1, [2]),
+ ([2], "wrap", 1, [2]),
+ ([2], "mirror", 1, [2]),
+ ([2], "constant", 1, [2]),
+ ([2], "reflect", 100, [2]),
+ ([2], "nearest", 100, [2]),
+ ([2], "wrap", 100, [2]),
+ ([2], "mirror", 100, [2]),
+ ([2], "constant", 100, [0]),
+])
+def test_gh_23075(samples, mode, size, expected):
+ # results verified against SciPy 1.14.1, before the median_filter
+ # overhaul
+ sample_array = np.asarray(samples, dtype=np.float32)
+ expected = np.asarray(expected, dtype=np.float32)
+ filtered_samples = ndimage.median_filter(sample_array, size=size, mode=mode)
+ xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True)
+
+
+@pytest.mark.parametrize('samples, size, cval, expected', [
+ ([2], 5, 17.7, [17.7]),
+ ([2], 1, 0, [2]),
+ ([2], 100, 1.4, [1.4]),
+ ([9], 137, -7807.7, [-7807.7]),
+])
+def test_gh_23075_constant(samples, size, cval, expected):
+ # results verified against SciPy 1.14.1, before the median_filter
+ # overhaul
+ sample_array = np.asarray(samples, dtype=np.single)
+ expected = np.asarray(expected, dtype=np.single)
+ filtered_samples = ndimage.median_filter(sample_array,
+ size=size,
+ mode="constant",
+ cval=cval)
+ xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True)
+
+
+def test_median_filter_lim2():
+ sample_array = np.ones(8)
+ expected = np.ones(8)
+ filtered_samples = ndimage.median_filter(sample_array, size=19, mode="reflect")
+ xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..97c737d3f62b4b84b01a884ea9fa43b6a75eb932
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py
@@ -0,0 +1,197 @@
+import math
+import numpy as np
+
+from scipy._lib._array_api import (
+ xp_assert_equal,
+ assert_array_almost_equal,
+ assert_almost_equal,
+ is_cupy,
+ make_xp_test_case,
+ make_xp_pytest_param,
+)
+
+import pytest
+
+from scipy import ndimage
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestNdimageFourier:
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+ @make_xp_test_case(ndimage.fourier_gaussian)
+ def test_fourier_gaussian_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.rfft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+ @make_xp_test_case(ndimage.fourier_gaussian)
+ def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.fft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+ @make_xp_test_case(ndimage.fourier_uniform)
+ def test_fourier_uniform_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.rfft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+ @make_xp_test_case(ndimage.fourier_uniform)
+ def test_fourier_uniform_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.fft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)])
+ @make_xp_test_case(ndimage.fourier_shift)
+ def test_fourier_shift_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+ expected = xp.asarray(expected)
+
+ a = fft.rfft(expected, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)])
+ @make_xp_test_case(ndimage.fourier_shift)
+ def test_fourier_shift_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+ expected = xp.asarray(expected)
+
+ a = fft.fft(expected, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_shift(a, [1, 1], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec)
+ assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)])
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.rfft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)])
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.fft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_unimplemented_ndim(self, xp):
+ # arrays with ndim > 3 raise NotImplementedError
+ x = xp.ones((4, 6, 8, 10), dtype=xp.complex128)
+ with pytest.raises(NotImplementedError):
+ ndimage.fourier_ellipsoid(x, 3)
+
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_1d_complex(self, xp):
+ # expected result of 1d ellipsoid is the same as for fourier_uniform
+ for shape in [(32, ), (31, )]:
+ for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]):
+ x = xp.ones(shape, dtype=type_)
+ a = ndimage.fourier_ellipsoid(x, 5, -1, 0)
+ b = ndimage.fourier_uniform(x, 5, -1, 0)
+ assert_array_almost_equal(a, b, decimal=dec)
+
+ @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)])
+ @pytest.mark.parametrize('dtype', ["float32", "float64",
+ "complex64", "complex128"])
+ @pytest.mark.parametrize('test_func',
+ [make_xp_pytest_param(ndimage.fourier_ellipsoid),
+ make_xp_pytest_param(ndimage.fourier_gaussian),
+ make_xp_pytest_param(ndimage.fourier_uniform)])
+ def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
+ if (
+ is_cupy(xp)
+ and test_func.__name__ == "fourier_ellipsoid"
+ and math.prod(shape) == 0
+ ):
+ pytest.xfail("CuPy's fourier_ellipsoid does not accept size==0 arrays")
+ dtype = getattr(xp, dtype)
+ a = xp.ones(shape, dtype=dtype)
+ b = test_func(a, 3)
+ xp_assert_equal(a, b)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..8030ab71d436f7b64ab074c392b4b16cbba66068
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py
@@ -0,0 +1,1529 @@
+import sys
+import warnings
+
+import numpy as np
+from scipy._lib._array_api import (
+ _asarray, assert_array_almost_equal,
+ is_jax, np_compat,
+ xp_assert_equal, xp_assert_close,
+ make_xp_test_case,
+)
+
+import pytest
+from pytest import raises as assert_raises
+import scipy.ndimage as ndimage
+
+from . import types
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+# lazy_xp_modules = [ndimage]
+
+
+eps = 1e-12
+
+ndimage_to_numpy_mode = {
+ 'mirror': 'reflect',
+ 'reflect': 'symmetric',
+ 'grid-mirror': 'symmetric',
+ 'grid-wrap': 'wrap',
+ 'nearest': 'edge',
+ 'grid-constant': 'constant',
+}
+
+# mypy: disable-error-code=attr-defined
+
+class TestBoundaries:
+
+ @make_xp_test_case(ndimage.geometric_transform)
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]),
+ ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]),
+ ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]),
+ ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]),
+ ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]),
+ ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]),
+ ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])]
+ )
+ def test_boundaries(self, mode, expected_value, xp):
+ def shift(x):
+ return (x[0] + 0.5,)
+
+ data = xp.asarray([1, 2, 3, 4.])
+ xp_assert_equal(
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+ output_shape=(7,), order=1),
+ xp.asarray(expected_value))
+
+ @make_xp_test_case(ndimage.geometric_transform)
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1, 1, 2, 3]),
+ ('wrap', [3, 1, 2, 3]),
+ ('grid-wrap', [4, 1, 2, 3]),
+ ('mirror', [2, 1, 2, 3]),
+ ('reflect', [1, 1, 2, 3]),
+ ('constant', [-1, 1, 2, 3]),
+ ('grid-constant', [-1, 1, 2, 3])]
+ )
+ def test_boundaries2(self, mode, expected_value, xp):
+ def shift(x):
+ return (x[0] - 0.9,)
+
+ data = xp.asarray([1, 2, 3, 4])
+ xp_assert_equal(
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+ output_shape=(4,)),
+ xp.asarray(expected_value))
+
+ @make_xp_test_case(ndimage.map_coordinates)
+ @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror',
+ 'grid-wrap', 'grid-constant',
+ 'nearest'])
+ @pytest.mark.parametrize('order', range(6))
+ def test_boundary_spline_accuracy(self, mode, order, xp):
+ """Tests based on examples from gh-2640"""
+ if (is_jax(xp) and
+ (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest']
+ or order > 1)
+ ):
+ pytest.xfail("Jax does not support grid- modes or order > 1")
+
+ np_data = np.arange(-6, 7, dtype=np.float64)
+ data = xp.asarray(np_data)
+ x = xp.asarray(np.linspace(-8, 15, num=1000))
+ y = ndimage.map_coordinates(data, x[xp.newaxis, ...], order=order, mode=mode)
+
+ # compute expected value using explicit padding via np.pad
+ npad = 32
+ pad_mode = ndimage_to_numpy_mode.get(mode)
+ padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode))
+ coords = xp.asarray(npad + x)[xp.newaxis, ...]
+ expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode)
+
+ atol = 1e-5 if mode == 'grid-constant' else 1e-12
+ xp_assert_close(y, expected, rtol=1e-7, atol=atol)
+
+
+@make_xp_test_case(ndimage.spline_filter)
+@pytest.mark.parametrize('order', range(2, 6))
+@pytest.mark.parametrize('dtype', types)
+class TestSpline:
+
+ def test_spline01(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.spline_filter(data, order=order)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ def test_spline02(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([1], dtype=dtype)
+ out = ndimage.spline_filter(data, order=order)
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output=dtype is numpy-specific')
+ def test_spline03(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.spline_filter(data, order, output=dtype)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ def test_spline04(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([4], dtype=dtype)
+ out = ndimage.spline_filter(data, order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+ def test_spline05(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([4, 4], dtype=dtype)
+ out = ndimage.spline_filter(data, order=order)
+ expected = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]])
+ assert_array_almost_equal(out, expected)
+
+
+@make_xp_test_case(ndimage.geometric_transform)
+@pytest.mark.parametrize('order', range(0, 6))
+class TestGeometricTransform:
+
+ def test_geometric_transform01(self, order, xp):
+ data = xp.asarray([1])
+
+ def mapping(x):
+ return x
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+ def test_geometric_transform02(self, order, xp):
+ data = xp.ones([4])
+
+ def mapping(x):
+ return x
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+ def test_geometric_transform03(self, order, xp):
+ data = xp.ones([4])
+
+ def mapping(x):
+ return (x[0] - 1,)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype))
+
+ def test_geometric_transform04(self, order, xp):
+ data = xp.asarray([4, 1, 3, 2])
+
+ def mapping(x):
+ return (x[0] - 1,)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype))
+
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_geometric_transform05(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+ expected = xp.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+
+ def mapping(x):
+ return (x[0], x[1] - 1)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform06(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0], x[1] - 1)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ expected = xp.asarray([[0, 4, 1, 3],
+ [0, 7, 6, 8],
+ [0, 3, 5, 3]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform07(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0] - 1, x[1])
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [4, 1, 3, 2],
+ [7, 6, 8, 5]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform08(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0] - 1, x[1] - 1)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform10(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0] - 1, x[1] - 1)
+
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ out = ndimage.geometric_transform(filtered, mapping, data.shape,
+ order=order, prefilter=False)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform13(self, order, xp):
+ data = xp.ones([2], dtype=xp.float64)
+
+ def mapping(x):
+ return (x[0] // 2,)
+
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+ def test_geometric_transform14(self, order, xp):
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+
+ def mapping(x):
+ return (2 * x[0],)
+
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype))
+
+ def test_geometric_transform15(self, order, xp):
+ data = xp.asarray([1, 2, 3, 4])
+
+ def mapping(x):
+ return (x[0] / 2,)
+
+ out = ndimage.geometric_transform(data, mapping, [8], order=order)
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
+
+ def test_geometric_transform16(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9.0, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0], x[1] * 2)
+
+ out = ndimage.geometric_transform(data, mapping, (3, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
+
+ def test_geometric_transform17(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] * 2, x[1])
+
+ out = ndimage.geometric_transform(data, mapping, (1, 4),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
+
+ def test_geometric_transform18(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] * 2, x[1] * 2)
+
+ out = ndimage.geometric_transform(data, mapping, (1, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
+
+ def test_geometric_transform19(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0], x[1] / 2)
+
+ out = ndimage.geometric_transform(data, mapping, (3, 8),
+ order=order)
+ assert_array_almost_equal(out[..., ::2], data)
+
+ def test_geometric_transform20(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] / 2, x[1])
+
+ out = ndimage.geometric_transform(data, mapping, (6, 4),
+ order=order)
+ assert_array_almost_equal(out[::2, ...], data)
+
+ def test_geometric_transform21(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] / 2, x[1] / 2)
+
+ out = ndimage.geometric_transform(data, mapping, (6, 8),
+ order=order)
+ assert_array_almost_equal(out[::2, ::2], data)
+
+ def test_geometric_transform22(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data, dtype=xp.float64)
+
+ def mapping1(x):
+ return (x[0] / 2, x[1] / 2)
+
+ def mapping2(x):
+ return (x[0] * 2, x[1] * 2)
+
+ out = ndimage.geometric_transform(data, mapping1,
+ (6, 8), order=order)
+ out = ndimage.geometric_transform(out, mapping2,
+ (3, 4), order=order)
+ assert_array_almost_equal(out, data)
+
+ def test_geometric_transform23(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (1, x[0] * 2)
+
+ out = ndimage.geometric_transform(data, mapping, (2,), order=order)
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
+
+ def test_geometric_transform24(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x, a, b):
+ return (a, x[0] * b)
+
+ out = ndimage.geometric_transform(
+ data, mapping, (2,), order=order, extra_arguments=(1,),
+ extra_keywords={'b': 2})
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
+
+
+@make_xp_test_case(ndimage.geometric_transform)
+class TestGeometricTransformExtra:
+
+ def test_geometric_transform_grid_constant_order1(self, xp):
+
+ # verify interpolation outside the original bounds
+ x = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=xp.float64)
+
+ def mapping(x):
+ return (x[0] - 0.5), (x[1] - 0.5)
+
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
+ [1.25, 3.00, 4.00]])
+ assert_array_almost_equal(
+ ndimage.geometric_transform(x, mapping, mode='grid-constant',
+ order=1),
+ expected_result,
+ )
+
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+ 'mirror', 'reflect'])
+ @pytest.mark.parametrize('order', range(6))
+ def test_geometric_transform_vs_padded(self, order, mode, xp):
+
+ def mapping(x):
+ return (x[0] - 0.4), (x[1] + 2.3)
+
+ # Manually pad and then extract center after the transform to get the
+ # expected result.
+ x = np.arange(144, dtype=float).reshape(12, 12)
+ npad = 24
+ pad_mode = ndimage_to_numpy_mode.get(mode)
+ x_padded = np.pad(x, npad, mode=pad_mode)
+
+ x = xp.asarray(x)
+ x_padded = xp.asarray(x_padded)
+
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
+ expected_result = ndimage.geometric_transform(
+ x_padded, mapping, mode=mode, order=order)[center_slice]
+
+ xp_assert_close(
+ ndimage.geometric_transform(x, mapping, mode=mode,
+ order=order),
+ expected_result,
+ rtol=1e-7,
+ )
+
+ @skip_xp_backends(np_only=True, reason='endianness is numpy-specific')
+ def test_geometric_transform_endianness_with_output_parameter(self, xp):
+ # geometric transform given output ndarray or dtype with
+ # non-native endianness. see issue #4127
+ data = np.asarray([1])
+
+ def mapping(x):
+ return x
+
+ for out in [data.dtype, data.dtype.newbyteorder(),
+ np.empty_like(data),
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
+ returned = ndimage.geometric_transform(data, mapping, data.shape,
+ output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, [1])
+
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+ def test_geometric_transform_with_string_output(self, xp):
+ data = xp.asarray([1])
+
+ def mapping(x):
+ return x
+
+ out = ndimage.geometric_transform(data, mapping, output='f')
+ assert out.dtype is np.dtype('f')
+ assert_array_almost_equal(out, [1])
+
+
+@make_xp_test_case(ndimage.map_coordinates)
+class TestMapCoordinates:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+ def test_map_coordinates01(self, order, dtype, xp):
+ if is_jax(xp) and order > 1:
+ pytest.xfail("jax map_coordinates requires order <= 1")
+
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]])
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data = data - 1j * data
+ expected = expected - 1j * expected
+
+ idx = np.indices(data.shape)
+ idx -= 1
+ idx = xp.asarray(idx)
+
+ out = ndimage.map_coordinates(data, idx, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_map_coordinates02(self, order, xp):
+ if is_jax(xp):
+ if order > 1:
+ pytest.xfail("jax map_coordinates requires order <= 1")
+ if order == 1:
+ pytest.xfail("output differs. jax bug?")
+
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ idx = np.indices(data.shape, np.float64)
+ idx -= 0.5
+ idx = xp.asarray(idx)
+
+ out1 = ndimage.shift(data, 0.5, order=order)
+ out2 = ndimage.map_coordinates(data, idx, order=order)
+ assert_array_almost_equal(out1, out2)
+
+ @skip_xp_backends("jax.numpy", reason="`order` is required in jax")
+ def test_map_coordinates03(self, xp):
+ data = _asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]], order='F', xp=xp)
+ idx = np.indices(data.shape) - 1
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data, idx)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]])
+ assert_array_almost_equal(out, expected)
+ assert_array_almost_equal(out, ndimage.shift(data, (1, 1)))
+
+ idx = np.indices(data[::2, ...].shape) - 1
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data[::2, ...], idx)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3]]))
+ assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1)))
+
+ idx = np.indices(data[:, ::2].shape) - 1
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data[:, ::2], idx)
+ assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]]))
+ assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1)))
+
+ @skip_xp_backends(np_only=True)
+ def test_map_coordinates_endianness_with_output_parameter(self, xp):
+ # output parameter given as array or dtype with either endianness
+ # see issue #4127
+ # NB: NumPy-only
+
+ data = np.asarray([[1, 2], [7, 6]])
+ expected = np.asarray([[0, 0], [0, 1]])
+ idx = np.indices(data.shape)
+ idx -= 1
+ for out in [
+ data.dtype,
+ data.dtype.newbyteorder(),
+ np.empty_like(expected),
+ np.empty_like(expected).astype(expected.dtype.newbyteorder())
+ ]:
+ returned = ndimage.map_coordinates(data, idx, output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, expected)
+
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+ def test_map_coordinates_with_string_output(self, xp):
+ data = xp.asarray([[1]])
+ idx = np.indices(data.shape)
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data, idx, output='f')
+ assert out.dtype is np.dtype('f')
+ assert_array_almost_equal(out, xp.asarray([[1]]))
+
+ @pytest.mark.skip_xp_backends(cpu_only=True)
+ @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8,
+ reason='do not run on 32 bit or windows '
+ '(no sparse memory)')
+ def test_map_coordinates_large_data(self, xp):
+ # check crash on large data
+ try:
+ n = 30000
+ # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n))
+ a = np.empty(n**2, dtype=np.float32).reshape(n, n)
+ # fill the part we might read
+ a[n - 3:, n - 3:] = 0
+ ndimage.map_coordinates(
+ xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1
+ )
+ except MemoryError as e:
+ raise pytest.skip('Not enough memory available') from e
+
+ @xfail_xp_backends("cupy", reason="CuPy map_coordinates has the same aliasing bug")
+ @pytest.mark.parametrize('n_channels', range(1, 4))
+ @pytest.mark.parametrize('order', range(2, 6))
+ def test_map_coordinates_reflect_multichannel(self, n_channels, order, xp):
+ # Regression test for gh-24550: reflect mode spline prefilter had an
+ # aliasing bug that caused accuracy loss for multi-channel images.
+ if is_jax(xp) and order > 1:
+ pytest.xfail("jax map_coordinates requires order <= 1")
+
+ rng = np.random.default_rng(4567)
+ image = xp.asarray(rng.random((8, 8)), dtype=xp.float64)
+ coords = xp.asarray(rng.random((2, 5, 5)) * 7)
+
+ single = ndimage.map_coordinates(image, coords, order=order,
+ mode='reflect')
+
+ color = xp.stack([image] * n_channels, axis=-1)
+ channels = np.broadcast_to(np.arange(n_channels),
+ (1, 5, 5, n_channels))
+ coords_color = np.broadcast_to(
+ np.asarray(coords)[..., np.newaxis], (2, 5, 5, n_channels))
+ coords_color = xp.asarray(np.concatenate(
+ (coords_color, channels), axis=0))
+
+ multi = ndimage.map_coordinates(color, coords_color, order=order,
+ mode='reflect')
+ expected = xp.stack([single] * n_channels, axis=-1)
+ xp_assert_close(multi, expected)
+
+
+@make_xp_test_case(ndimage.affine_transform)
+class TestAffineTransform:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform01(self, order, xp):
+ data = xp.asarray([1])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform02(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform03(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform04(self, order, xp):
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_affine_transform05(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+ expected = xp.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [0, -1], order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform06(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [0, -1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+ [0, 7, 6, 8],
+ [0, 3, 5, 3]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform07(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [-1, 0], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [4, 1, 3, 2],
+ [7, 6, 8, 5]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform08(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [-1, -1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform09(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]),
+ [-1, -1], order=order,
+ prefilter=False)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform10(self, order, xp):
+ data = xp.ones([2], dtype=xp.float64)
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform11(self, order, xp):
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform12(self, order, xp):
+ data = xp.asarray([1, 2, 3, 4])
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order)
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform13(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9.0, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform14(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform15(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform16(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0,
+ (3, 8), order=order)
+ assert_array_almost_equal(out[..., ::2], data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform17(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0,
+ (6, 4), order=order)
+ assert_array_almost_equal(out[::2, ...], data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform18(self, order, xp):
+ data = xp.asarray([[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]])
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+ (6, 8), order=order)
+ assert_array_almost_equal(out[::2, ::2], data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform19(self, order, xp):
+ data = xp.asarray([[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]], dtype=xp.float64)
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+ (6, 8), order=order)
+ out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0,
+ (3, 4), order=order)
+ assert_array_almost_equal(out, data)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform20(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 3]))
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform21(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 9]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform22(self, order, xp):
+ # shift and offset interaction; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 2]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform23(self, order, xp):
+ # shift and offset interaction; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,),
+ order=order)
+ assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform24(self, order, xp):
+ # consistency between diagonal and non-diagonal case; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ 'The behavior of affine_transform with a 1-D array .* has changed',
+ UserWarning)
+ out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order)
+ out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order)
+ assert_array_almost_equal(out1, out2)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform25(self, order, xp):
+ # consistency between diagonal and non-diagonal case; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ 'The behavior of affine_transform with a 1-D array .* '
+ 'has changed', UserWarning)
+ out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order)
+ out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order)
+ assert_array_almost_equal(out1, out2)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform26(self, order, xp):
+ # test homogeneous coordinates
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ tform_original = xp.eye(2)
+ offset_original = -xp.ones((2, 1))
+
+ tform_h1 = xp.concat((tform_original, offset_original), axis=1) # hstack
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0) # vstack
+
+ offs = [float(x) for x in xp.reshape(offset_original, (-1,))]
+
+ out1 = ndimage.affine_transform(filtered, tform_original,
+ offs,
+ order=order, prefilter=False)
+ out2 = ndimage.affine_transform(filtered, tform_h1, order=order,
+ prefilter=False)
+ out3 = ndimage.affine_transform(filtered, tform_h2, order=order,
+ prefilter=False)
+ for out in [out1, out2, out3]:
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @xfail_xp_backends("cupy", reason="does not raise")
+ def test_affine_transform27(self, xp):
+ # test valid homogeneous transformation matrix
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ tform_h1 = xp.concat((xp.eye(2), -xp.ones((2, 1))) , axis=1) # vstack
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0) # hstack
+
+ assert_raises(ValueError, ndimage.affine_transform, data, tform_h2)
+
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+ def test_affine_transform_1d_endianness_with_output_parameter(self, xp):
+ # 1d affine transform given output ndarray or dtype with
+ # either endianness. see issue #7388
+ data = xp.ones((2, 2))
+ for out in [xp.empty_like(data),
+ xp.empty_like(data).astype(data.dtype.newbyteorder()),
+ data.dtype, data.dtype.newbyteorder()]:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ 'The behavior of affine_transform with a 1-D array '
+ '.* has changed', UserWarning)
+ matrix = xp.asarray([1, 1])
+ returned = ndimage.affine_transform(data, matrix, output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]]))
+
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+ def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp):
+ # affine transform given output ndarray or dtype with either endianness
+ # see issue #4127
+ # NB: byteorder is numpy-specific
+ data = np.asarray([1])
+ for out in [data.dtype, data.dtype.newbyteorder(),
+ np.empty_like(data),
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
+ returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, np.asarray([1]))
+
+ @skip_xp_backends(np_only=True,
+ reason='`out` of a different size is numpy-specific'
+ )
+ def test_affine_transform_output_shape(self, xp):
+ # don't require output_shape when out of a different size is given
+ data = xp.arange(8, dtype=xp.float64)
+ out = xp.ones((16,))
+
+ ndimage.affine_transform(data, xp.asarray([[1]]), output=out)
+ assert_array_almost_equal(out[:8], data)
+
+ # mismatched output shape raises an error
+ with pytest.raises(RuntimeError):
+ ndimage.affine_transform(
+ data, [[1]], output=out, output_shape=(12,))
+
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+ def test_affine_transform_with_string_output(self, xp):
+ data = xp.asarray([1])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f')
+ assert out.dtype is np.dtype('f')
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @pytest.mark.parametrize('shift',
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp):
+ # For mode 'grid-wrap', integer shifts should match np.roll
+ x = np.asarray([[0, 1],
+ [2, 3]])
+ affine = np.zeros((2, 3))
+ affine[:2, :2] = np.eye(2)
+ affine[:, 2] = np.asarray(shift)
+
+ expected = np.roll(x, shift, axis=(0, 1))
+
+ x = xp.asarray(x)
+ affine = xp.asarray(affine)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(
+ ndimage.affine_transform(x, affine, mode='grid-wrap', order=order),
+ expected
+ )
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform_shift_reflect(self, order, xp):
+ # shift by x.shape results in reflection
+ x = np.asarray([[0, 1, 2],
+ [3, 4, 5]])
+ expected = x[::-1, ::-1].copy() # strides >0 for torch
+ x = xp.asarray(x)
+ expected = xp.asarray(expected)
+
+ affine = np.zeros([2, 3])
+ affine[:2, :2] = np.eye(2)
+ affine[:, 2] = np.asarray(x.shape)
+ affine = xp.asarray(affine)
+
+ assert_array_almost_equal(
+ ndimage.affine_transform(x, affine, mode='reflect', order=order),
+ expected,
+ )
+
+
+@make_xp_test_case(ndimage.shift)
+class TestShift:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift01(self, order, xp):
+ data = xp.asarray([1])
+ out = ndimage.shift(data, [1], order=order)
+ assert_array_almost_equal(out, xp.asarray([0]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift02(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.shift(data, [1], order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift03(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.shift(data, -1, order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift04(self, order, xp):
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.shift(data, 1, order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_shift05(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+ expected = xp.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ out = ndimage.shift(data, [0, 1], order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('mode', ['constant', 'grid-constant'])
+ @pytest.mark.parametrize('dtype', ['float64', 'complex128'])
+ def test_shift_with_nonzero_cval(self, order, mode, dtype, xp):
+ data = np.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+
+ expected = np.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+
+ if np_compat.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ cval = 5.0
+ expected[:, 0] = cval # specific to shift of [0, 1] used below
+
+ data = xp.asarray(data)
+ expected = xp.asarray(expected)
+ out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift06(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.shift(data, [0, 1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+ [0, 7, 6, 8],
+ [0, 3, 5, 3]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift07(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.shift(data, [1, 0], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [4, 1, 3, 2],
+ [7, 6, 8, 5]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift08(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.shift(data, [1, 1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift09(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('shift',
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift_grid_wrap(self, shift, order, xp):
+ # For mode 'grid-wrap', integer shifts should match np.roll
+ x = np.asarray([[0, 1],
+ [2, 3]])
+ expected = np.roll(x, shift, axis=(0,1))
+
+ x = xp.asarray(x)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(
+ ndimage.shift(x, shift, mode='grid-wrap', order=order),
+ expected
+ )
+
+ @pytest.mark.parametrize('shift',
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift_grid_constant1(self, shift, order, xp):
+ # For integer shifts, 'constant' and 'grid-constant' should be equal
+ x = xp.reshape(xp.arange(20), (5, 4))
+ assert_array_almost_equal(
+ ndimage.shift(x, shift, mode='grid-constant', order=order),
+ ndimage.shift(x, shift, mode='constant', order=order),
+ )
+
+ def test_shift_grid_constant_order1(self, xp):
+ x = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=xp.float64)
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
+ [1.25, 3.00, 4.00]])
+ assert_array_almost_equal(
+ ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1),
+ expected_result,
+ )
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift_reflect(self, order, xp):
+ # shift by x.shape results in reflection
+ x = np.asarray([[0, 1, 2],
+ [3, 4, 5]])
+ expected = x[::-1, ::-1].copy() # strides > 0 for torch
+
+ x = xp.asarray(x)
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(
+ ndimage.shift(x, x.shape, mode='reflect', order=order),
+ expected,
+ )
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('prefilter', [False, True])
+ def test_shift_nearest_boundary(self, order, prefilter, xp):
+ # verify that shifting at least order // 2 beyond the end of the array
+ # gives a value equal to the edge value.
+ x = xp.arange(16)
+ kwargs = dict(mode='nearest', order=order, prefilter=prefilter)
+ assert_array_almost_equal(
+ ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0],
+ )
+ assert_array_almost_equal(
+ ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1],
+ )
+
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+ 'mirror', 'reflect'])
+ @pytest.mark.parametrize('order', range(6))
+ def test_shift_vs_padded(self, order, mode, xp):
+ x_np = np.arange(144, dtype=float).reshape(12, 12)
+ shift = (0.4, -2.3)
+
+ # manually pad and then extract center to get expected result
+ npad = 32
+ pad_mode = ndimage_to_numpy_mode.get(mode)
+ x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode))
+ x = xp.asarray(x_np)
+
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
+ expected_result = ndimage.shift(
+ x_padded, shift, mode=mode, order=order)[center_slice]
+
+ xp_assert_close(
+ ndimage.shift(x, shift, mode=mode, order=order),
+ expected_result,
+ rtol=1e-7,
+ )
+
+
+@make_xp_test_case(ndimage.zoom)
+class TestZoom:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_zoom1(self, order, xp):
+ for z in [2, [2, 2]]:
+ arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5))
+ arr = ndimage.zoom(arr, z, order=order)
+ assert arr.shape == (10, 10)
+ assert xp.all(arr[-1, :] != 0)
+ assert xp.all(arr[-1, :] >= (20 - eps))
+ assert xp.all(arr[0, :] <= (5 + eps))
+ assert xp.all(arr >= (0 - eps))
+ assert xp.all(arr <= (24 + eps))
+
+ def test_zoom2(self, xp):
+ arr = xp.reshape(xp.arange(12), (3, 4))
+ out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5)
+ xp_assert_equal(out, arr)
+
+ def test_zoom3(self, xp):
+ arr = xp.asarray([[1, 2]])
+ out1 = ndimage.zoom(arr, (2, 1))
+ out2 = ndimage.zoom(arr, (1, 2))
+
+ assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]]))
+ assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_zoom_affine01(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ 'The behavior of affine_transform with a 1-D array .* '
+ 'has changed', UserWarning)
+ out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0,
+ (6, 8), order=order)
+ assert_array_almost_equal(out[::2, ::2], data)
+
+ def test_zoom_infinity(self, xp):
+ # Ticket #1419 regression test
+ dim = 8
+ ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest')
+
+ def test_zoom_zoomfactor_one(self, xp):
+ # Ticket #1122 regression test
+ arr = xp.zeros((1, 5, 5))
+ zoom = (1.0, 2.0, 2.0)
+
+ out = ndimage.zoom(arr, zoom, cval=7)
+ ref = xp.zeros((1, 10, 10))
+ assert_array_almost_equal(out, ref)
+
+ def test_zoom_output_shape_roundoff(self, xp):
+ arr = xp.zeros((3, 11, 25))
+ zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25)
+ out = ndimage.zoom(arr, zoom)
+ assert out.shape == (4, 15, 29)
+
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+ @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect',
+ 'mirror', 'grid-wrap', 'grid-mirror',
+ 'grid-constant'])
+ def test_zoom_by_int_order0(self, zoom, mode, xp):
+ # order 0 zoom should be the same as replication via np.kron
+ # Note: This is not True for general x shapes when grid_mode is False,
+ # but works here for all modes because the size ratio happens to
+ # always be an integer when x.shape = (2, 2).
+ x_np = np.asarray([[0, 1],
+ [2, 3]], dtype=np.float64)
+ expected = np.kron(x_np, np.ones(zoom))
+
+ x = xp.asarray(x_np)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(
+ ndimage.zoom(x, zoom, order=0, mode=mode),
+ expected
+ )
+
+ @pytest.mark.parametrize('shape', [(2, 3), (4, 4)])
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+ @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror',
+ 'grid-wrap', 'grid-constant'])
+ def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp):
+ # When grid_mode is True, order 0 zoom should be the same as
+ # replication via np.kron. The only exceptions to this are the
+ # non-grid modes 'constant' and 'wrap'.
+ x_np = np.arange(np.prod(shape), dtype=float).reshape(shape)
+
+ x = xp.asarray(x_np)
+ assert_array_almost_equal(
+ ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True),
+ xp.asarray(np.kron(x_np, np.ones(zoom)))
+ )
+
+ @pytest.mark.parametrize('mode', ['constant', 'wrap'])
+ def test_zoom_grid_mode_warnings(self, mode, xp):
+ # Warn on use of non-grid modes when grid_mode is True
+ x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3))
+ with pytest.warns(UserWarning,
+ match="It is recommended to use mode"):
+ ndimage.zoom(x, 2, mode=mode, grid_mode=True),
+
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ def test_zoom_output_shape(self, xp):
+ """Ticket #643"""
+ x = xp.reshape(xp.arange(12), (3, 4))
+ ndimage.zoom(x, 2, output=xp.zeros((6, 8)))
+
+ def test_zoom_0d_array(self, xp):
+ # Ticket #21670 regression test
+ a = xp.arange(10.)
+ factor = 2
+ actual = ndimage.zoom(a, np.array(factor))
+ expected = ndimage.zoom(a, factor)
+ xp_assert_close(actual, expected)
+
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
+ def test_zoom_1_gh20999(self, xp):
+ # gh-20999 reported that zoom with `zoom=1` (or sequence of ones)
+ # introduced noise. Check that this is resolved.
+ x = xp.eye(3)
+ xp_assert_equal(ndimage.zoom(x, 1), x)
+ xp_assert_equal(ndimage.zoom(x, (1, 1)), x)
+
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
+ @skip_xp_backends("jax.numpy", reason="read-only backend")
+ @xfail_xp_backends("dask.array", reason="numpy round-trip")
+ def test_zoom_1_gh20999_output(self, xp):
+ x = xp.eye(3)
+ output = xp.zeros_like(x)
+ ndimage.zoom(x, 1, output=output)
+ xp_assert_equal(output, x)
+
+
+@make_xp_test_case(ndimage.rotate)
+class TestRotate:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate01(self, order, xp):
+ data = xp.asarray([[0, 0, 0, 0],
+ [0, 1, 1, 0],
+ [0, 0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 0, order=order)
+ assert_array_almost_equal(out, data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate02(self, order, xp):
+ data = xp.asarray([[0, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 0, 0]], dtype=xp.float64)
+ expected = xp.asarray([[0, 0, 0],
+ [0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_rotate03(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]], dtype=dtype)
+ expected = xp.asarray([[0, 0, 0],
+ [0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ out = ndimage.rotate(data, 90, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate04(self, order, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]], dtype=xp.float64)
+ expected = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, reshape=False, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate05(self, order, xp):
+ data = np.empty((4, 3, 3))
+ for i in range(3):
+ data[:, :, i] = np.asarray([[0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=np.float64)
+ data = xp.asarray(data)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 1, 1, 0],
+ [0, 0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, order=order)
+ for i in range(3):
+ assert_array_almost_equal(out[:, :, i], expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate06(self, order, xp):
+ data = np.empty((3, 4, 3))
+ for i in range(3):
+ data[:, :, i] = np.asarray([[0, 0, 0, 0],
+ [0, 1, 1, 0],
+ [0, 0, 0, 0]], dtype=np.float64)
+ data = xp.asarray(data)
+ expected = xp.asarray([[0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, order=order)
+ for i in range(3):
+ assert_array_almost_equal(out[:, :, i], expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate07(self, order, xp):
+ data = xp.asarray([[[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+ data = xp.permute_dims(data, (2, 1, 0))
+ expected = xp.asarray([[[0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0],
+ [0, 0, 0]]] * 2, dtype=xp.float64)
+ expected = xp.permute_dims(expected, (2, 1, 0))
+ out = ndimage.rotate(data, 90, axes=(0, 1), order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate08(self, order, xp):
+ data = xp.asarray([[[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+ data = xp.permute_dims(data, (2, 1, 0)) # == np.transpose
+ expected = xp.asarray([[[0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+ expected = xp.permute_dims(expected, (2, 1, 0))
+ out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order)
+ assert_array_almost_equal(out, expected)
+
+ def test_rotate09(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]] * 2, dtype=xp.float64)
+ with assert_raises(ValueError):
+ ndimage.rotate(data, 90, axes=(0, data.ndim))
+
+ def test_rotate10(self, xp):
+ data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3))
+
+ # The output of ndimage.rotate before refactoring
+ expected = xp.asarray([[[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [6.54914793, 7.54914793, 8.54914793],
+ [10.84520162, 11.84520162, 12.84520162],
+ [0.0, 0.0, 0.0]],
+ [[6.19286575, 7.19286575, 8.19286575],
+ [13.4730712, 14.4730712, 15.4730712],
+ [21.0, 22.0, 23.0],
+ [28.5269288, 29.5269288, 30.5269288],
+ [35.80713425, 36.80713425, 37.80713425]],
+ [[0.0, 0.0, 0.0],
+ [31.15479838, 32.15479838, 33.15479838],
+ [35.45085207, 36.45085207, 37.45085207],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]]], dtype=xp.float64)
+
+ out = ndimage.rotate(data, angle=12, reshape=False)
+ #assert_array_almost_equal(out, expected)
+ xp_assert_close(out, expected, rtol=1e-6, atol=2e-6)
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8400")
+ def test_rotate_exact_180(self, xp):
+ a = xp.asarray(np.tile(np.arange(5), (5, 1)))
+ b = ndimage.rotate(ndimage.rotate(a, 180), -180)
+ xp_assert_equal(a, b)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..989e9bc11da7f0c5e7b63a8f5aa76755a953066f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py
@@ -0,0 +1,1697 @@
+import os
+import os.path
+import warnings
+
+import numpy as np
+
+from scipy._lib._array_api import (
+ is_torch,
+ xp_assert_equal,
+ xp_assert_close,
+ assert_array_almost_equal,
+ assert_almost_equal,
+ make_xp_test_case,
+)
+
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.ndimage as ndimage
+
+from . import types
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+# mypy: disable-error-code=attr-defined
+
+@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+class Test_measurements_stats:
+ """ndimage._measurements._stats() is a utility used by other functions.
+
+ Since internal ndimage/_measurements.py code is NumPy-only,
+ so is this this test class.
+ """
+ def test_a(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 1, 1]
+ index = [0, 1]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums = ndimage._measurements._stats(
+ x, labels=labels, index=index)
+
+ dtype_arg = {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+ def test_b(self, xp):
+ # Same data as test_a, but different labels. The label 9 exceeds the
+ # length of 'labels', so this test will follow a different code path.
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 9, 9]
+ index = [0, 9]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums = ndimage._measurements._stats(
+ x, labels=labels, index=index)
+
+ dtype_arg = {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+ def test_a_centered(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 1, 1]
+ index = [0, 1]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums, centers = ndimage._measurements._stats(
+ x, labels=labels, index=index, centered=True)
+
+ dtype_arg = {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+ def test_b_centered(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 9, 9]
+ index = [0, 9]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums, centers = ndimage._measurements._stats(
+ x, labels=labels, index=index, centered=True)
+
+ dtype_arg = {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+ def test_nonint_labels(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0.0, 0.0, 9.0, 9.0]
+ index = [0.0, 9.0]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums, centers = ndimage._measurements._stats(
+ x, labels=labels, index=index, centered=True)
+
+ dtype_arg = {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+
+@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
+@pytest.mark.uses_xp_capabilities(False, reason="private")
+class Test_measurements_select:
+ """ndimage._measurements._select() is a utility used by other functions."""
+
+ def test_basic(self, xp):
+ x = [0, 1, 6, 2]
+ cases = [
+ ([0, 0, 1, 1], [0, 1]), # "Small" integer labels
+ ([0, 0, 9, 9], [0, 9]), # A label larger than len(labels)
+ ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]), # Non-integer labels
+ ]
+ for labels, index in cases:
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index)
+ assert len(result) == 0
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_max=True)
+ assert len(result) == 1
+ xp_assert_equal(result[0], [1, 6])
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_min=True)
+ assert len(result) == 1
+ xp_assert_equal(result[0], [0, 2])
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_min=True,
+ find_min_positions=True)
+ assert len(result) == 2
+ xp_assert_equal(result[0], [0, 2])
+ xp_assert_equal(result[1], [0, 3])
+ assert result[1].dtype.kind == 'i'
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_max=True,
+ find_max_positions=True)
+ assert len(result) == 2
+ xp_assert_equal(result[0], [1, 6])
+ xp_assert_equal(result[1], [1, 2])
+ assert result[1].dtype.kind == 'i'
+
+
+@make_xp_test_case(ndimage.label)
+def test_label01(xp):
+ data = xp.ones(())
+ out, n = ndimage.label(data)
+ assert out == 1
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label02(xp):
+ data = xp.zeros(())
+ out, n = ndimage.label(data)
+ assert out == 0
+ assert n == 0
+
+
+@make_xp_test_case(ndimage.label)
+def test_label03(xp):
+ data = xp.ones([1])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([1]))
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label04(xp):
+ data = xp.zeros([1])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([0]))
+ assert n == 0
+
+
+@make_xp_test_case(ndimage.label)
+def test_label05(xp):
+ data = xp.ones([5])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label06(xp):
+ data = xp.asarray([1, 0, 1, 1, 0, 1])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3]))
+ assert n == 3
+
+
+@make_xp_test_case(ndimage.label)
+def test_label07(xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0]])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray(
+ [[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0]]))
+ assert n == 0
+
+
+@make_xp_test_case(ndimage.label)
+def test_label08(xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]]))
+ assert n == 4
+
+
+@make_xp_test_case(ndimage.label)
+def test_label09(xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]])
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ out, n = ndimage.label(data, struct)
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [2, 2, 0, 0, 0, 0],
+ [2, 2, 0, 0, 0, 0],
+ [0, 0, 0, 3, 3, 0]]))
+ assert n == 3
+
+
+@make_xp_test_case(ndimage.label)
+def test_label10(xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0]])
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ out, n = ndimage.label(data, struct)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0]]))
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label11(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
+ out, n = ndimage.label(data)
+ expected = [[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+ assert n == 4
+
+
+@skip_xp_backends(np_only=True, reason='inplace output is numpy-specific')
+@make_xp_test_case(ndimage.label)
+def test_label11_inplace(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
+ n = ndimage.label(data, output=data)
+ expected = [[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(data, expected)
+ assert n == 4
+
+
+@make_xp_test_case(ndimage.label)
+def test_label12(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 1],
+ [0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1],
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
+ out, n = ndimage.label(data)
+ expected = [[0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 1],
+ [0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1],
+ [0, 0, 0, 1, 1, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label13(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
+ dtype=dtype)
+ out, n = ndimage.label(data)
+ expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+ assert n == 1
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output=dtype is numpy-specific')
+@make_xp_test_case(ndimage.label)
+def test_label_output_typed(xp):
+ data = xp.ones([5])
+ for t in types:
+ dtype = getattr(xp, t)
+ output = xp.zeros([5], dtype=dtype)
+ n = ndimage.label(data, output=output)
+ assert_array_almost_equal(output,
+ xp.ones(output.shape, dtype=output.dtype))
+ assert n == 1
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output=dtype is numpy-specific')
+@make_xp_test_case(ndimage.label)
+def test_label_output_dtype(xp):
+ data = xp.ones([5])
+ for t in types:
+ dtype = getattr(xp, t)
+ output, n = ndimage.label(data, output=dtype)
+ assert_array_almost_equal(output,
+ xp.ones(output.shape, dtype=output.dtype))
+ assert output.dtype == t
+
+
+@skip_xp_backends(np_only=True, reason="in-place output is numpy-specific")
+@make_xp_test_case(ndimage.label)
+def test_label_output_wrong_size(xp):
+ data = xp.ones([5])
+ for t in types:
+ dtype = getattr(xp, t)
+ output = xp.zeros([10], dtype=dtype)
+ assert_raises(ValueError, ndimage.label, data, output=output)
+
+
+@make_xp_test_case(ndimage.label)
+def test_label_structuring_elements(xp):
+ data = np.loadtxt(os.path.join(os.path.dirname(
+ __file__), "data", "label_inputs.txt"))
+ strels = np.loadtxt(os.path.join(
+ os.path.dirname(__file__), "data", "label_strels.txt"))
+ results = np.loadtxt(os.path.join(
+ os.path.dirname(__file__), "data", "label_results.txt"))
+ data = data.reshape((-1, 7, 7))
+ strels = strels.reshape((-1, 3, 3))
+ results = results.reshape((-1, 7, 7))
+
+ data = xp.asarray(data)
+ strels = xp.asarray(strels)
+ results = xp.asarray(results)
+ r = 0
+ for i in range(data.shape[0]):
+ d = data[i, :, :]
+ for j in range(strels.shape[0]):
+ s = strels[j, :, :]
+ xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False)
+ r += 1
+
+
+@make_xp_test_case(ndimage.label, ndimage.find_objects)
+def test_ticket_742(xp):
+ def SE(img, thresh=.7, size=4):
+ mask = img > thresh
+ rank = len(mask.shape)
+ struct = ndimage.generate_binary_structure(rank, rank)
+ struct = xp.asarray(struct)
+ la, co = ndimage.label(mask,
+ struct)
+ _ = ndimage.find_objects(la)
+
+ if np.dtype(np.intp) != np.dtype('i'):
+ shape = (3, 1240, 1240)
+ a = np.random.rand(np.prod(shape)).reshape(shape)
+ a = xp.asarray(a)
+ # shouldn't crash
+ SE(a)
+
+
+@make_xp_test_case(ndimage.label)
+def test_gh_issue_3025(xp):
+ """Github issue #3025 - improper merging of labels"""
+ d = np.zeros((60, 320))
+ d[:, :257] = 1
+ d[:, 260:] = 1
+ d[36, 257] = 1
+ d[35, 258] = 1
+ d[35, 259] = 1
+ d = xp.asarray(d)
+ assert ndimage.label(d, xp.ones((3, 3)))[1] == 1
+
+
+@make_xp_test_case(ndimage.label, ndimage.find_objects)
+class TestFindObjects:
+ def test_label_default_dtype(self, xp):
+ test_array = np.random.rand(10, 10)
+ test_array = xp.asarray(test_array)
+ label, no_features = ndimage.label(test_array > 0.5)
+ assert label.dtype in (xp.int32, xp.int64)
+ # Shouldn't raise an exception
+ ndimage.find_objects(label)
+
+
+ def test_find_objects01(self, xp):
+ data = xp.ones([], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == [()]
+
+
+ def test_find_objects02(self, xp):
+ data = xp.zeros([], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == []
+
+
+ def test_find_objects03(self, xp):
+ data = xp.ones([1], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None),)]
+
+
+ def test_find_objects04(self, xp):
+ data = xp.zeros([1], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == []
+
+
+ def test_find_objects05(self, xp):
+ data = xp.ones([5], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 5, None),)]
+
+
+ def test_find_objects06(self, xp):
+ data = xp.asarray([1, 0, 2, 2, 0, 3])
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None),),
+ (slice(2, 4, None),),
+ (slice(5, 6, None),)]
+
+
+ def test_find_objects07(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0]])
+ out = ndimage.find_objects(data)
+ assert out == []
+
+
+ def test_find_objects08(self, xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]])
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
+ (slice(1, 3, None), slice(2, 5, None)),
+ (slice(3, 5, None), slice(0, 2, None)),
+ (slice(5, 6, None), slice(3, 5, None))]
+
+
+ def test_find_objects09(self, xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]])
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
+ (slice(1, 3, None), slice(2, 5, None)),
+ None,
+ (slice(5, 6, None), slice(3, 5, None))]
+
+
+@make_xp_test_case(ndimage.value_indices)
+def test_value_indices01(xp):
+ "Test dictionary keys and entries"
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]])
+ vi = ndimage.value_indices(data, ignore_value=0)
+ true_keys = [1, 2, 4]
+ assert list(vi.keys()) == true_keys
+
+ truevi = {k: xp.nonzero(data == k) for k in true_keys}
+
+ vi = ndimage.value_indices(data, ignore_value=0)
+ assert vi.keys() == truevi.keys()
+ for key in vi.keys():
+ assert len(vi[key]) == len(truevi[key])
+ for v, true_v in zip(vi[key], truevi[key]):
+ xp_assert_equal(v, true_v)
+
+
+@make_xp_test_case(ndimage.value_indices)
+def test_value_indices02(xp):
+ "Test input checking"
+ data = xp.zeros((5, 4), dtype=xp.float32)
+ msg = "Parameter 'arr' must be an integer array"
+ with assert_raises(ValueError, match=msg):
+ ndimage.value_indices(data)
+
+
+@make_xp_test_case(ndimage.value_indices)
+def test_value_indices03(xp):
+ "Test different input array shapes, from 1-D to 4-D"
+ for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]:
+ a = np.asarray((12*[1]+12*[2]+12*[3]), dtype=np.int32)
+ a = np.reshape(a, shape)
+
+ trueKeys = np.unique(a)
+ a = xp.asarray(a)
+ vi = ndimage.value_indices(a)
+ assert list(vi.keys()) == list(trueKeys)
+ for k in [int(x) for x in trueKeys]:
+ trueNdx = xp.nonzero(a == k)
+ assert len(vi[k]) == len(trueNdx)
+ for vik, true_vik in zip(vi[k], trueNdx):
+ xp_assert_equal(vik, true_vik)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum01(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ output = ndimage.sum(input)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.zeros([0, 4], dtype=dtype)
+ output = ndimage.sum(input)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum03(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.ones([], dtype=dtype)
+ output = ndimage.sum(input)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum04(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 2], dtype=dtype)
+ output = ndimage.sum(input)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum05(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input)
+ assert_almost_equal(output, xp.asarray(10.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum06(xp):
+ labels = np.asarray([], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum07(xp):
+ labels = np.ones([0, 4], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.zeros([0, 4], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum08(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 2], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert output == 1
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum09(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum10(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.sum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum11(xp):
+ labels = xp.asarray([1, 2], dtype=xp.int8)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(6.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum12(xp):
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+ assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0]))
+
+
+@make_xp_test_case(ndimage.sum, ndimage.sum_labels)
+def test_sum_labels(xp):
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+ output_labels = ndimage.sum_labels(
+ input, labels=labels, index=xp.asarray([4, 8, 2]))
+
+ assert xp.all(output_sum == output_labels)
+ assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0]))
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.mean(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean02(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.mean(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean03(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.mean(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean04(xp):
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.mean(input, labels=labels,
+ index=xp.asarray([4, 8, 2]))
+ # XXX: output[[0, 2]] does not work in array-api-strict; annoying
+ # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5]))
+ assert output[0] == 4.0
+ assert output[2] == 2.5
+ assert xp.isnan(output[1])
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum02(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.minimum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum03(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum04(xp):
+ labels = xp.asarray([[1, 2], [2, 3]])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum(input, labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum02(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.maximum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum03(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum04(xp):
+ labels = xp.asarray([[1, 2], [2, 3]])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum(input, labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum05(xp):
+ # Regression test for ticket #501 (Trac)
+ x = xp.asarray([-3, -2, -1])
+ assert ndimage.maximum(x) == -1
+
+
+@make_xp_test_case(ndimage.median)
+def test_median01(xp):
+ a = xp.asarray([[1, 2, 0, 1],
+ [5, 3, 0, 4],
+ [0, 0, 0, 7],
+ [9, 3, 0, 0]])
+ labels = xp.asarray([[1, 1, 0, 2],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]])
+ output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3]))
+ assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0]))
+
+
+@make_xp_test_case(ndimage.median)
+def test_median02(xp):
+ a = xp.asarray([[1, 2, 0, 1],
+ [5, 3, 0, 4],
+ [0, 0, 0, 7],
+ [9, 3, 0, 0]])
+ output = ndimage.median(a)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.median)
+def test_median03(xp):
+ a = xp.asarray([[1, 2, 0, 1],
+ [5, 3, 0, 4],
+ [0, 0, 0, 7],
+ [9, 3, 0, 0]])
+ labels = xp.asarray([[1, 1, 0, 2],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]])
+ output = ndimage.median(a, labels=labels)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.median)
+def test_median_gh12836_bool(xp):
+ # test boolean addition fix on example from gh-12836
+ a = np.asarray([1, 1], dtype=bool)
+ a = xp.asarray(a)
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+ assert_array_almost_equal(output, xp.asarray([1.0]))
+
+
+@make_xp_test_case(ndimage.median)
+def test_median_no_int_overflow(xp):
+ # test integer overflow fix on example from gh-12836
+ a = xp.asarray([65, 70], dtype=xp.int8)
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+ assert_array_almost_equal(output, xp.asarray([67.5]))
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance01(xp):
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
+ output = ndimage.variance(input)
+ assert xp.isnan(output)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1], dtype=dtype)
+ output = ndimage.variance(input)
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance03(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3], dtype=dtype)
+ output = ndimage.variance(input)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance04(xp):
+ input = np.asarray([1, 0], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.variance(input)
+ assert_almost_equal(output, xp.asarray(0.25), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance05(xp):
+ labels = xp.asarray([2, 2, 3])
+ for type in types:
+ dtype = getattr(xp, type)
+
+ input = xp.asarray([1, 3, 8], dtype=dtype)
+ output = ndimage.variance(input, labels, 2)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance06(xp):
+ labels = xp.asarray([2, 2, 3, 3, 4])
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+ output = ndimage.variance(input, labels, xp.asarray([2, 3, 4]))
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation01(xp):
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
+ output = ndimage.standard_deviation(input)
+ assert xp.isnan(output)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1], dtype=dtype)
+ output = ndimage.standard_deviation(input)
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation03(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3], dtype=dtype)
+ output = ndimage.standard_deviation(input)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation04(xp):
+ input = np.asarray([1, 0], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.standard_deviation(input)
+ assert_almost_equal(output, xp.asarray(0.5), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation05(xp):
+ labels = xp.asarray([2, 2, 3])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3, 8], dtype=dtype)
+ output = ndimage.standard_deviation(input, labels, 2)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation06(xp):
+ labels = xp.asarray([2, 2, 3, 3, 4])
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+ output = ndimage.standard_deviation(
+ input, labels, xp.asarray([2, 3, 4])
+ )
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation07(xp):
+ labels = xp.asarray([1])
+ with np.errstate(all='ignore'):
+ for type in types:
+ if is_torch(xp) and type == 'uint8':
+ pytest.xfail("value cannot be converted to type uint8 "
+ "without overflow")
+ dtype = getattr(xp, type)
+ input = xp.asarray([-0.00619519], dtype=dtype)
+ output = ndimage.standard_deviation(input, labels, xp.asarray([1]))
+ assert_array_almost_equal(output, xp.asarray([0]))
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels=labels)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.minimum_position(input)
+ assert output == (1, 2)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position03(xp):
+ input = np.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.minimum_position(input)
+ assert output == (1, 2)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position04(xp):
+ input = np.asarray([[5, 4, 2, 5],
+ [3, 7, 1, 2],
+ [1, 5, 1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.minimum_position(input)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position05(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 2, 3]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels)
+ assert output == (2, 0)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position06(xp):
+ labels = xp.asarray([1, 2, 3, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels, 2)
+ assert output == (0, 1)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position07(xp):
+ labels = xp.asarray([1, 2, 3, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels,
+ xp.asarray([2, 3]))
+ assert output[0] == (0, 1)
+ assert output[1] == (1, 2)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum_position(input,
+ labels=labels)
+ assert output == (1, 0)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input)
+ assert output == (1, 2)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position03(xp):
+ input = np.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.maximum_position(input)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position04(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels)
+ assert output == (1, 1)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position05(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels, 1)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position06(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels,
+ xp.asarray([1, 2]))
+ assert output[0] == (0, 0)
+ assert output[1] == (1, 1)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position07(xp):
+ # Test float labels
+ labels = xp.asarray([1.0, 2.5, 0.0, 4.5])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels,
+ xp.asarray([1.0, 4.5]))
+ assert output[0] == (0, 0)
+ assert output[1] == (0, 3)
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output1 = ndimage.extrema(input, labels=labels)
+ output2 = ndimage.minimum(input, labels=labels)
+ output3 = ndimage.maximum(input, labels=labels)
+ output4 = ndimage.minimum_position(input,
+ labels=labels)
+ output5 = ndimage.maximum_position(input,
+ labels=labels)
+ assert output1 == (output2, output3, output4, output5)
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema02(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output1 = ndimage.extrema(input, labels=labels,
+ index=2)
+ output2 = ndimage.minimum(input, labels=labels,
+ index=2)
+ output3 = ndimage.maximum(input, labels=labels,
+ index=2)
+ output4 = ndimage.minimum_position(input,
+ labels=labels, index=2)
+ output5 = ndimage.maximum_position(input,
+ labels=labels, index=2)
+ assert output1 == (output2, output3, output4, output5)
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema03(xp):
+ labels = xp.asarray([[1, 2], [2, 3]])
+ for type in types:
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output1 = ndimage.extrema(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output2 = ndimage.minimum(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output3 = ndimage.maximum(input, labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output4 = ndimage.minimum_position(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output5 = ndimage.maximum_position(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ assert_array_almost_equal(output1[0], output2)
+ assert_array_almost_equal(output1[1], output3)
+ assert output1[2] == output4
+ assert output1[3] == output5
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema04(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output1 = ndimage.extrema(input, labels, xp.asarray([1, 2]))
+ output2 = ndimage.minimum(input, labels, xp.asarray([1, 2]))
+ output3 = ndimage.maximum(input, labels, xp.asarray([1, 2]))
+ output4 = ndimage.minimum_position(input, labels,
+ xp.asarray([1, 2]))
+ output5 = ndimage.maximum_position(input, labels,
+ xp.asarray([1, 2]))
+ assert_array_almost_equal(output1[0], output2)
+ assert_array_almost_equal(output1[1], output3)
+ assert output1[2] == output4
+ assert output1[3] == output5
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass01(xp):
+ expected = (0.0, 0.0)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 0], [0, 0]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass02(xp):
+ expected = (1, 0)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[0, 0], [1, 0]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass03(xp):
+ expected = (0, 1)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[0, 1], [0, 0]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass04(xp):
+ expected = (1, 1)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[0, 0], [0, 1]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass05(xp):
+ expected = (0.5, 0.5)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 1], [1, 1]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass06(xp):
+ expected = (0.5, 0.5)
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass07(xp):
+ labels = xp.asarray([1, 0])
+ expected = (0.5, 0.0)
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input, labels)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass08(xp):
+ labels = xp.asarray([1, 2])
+ expected = (0.5, 1.0)
+ input = np.asarray([[5, 2], [3, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input, labels, 2)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass09(xp):
+ labels = xp.asarray((1, 2))
+ expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64)
+ input = np.asarray([[1, 2], [1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2]))
+ xp_assert_equal(xp.asarray(output), xp.asarray(expected))
+
+
+@make_xp_test_case(ndimage.histogram)
+def test_histogram01(xp):
+ expected = xp.ones(10)
+ input = xp.arange(10)
+ output = ndimage.histogram(input, 0, 10, 10)
+ assert_array_almost_equal(output, expected)
+
+
+@make_xp_test_case(ndimage.histogram)
+def test_histogram02(xp):
+ labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2])
+ expected = xp.asarray([0, 2, 0, 1, 1])
+ input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3])
+ output = ndimage.histogram(input, 0, 4, 5, labels, 1)
+ assert_array_almost_equal(output, expected)
+
+
+@skip_xp_backends(np_only=True, reason='object arrays')
+@make_xp_test_case(ndimage.histogram)
+def test_histogram03(xp):
+ labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2])
+ expected1 = xp.asarray([0, 1, 0, 1, 1])
+ expected2 = xp.asarray([0, 0, 0, 3, 0])
+ input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3])
+
+ output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2))
+
+ assert_array_almost_equal(output[0], expected1)
+ assert_array_almost_equal(output[1], expected2)
+
+@make_xp_test_case(ndimage.mean, ndimage.variance, ndimage.standard_deviation,
+ ndimage.median, ndimage.minimum, ndimage.maximum)
+def test_stat_funcs_2d(xp):
+ a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]])
+ lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]])
+
+ mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+ var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64))
+
+ std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2]))
+ assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64)))
+
+ med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+ min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False)
+
+ max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False)
+
+
+@skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+@make_xp_test_case(ndimage.watershed_ift)
+class TestWatershedIft:
+
+ def test_watershed_ift01(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift02(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, 1, 1, 1, -1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, 1, 1, 1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift03(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 2, 0, 3, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, 2, -1, 3, -1, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, -1, 2, -1, 3, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift04(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 2, 0, 3, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, -1]],
+ dtype=xp.int8)
+
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift05(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 3, 0, 2, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, -1]],
+ dtype=xp.int8)
+ structure = xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift06(self, xp):
+ data = xp.asarray([[0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific")
+ def test_watershed_ift07(self, xp):
+ shape = (7, 6)
+ data = np.zeros(shape, dtype=np.uint8)
+ data = data.transpose()
+ data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
+ data = xp.asarray(data)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ out = xp.zeros(shape, dtype=xp.int16)
+ out = out.T
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ ndimage.watershed_ift(data, markers, structure=structure,
+ output=out)
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+ def test_watershed_ift08(self, xp):
+ # Test cost larger than uint8. See gh-10069.
+ data = xp.asarray([[256, 0],
+ [0, 0]], dtype=xp.uint16)
+ markers = xp.asarray([[1, 0],
+ [0, 0]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[1, 1],
+ [1, 1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+ def test_watershed_ift09(self, xp):
+ # Test large cost. See gh-19575
+ data = xp.asarray([[xp.iinfo(xp.uint16).max, 0],
+ [0, 0]], dtype=xp.uint16)
+ markers = xp.asarray([[1, 0],
+ [0, 0]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[1, 1],
+ [1, 1]]
+ xp_assert_close(out, xp.asarray(expected), check_dtype=False)
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize("dt", [np.intc, np.uintc])
+@make_xp_test_case(ndimage.value_indices)
+def test_gh_19423(dt, xp):
+ rng = np.random.default_rng(123)
+ max_val = 8
+ image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt)
+ val_idx = ndimage.value_indices(image)
+ assert len(val_idx.keys()) == max_val
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..57a0f1b1c7c60d6967289e93a398ae0e73c9702b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py
@@ -0,0 +1,3108 @@
+import numpy as np
+from scipy._lib._array_api import (
+ is_cupy, is_numpy,
+ xp_assert_close, xp_assert_equal, assert_array_almost_equal,
+ make_xp_test_case,
+ make_xp_pytest_param,
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy import ndimage
+
+from . import types
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+# mypy: disable-error-code=attr-defined
+
+class TestNdimageMorphology:
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # brute force (bf) distance transform
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(data, 'euclidean',
+ return_indices=True)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 2, 4, 2, 1, 0, 0],
+ [0, 0, 1, 4, 8, 4, 1, 0, 0],
+ [0, 0, 1, 2, 4, 2, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out * out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 3, 2, 1, 2, 3, 3, 3],
+ [4, 4, 4, 4, 6, 4, 4, 4, 4],
+ [5, 5, 6, 6, 7, 6, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 1, 2, 4, 6, 7, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(data, 'cityblock',
+ return_indices=True)
+
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 2, 2, 2, 1, 0, 0],
+ [0, 0, 1, 2, 3, 2, 1, 0, 0],
+ [0, 0, 1, 2, 2, 2, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 3, 3, 1, 3, 3, 3, 3],
+ [4, 4, 4, 4, 7, 4, 4, 4, 4],
+ [5, 5, 6, 7, 7, 7, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 1, 1, 4, 7, 7, 7, 8],
+ [0, 1, 1, 1, 4, 7, 7, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(data, 'chessboard',
+ return_indices=True)
+
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 2, 1, 1, 0, 0],
+ [0, 0, 1, 2, 2, 2, 1, 0, 0],
+ [0, 0, 1, 1, 2, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 4, 2, 2, 2, 4, 3, 3],
+ [4, 4, 5, 6, 6, 6, 5, 4, 4],
+ [5, 5, 6, 6, 7, 6, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 5, 6, 6, 7, 8],
+ [0, 1, 1, 2, 6, 6, 7, 7, 8],
+ [0, 1, 1, 2, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 6, 6, 7, 7, 8],
+ [0, 1, 2, 4, 5, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+
+ @skip_xp_backends(
+ np_only=True, reason='inplace distances= arrays are numpy-specific'
+ )
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ tdt, tft = ndimage.distance_transform_bf(data, return_indices=1)
+ dts = []
+ fts = []
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ndimage.distance_transform_bf(data, distances=dt)
+ dts.append(dt)
+ ft = ndimage.distance_transform_bf(
+ data, return_distances=False, return_indices=1)
+ fts.append(ft)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ndimage.distance_transform_bf(
+ data, return_distances=False, return_indices=True, indices=ft)
+ fts.append(ft)
+ dt, ft = ndimage.distance_transform_bf(
+ data, return_indices=1)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = ndimage.distance_transform_bf(
+ data, distances=dt, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ dt = ndimage.distance_transform_bf(
+ data, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ndimage.distance_transform_bf(
+ data, distances=dt, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ for dt in dts:
+ assert_array_almost_equal(tdt, dt)
+ for ft in fts:
+ assert_array_almost_equal(tft, ft)
+
+ @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf')
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(
+ data, 'euclidean', return_indices=True, sampling=[2, 2])
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 4, 0, 0, 0],
+ [0, 0, 4, 8, 16, 8, 4, 0, 0],
+ [0, 0, 4, 16, 32, 16, 4, 0, 0],
+ [0, 0, 4, 8, 16, 8, 4, 0, 0],
+ [0, 0, 0, 4, 4, 4, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out * out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 3, 2, 1, 2, 3, 3, 3],
+ [4, 4, 4, 4, 6, 4, 4, 4, 4],
+ [5, 5, 6, 6, 7, 6, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 1, 2, 4, 6, 7, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf06(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(
+ data, 'euclidean', return_indices=True, sampling=[2, 1])
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 4, 1, 0, 0, 0],
+ [0, 0, 1, 4, 8, 4, 1, 0, 0],
+ [0, 0, 1, 4, 9, 4, 1, 0, 0],
+ [0, 0, 1, 4, 8, 4, 1, 0, 0],
+ [0, 0, 0, 1, 4, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out * out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 2, 2, 2, 2, 2],
+ [3, 3, 3, 3, 2, 3, 3, 3, 3],
+ [4, 4, 4, 4, 4, 4, 4, 4, 4],
+ [5, 5, 5, 5, 6, 5, 5, 5, 5],
+ [6, 6, 6, 6, 7, 6, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 6, 6, 6, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 1, 1, 7, 7, 7, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ def test_distance_transform_bf07(self, xp):
+ # test input validation per discussion on PR #13302
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+ with assert_raises(RuntimeError):
+ ndimage.distance_transform_bf(
+ data, return_distances=False, return_indices=False
+ )
+
+ @make_xp_test_case(ndimage.distance_transform_bf,
+ ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # chamfer type distance (cdt) transform
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_cdt(
+ data, 'cityblock', return_indices=True)
+ bf = ndimage.distance_transform_bf(data, 'cityblock')
+ assert_array_almost_equal(bf, out)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 1, 1, 1, 2, 2, 2],
+ [3, 3, 2, 1, 1, 1, 2, 3, 3],
+ [4, 4, 4, 4, 1, 4, 4, 4, 4],
+ [5, 5, 5, 5, 7, 7, 6, 5, 5],
+ [6, 6, 6, 6, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 1, 1, 4, 7, 7, 7, 8],
+ [0, 1, 1, 1, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf,
+ ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_cdt(data, 'chessboard',
+ return_indices=True)
+ bf = ndimage.distance_transform_bf(data, 'chessboard')
+ assert_array_almost_equal(bf, out)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 1, 1, 1, 2, 2, 2],
+ [3, 3, 2, 2, 1, 2, 2, 3, 3],
+ [4, 4, 3, 2, 2, 2, 3, 4, 4],
+ [5, 5, 4, 6, 7, 6, 4, 5, 5],
+ [6, 6, 6, 6, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 3, 4, 6, 7, 8],
+ [0, 1, 1, 2, 2, 6, 6, 7, 8],
+ [0, 1, 1, 1, 2, 6, 7, 7, 8],
+ [0, 1, 1, 2, 6, 6, 7, 7, 8],
+ [0, 1, 2, 2, 5, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @skip_xp_backends(
+ np_only=True, reason='inplace indices= arrays are numpy-specific'
+ )
+ @make_xp_test_case(ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True)
+ dts = []
+ fts = []
+ dt = xp.zeros(data.shape, dtype=xp.int32)
+ ndimage.distance_transform_cdt(data, distances=dt)
+ dts.append(dt)
+ ft = ndimage.distance_transform_cdt(
+ data, return_distances=False, return_indices=True)
+ fts.append(ft)
+ ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+ ndimage.distance_transform_cdt(
+ data, return_distances=False, return_indices=True, indices=ft)
+ fts.append(ft)
+ dt, ft = ndimage.distance_transform_cdt(
+ data, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.int32)
+ ft = ndimage.distance_transform_cdt(
+ data, distances=dt, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+ ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+ dt = ndimage.distance_transform_cdt(
+ data, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.int32)
+ ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+ ndimage.distance_transform_cdt(data, distances=dt,
+ return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ for dt in dts:
+ assert_array_almost_equal(tdt, dt)
+ for ft in fts:
+ assert_array_almost_equal(tft, ft)
+
+ @skip_xp_backends(
+ np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+ )
+ @make_xp_test_case(ndimage.distance_transform_cdt)
+ def test_distance_transform_cdt04(self, xp):
+ # test input validation per discussion on PR #13302
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+ indices_out = xp.zeros((data.ndim,) + data.shape, dtype=xp.int32)
+ with assert_raises(RuntimeError):
+ ndimage.distance_transform_bf(
+ data,
+ return_distances=True,
+ return_indices=False,
+ indices=indices_out
+ )
+
+ @xfail_xp_backends("torch", reason="int overflow")
+ @make_xp_test_case(ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # test custom metric type per discussion on issue #17381
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ metric_arg = xp.ones((3, 3))
+ actual = ndimage.distance_transform_cdt(data, metric=metric_arg)
+ assert xp.sum(actual) == -21
+
+ @skip_xp_backends("cupy", reason="CuPy does not have distance_transform_bf")
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # euclidean distance transform (edt)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_edt(data, return_indices=True)
+ bf = ndimage.distance_transform_bf(data, 'euclidean')
+ assert_array_almost_equal(bf, out)
+
+ # np-specific check
+ np_ft = np.asarray(ft)
+ dt = np_ft - np.indices(np_ft.shape[1:], dtype=np_ft.dtype)
+ dt = dt.astype(np.float64)
+ np.multiply(dt, dt, dt)
+ dt = np.add.reduce(dt, axis=0)
+ np.sqrt(dt, dt)
+
+ dt = xp.asarray(dt)
+ assert_array_almost_equal(bf, dt)
+
+ @skip_xp_backends(
+ np_only=True, reason='inplace distances= are numpy-specific'
+ )
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ tdt, tft = ndimage.distance_transform_edt(data, return_indices=True)
+ dts = []
+ fts = []
+
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ndimage.distance_transform_edt(data, distances=dt)
+ dts.append(dt)
+
+ ft = ndimage.distance_transform_edt(
+ data, return_distances=0, return_indices=True)
+ fts.append(ft)
+
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ft = xp.asarray(ft)
+ ndimage.distance_transform_edt(
+ data, return_distances=False, return_indices=True, indices=ft)
+ fts.append(ft)
+
+ dt, ft = ndimage.distance_transform_edt(
+ data, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = ndimage.distance_transform_edt(
+ data, distances=dt, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ft = xp.asarray(ft)
+ dt = ndimage.distance_transform_edt(
+ data, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ft = xp.asarray(ft)
+ ndimage.distance_transform_edt(
+ data, distances=dt, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+
+ for dt in dts:
+ assert_array_almost_equal(tdt, dt)
+ for ft in fts:
+ assert_array_almost_equal(tft, ft)
+
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2])
+ out = ndimage.distance_transform_edt(data, sampling=[2, 2])
+ assert_array_almost_equal(out, ref)
+
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt4(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1])
+ out = ndimage.distance_transform_edt(data, sampling=[2, 1])
+ assert_array_almost_equal(out, ref)
+
+ @xfail_xp_backends(
+ "cupy", reason="Only 2D and 3D distance transforms are supported in CuPy"
+ )
+ @make_xp_test_case(ndimage.distance_transform_edt)
+ def test_distance_transform_edt5(self, xp):
+ # Ticket #954 regression test
+ out = ndimage.distance_transform_edt(xp.asarray(False))
+ assert_array_almost_equal(out, xp.asarray([0.]))
+
+ @xfail_xp_backends(
+ np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+ )
+ @make_xp_test_case(ndimage.distance_transform_edt)
+ def test_distance_transform_edt6(self, xp):
+ # test input validation per discussion on PR #13302
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+ distances_out = xp.zeros(data.shape, dtype=xp.float64)
+ with assert_raises(RuntimeError):
+ ndimage.distance_transform_bf(
+ data,
+ return_indices=True,
+ return_distances=False,
+ distances=distances_out
+ )
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure01(self, xp):
+ struct = ndimage.generate_binary_structure(0, 1)
+ assert struct == 1
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure02(self, xp):
+ struct = ndimage.generate_binary_structure(1, 1)
+ assert_array_almost_equal(struct, [1, 1, 1])
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure03(self, xp):
+ struct = ndimage.generate_binary_structure(2, 1)
+ assert_array_almost_equal(struct, [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]])
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure04(self, xp):
+ struct = ndimage.generate_binary_structure(2, 2)
+ assert_array_almost_equal(struct, [[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+
+ @make_xp_test_case(ndimage.iterate_structure)
+ def test_iterate_structure01(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ out = ndimage.iterate_structure(struct, 2)
+ expected = np.asarray([[0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.iterate_structure)
+ def test_iterate_structure02(self, xp):
+ struct = [[0, 1],
+ [1, 1],
+ [0, 1]]
+ struct = xp.asarray(struct)
+ out = ndimage.iterate_structure(struct, 2)
+ expected = np.asarray([[0, 0, 1],
+ [0, 1, 1],
+ [1, 1, 1],
+ [0, 1, 1],
+ [0, 0, 1]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.iterate_structure)
+ def test_iterate_structure03(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ out = ndimage.iterate_structure(struct, 2, 1)
+ expected = [[0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out[0], expected)
+ assert out[1] == [2, 2]
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0]))
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8912")
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion05_broadcasted(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones((1, ), dtype=dtype)
+ data = xp.broadcast_to(data, (3, ))
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion06(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion07(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([5], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion08(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([5], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion09(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 0, 0, 0, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion10(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 0, 0, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion11(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion12(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion13(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1, origin=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion14(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion15(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 0, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion16(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 1], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([[1]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion17(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 1], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([[0]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion18(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion19(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion20(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion21(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion22(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion23(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion24(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = xp.asarray([[0, 1],
+ [1, 1]])
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion25(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 0, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [0, 0, 1, 0, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion26(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 0, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1],
+ [0, 0, 0, 0, 1, 0, 0, 1],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [0, 0, 1, 0, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1,
+ origin=(-1, -1))
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends(
+ "cupy", reason="CuPy: NotImplementedError: only brute_force iteration"
+ )
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion27(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=2)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion28(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=2, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends(
+ "cupy", reason="CuPy: NotImplementedError: only brute_force iteration"
+ )
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion29(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, iterations=3)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion30(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=3, output=out)
+ assert_array_almost_equal(out, expected)
+
+ # test with output memory overlap
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=3, output=data)
+ assert_array_almost_equal(data, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion31(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 0, 1],
+ [0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 1]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=1, output=out, origin=(-1, -1))
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion32(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, iterations=2)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion33(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 0, 1],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ mask = [[1, 1, 1, 1, 1, 0, 0],
+ [1, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1]]
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 1, 0, 0, 1],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, mask=mask, iterations=-1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion34(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ mask = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, mask=mask)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion35(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ mask = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray(mask, dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ tmp = [[0, 0, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 0, 1],
+ [0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 1]]
+ tmp = np.asarray(tmp, dtype=bool)
+ tmp = xp.asarray(tmp)
+ expected = xp.logical_and(tmp, mask)
+ tmp = xp.logical_and(data, xp.logical_not(mask))
+ expected = xp.logical_or(expected, tmp)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=1, output=out,
+ origin=(-1, -1), mask=mask)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion36(self, xp):
+ struct = [[0, 1, 0],
+ [1, 0, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ mask = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray(mask, dtype=bool)
+ mask = xp.asarray(mask)
+ tmp = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1],
+ [0, 0, 0, 0, 1, 0, 0, 1],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1]]
+ tmp = np.asarray(tmp, dtype=bool)
+ tmp = xp.asarray(tmp)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [0, 0, 1, 0, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ expected = xp.logical_and(tmp, mask)
+ tmp = xp.logical_and(data, xp.logical_not(mask))
+ expected = xp.logical_or(expected, tmp)
+ out = ndimage.binary_erosion(data, struct, mask=mask,
+ border_value=1, origin=(-1, -1))
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion37(self, xp):
+ a = np.asarray([[1, 0, 1],
+ [0, 1, 0],
+ [1, 0, 1]], dtype=bool)
+ a = xp.asarray(a)
+ b = xp.zeros_like(a)
+ out = ndimage.binary_erosion(a, structure=a, output=b, iterations=0,
+ border_value=True, brute_force=True)
+ assert out is b
+ xp_assert_equal(
+ ndimage.binary_erosion(a, structure=a, iterations=0,
+ border_value=True),
+ b)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion38(self, xp):
+ data = np.asarray([[1, 0, 1],
+ [0, 1, 0],
+ [1, 0, 1]], dtype=bool)
+ data = xp.asarray(data)
+ iterations = 2.0
+ with assert_raises(TypeError):
+ _ = ndimage.binary_erosion(data, iterations=iterations)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion39(self, xp):
+ iterations = np.int32(3)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=iterations, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion40(self, xp):
+ iterations = np.int64(3)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=iterations, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert out == xp.asarray(False)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation05_broadcasted(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones((1, ), dtype=dtype)
+ data = xp.broadcast_to(data, (3,))
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation06(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([0, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation07(self, dtype, xp):
+ data = np.zeros([3], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation08(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data[3] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation09(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation10(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation11(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, origin=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation12(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation13(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation14(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation15(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct,
+ origin=-1, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation16(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation17(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([1, 1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[0]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation18(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation19(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3, 3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation20(self, dtype, xp):
+ data = np.zeros([3, 3], dtype=dtype)
+ data[1, 1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation21(self, dtype, xp):
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ data = np.zeros([3, 3], dtype=dtype)
+ data[1, 1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation22(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation23(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 0, 0, 0, 0, 1],
+ [1, 1, 0, 0, 0, 1, 0, 1],
+ [1, 0, 0, 1, 1, 1, 1, 1],
+ [1, 0, 1, 1, 1, 1, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 0, 1, 0, 0, 1, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation24(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 0, 0, 0, 0, 0, 0],
+ [1, 0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 0, 0],
+ [0, 1, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, origin=(1, 1))
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation25(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 0, 0, 0, 0, 1, 1],
+ [1, 0, 0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 0, 0, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation26(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation27(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation28(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 1, 1],
+ [1, 0, 0, 1],
+ [1, 0, 0, 1],
+ [1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation29(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct, iterations=2)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output= arrays are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation30(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_dilation(data, struct, iterations=2, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation31(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct, iterations=3)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output= arrays are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation32(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_dilation(data, struct, iterations=3, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation33(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+
+ out = ndimage.binary_dilation(data, struct, iterations=-1,
+ mask=mask, border_value=0)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace output= arrays are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation34(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.zeros(mask.shape, dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct, iterations=-1,
+ mask=mask, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation35(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ tmp = [[1, 1, 0, 0, 0, 0, 1, 1],
+ [1, 0, 0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 0, 0, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1]]
+
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]])
+ mask = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray(mask, dtype=bool)
+
+ expected = np.logical_and(tmp, mask)
+ tmp = np.logical_and(data, np.logical_not(mask))
+ expected = np.logical_or(expected, tmp)
+
+ mask = xp.asarray(mask)
+ expected = xp.asarray(expected)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, mask=mask,
+ origin=(1, 1), border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation36(self, xp):
+ # gh-21009
+ data = np.zeros([], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, iterations=-1)
+ assert out == xp.asarray(False)
+
+ @make_xp_test_case(ndimage.binary_propagation)
+ def test_binary_propagation01(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_propagation(data, struct,
+ mask=mask, border_value=0)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_propagation)
+ def test_binary_propagation02(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ struct = xp.asarray(struct)
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.zeros(mask.shape, dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_propagation(data, struct,
+ mask=mask, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_propagation)
+ def test_binary_propagation03(self, xp):
+ # gh-21009
+ data = xp.asarray(np.zeros([], dtype=bool))
+ expected = xp.asarray(np.zeros([], dtype=bool))
+ out = ndimage.binary_propagation(data)
+ assert out == expected
+
+ @make_xp_test_case(ndimage.binary_opening)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_opening01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_opening(data)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_opening)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_opening02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ struct = xp.asarray(struct)
+ data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_opening(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_closing)
+ def test_binary_closing01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_closing(data)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_closing)
+ def test_binary_closing02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ struct = xp.asarray(struct)
+ data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_closing(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_fill_holes)
+ def test_binary_fill_holes01(self, xp):
+ expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+
+ out = ndimage.binary_fill_holes(data)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_fill_holes)
+ def test_binary_fill_holes02(self, xp):
+ expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_fill_holes(data)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_fill_holes)
+ def test_binary_fill_holes03(self, xp):
+ expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 1, 1, 1],
+ [0, 1, 1, 1, 0, 1, 1, 1],
+ [0, 1, 1, 1, 0, 1, 1, 1],
+ [0, 0, 1, 0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 1, 0, 1, 1, 1],
+ [0, 1, 0, 1, 0, 1, 0, 1],
+ [0, 1, 0, 1, 0, 1, 0, 1],
+ [0, 0, 1, 0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_fill_holes(data)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(cpu_only=True)
+ @skip_xp_backends(
+ "cupy", reason="these filters do not yet have axes support in CuPy")
+ @skip_xp_backends(
+ "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+ @pytest.mark.parametrize('border_value',[0, 1])
+ @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+ @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+ @pytest.mark.parametrize(
+ 'func', [
+ make_xp_pytest_param(ndimage.binary_erosion),
+ make_xp_pytest_param(ndimage.binary_dilation),
+ make_xp_pytest_param(ndimage.binary_opening),
+ make_xp_pytest_param(ndimage.binary_closing),
+ make_xp_pytest_param(ndimage.binary_hit_or_miss),
+ make_xp_pytest_param(ndimage.binary_propagation),
+ make_xp_pytest_param(ndimage.binary_fill_holes),
+ ]
+ )
+ def test_binary_axes(self, xp, func, expand_axis, origin, border_value):
+ func_name = func.__name__
+ struct = np.asarray([[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]], bool)
+ struct = xp.asarray(struct)
+
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 0, 1, 0],
+ [0, 1, 0, 1, 1, 0, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], bool)
+ data = xp.asarray(data)
+ if func_name == "binary_hit_or_miss":
+ kwargs = dict(origin1=origin, origin2=origin)
+ else:
+ kwargs = dict(origin=origin)
+ border_supported = func_name not in ["binary_hit_or_miss",
+ "binary_fill_holes"]
+ if border_supported:
+ kwargs['border_value'] = border_value
+ elif border_value != 0:
+ pytest.skip('border_value !=0 unsupported by this function')
+
+ expected = func(data, struct, **kwargs)
+
+ # replicate data and expected result along a new axis
+ n_reps = 5
+ expected = xp.stack([expected] * n_reps, axis=expand_axis)
+ data = xp.stack([data] * n_reps, axis=expand_axis)
+
+ # filter all axes except expand_axis
+ axes = [0, 1, 2]
+ axes.remove(expand_axis)
+ if is_numpy(xp) or is_cupy(xp):
+ out = xp.asarray(np.zeros(data.shape, bool))
+ func(data, struct, output=out, axes=axes, **kwargs)
+ else:
+ # inplace output= is unsupported by JAX
+ out = func(data, struct, axes=axes, **kwargs)
+ xp_assert_close(out, expected)
+
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.grey_erosion(array, footprint=footprint)
+ assert_array_almost_equal(output,
+ xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]]))
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8398")
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion01_overlap(self, xp):
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ ndimage.grey_erosion(array, footprint=footprint, output=array)
+ assert_array_almost_equal(array,
+ xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]])
+ )
+
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ output = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]])
+ )
+
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion03(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[1, 1, 0, 0, 0],
+ [1, 2, 0, 2, 0],
+ [4, 4, 2, 2, 0]])
+ )
+
+ @make_xp_test_case(ndimage.grey_dilation)
+ def test_grey_dilation01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+ output = ndimage.grey_dilation(array, footprint=footprint)
+ assert_array_almost_equal(output,
+ xp.asarray([[7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7],
+ [8, 8, 8, 7, 7]]),
+ )
+
+ @make_xp_test_case(ndimage.grey_dilation)
+ def test_grey_dilation02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ output = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7],
+ [8, 8, 8, 7, 7]]),
+ )
+
+ @make_xp_test_case(ndimage.grey_dilation)
+ def test_grey_dilation03(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+ structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[8, 8, 10, 10, 6],
+ [8, 10, 9, 10, 8],
+ [9, 9, 9, 8, 8]]),
+ )
+
+ @make_xp_test_case(ndimage.grey_opening)
+ def test_grey_opening01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ tmp = ndimage.grey_erosion(array, footprint=footprint)
+ expected = ndimage.grey_dilation(tmp, footprint=footprint)
+ output = ndimage.grey_opening(array, footprint=footprint)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_opening)
+ def test_grey_opening02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = ndimage.grey_dilation(tmp, footprint=footprint,
+ structure=structure)
+ output = ndimage.grey_opening(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_closing)
+ def test_grey_closing01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ tmp = ndimage.grey_dilation(array, footprint=footprint)
+ expected = ndimage.grey_erosion(tmp, footprint=footprint)
+ output = ndimage.grey_closing(array, footprint=footprint)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_closing)
+ def test_grey_closing02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ expected = ndimage.grey_erosion(tmp, footprint=footprint,
+ structure=structure)
+ output = ndimage.grey_closing(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_gradient)
+ def test_morphological_gradient01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 - tmp2
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.morphological_gradient(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_gradient)
+ def test_morphological_gradient02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 - tmp2
+ output = ndimage.morphological_gradient(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_laplace)
+ def test_morphological_laplace01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 + tmp2 - 2 * array
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.morphological_laplace(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_laplace)
+ def test_morphological_laplace02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 + tmp2 - 2 * array
+ output = ndimage.morphological_laplace(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @make_xp_test_case(ndimage.grey_opening, ndimage.white_tophat)
+ def test_white_tophat01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_opening(array, footprint=footprint,
+ structure=structure)
+ expected = array - tmp
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.white_tophat(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_opening, ndimage.white_tophat)
+ def test_white_tophat02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_opening(array, footprint=footprint,
+ structure=structure)
+ expected = array - tmp
+ output = ndimage.white_tophat(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @xfail_xp_backends('cupy', reason="cupy#8399")
+ @make_xp_test_case(ndimage.white_tophat)
+ def test_white_tophat03(self, xp):
+
+ array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+ array = xp.asarray(array)
+ structure = np.ones((3, 3), dtype=bool)
+ structure = xp.asarray(structure)
+ expected = np.asarray([[0, 1, 1, 0, 0, 0, 0],
+ [1, 0, 0, 1, 1, 1, 0],
+ [1, 0, 0, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 0, 1],
+ [0, 1, 1, 0, 1, 0, 1],
+ [0, 1, 1, 0, 0, 0, 1],
+ [0, 0, 0, 1, 1, 1, 1]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ output = ndimage.white_tophat(array, structure=structure)
+ xp_assert_equal(output, expected)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/9756")
+ @make_xp_test_case(ndimage.white_tophat)
+ def test_white_tophat04(self, xp):
+ array = np.eye(5, dtype=bool)
+ structure = np.ones((3, 3), dtype=bool)
+
+ array = xp.asarray(array)
+ structure = xp.asarray(structure)
+
+ # Check that type mismatch is properly handled
+ output = xp.empty_like(array, dtype=xp.float64)
+ ndimage.white_tophat(array, structure=structure, output=output)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @make_xp_test_case(ndimage.grey_closing, ndimage.black_tophat)
+ def test_black_tophat01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_closing(array, footprint=footprint,
+ structure=structure)
+ expected = tmp - array
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.black_tophat(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_closing, ndimage.black_tophat)
+ def test_black_tophat02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_closing(array, footprint=footprint,
+ structure=structure)
+ expected = tmp - array
+ output = ndimage.black_tophat(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @xfail_xp_backends('cupy', reason="cupy/cupy#8399")
+ @make_xp_test_case(ndimage.black_tophat)
+ def test_black_tophat03(self, xp):
+
+ array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+ array = xp.asarray(array)
+ structure = np.ones((3, 3), dtype=bool)
+ structure = xp.asarray(structure)
+ expected = np.asarray([[0, 1, 1, 1, 1, 1, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 1, 0, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 1, 1, 1, 1, 1, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ output = ndimage.black_tophat(array, structure=structure)
+ xp_assert_equal(output, expected)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/9756")
+ @make_xp_test_case(ndimage.black_tophat)
+ def test_black_tophat04(self, xp):
+ array = xp.asarray(np.eye(5, dtype=bool))
+ structure = xp.asarray(np.ones((3, 3), dtype=bool))
+
+ # Check that type mismatch is properly handled
+ output = xp.empty_like(array, dtype=xp.float64)
+ ndimage.black_tophat(array, structure=structure, output=output)
+
+ @skip_xp_backends(cpu_only=True)
+ @skip_xp_backends(
+ "cupy", reason="these filters do not yet have axes support in CuPy")
+ @skip_xp_backends(
+ "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+ @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+ @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+ @pytest.mark.parametrize('mode', ['reflect', 'constant', 'nearest',
+ 'mirror', 'wrap'])
+ @pytest.mark.parametrize('footprint_mode', ['size', 'footprint',
+ 'structure'])
+ @pytest.mark.parametrize(
+ 'func',
+ [
+ make_xp_pytest_param(ndimage.grey_erosion),
+ make_xp_pytest_param(ndimage.grey_dilation),
+ make_xp_pytest_param(ndimage.grey_opening),
+ make_xp_pytest_param(ndimage.grey_closing),
+ make_xp_pytest_param(ndimage.morphological_laplace),
+ make_xp_pytest_param(ndimage.morphological_gradient),
+ make_xp_pytest_param(ndimage.white_tophat),
+ make_xp_pytest_param(ndimage.black_tophat),
+ ]
+ )
+ def test_grey_axes(self, xp, func, expand_axis, origin, footprint_mode,
+ mode):
+ data = xp.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 4, 0, 0, 0],
+ [0, 0, 2, 1, 0, 2, 0],
+ [0, 3, 0, 6, 5, 0, 1],
+ [0, 4, 5, 3, 3, 4, 0],
+ [0, 0, 9, 3, 0, 0, 0],
+ [0, 0, 0, 2, 0, 0, 0]])
+ kwargs = dict(origin=origin, mode=mode)
+ if footprint_mode == 'size':
+ kwargs['size'] = (2, 3)
+ else:
+ kwargs['footprint'] = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ if footprint_mode == 'structure':
+ kwargs['structure'] = xp.ones_like(kwargs['footprint'])
+
+ expected = func(data, **kwargs)
+
+ # replicate data and expected result along a new axis
+ n_reps = 5
+ expected = xp.stack([expected] * n_reps, axis=expand_axis)
+ data = xp.stack([data] * n_reps, axis=expand_axis)
+
+ # filter all axes except expand_axis
+ axes = [0, 1, 2]
+ axes.remove(expand_axis)
+
+ if is_numpy(xp) or is_cupy(xp):
+ out = xp.zeros(expected.shape, dtype=expected.dtype)
+ func(data, output=out, axes=axes, **kwargs)
+ else:
+ # inplace output= is unsupported by JAX
+ out = func(data, axes=axes, **kwargs)
+ xp_assert_close(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="inplace output= is numpy-specific")
+ @make_xp_test_case(ndimage.binary_hit_or_miss)
+ @pytest.mark.parametrize('dtype', types)
+ def test_hit_or_miss01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 0],
+ [1, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1],
+ [0, 0, 0, 0, 0]], dtype=dtype)
+ out = xp.asarray(np.zeros(data.shape, dtype=bool))
+ ndimage.binary_hit_or_miss(data, struct, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_hit_or_miss)
+ @pytest.mark.parametrize('dtype', types)
+ def test_hit_or_miss02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+ [1, 1, 1, 0, 0, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_hit_or_miss(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_hit_or_miss)
+ @pytest.mark.parametrize('dtype', types)
+ def test_hit_or_miss03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct1 = [[0, 0, 0],
+ [1, 1, 1],
+ [0, 0, 0]]
+ struct2 = [[1, 1, 1],
+ [0, 0, 0],
+ [1, 1, 1]]
+ expected = [[0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct1 = xp.asarray(struct1)
+ struct2 = xp.asarray(struct2)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ [0, 0, 0, 0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_hit_or_miss(data, struct1, struct2)
+ assert_array_almost_equal(out, expected)
+
+
+@make_xp_test_case(ndimage.binary_dilation, ndimage.grey_dilation)
+class TestDilateFix:
+
+ # pytest's setup_method seems to clash with the autouse `xp` fixture
+ # so call _setup manually from all methods
+ def _setup(self, xp):
+ # dilation related setup
+ self.array = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=xp.uint8)
+
+ self.sq3x3 = xp.ones((3, 3))
+ dilated3x3 = ndimage.binary_dilation(self.array, structure=self.sq3x3)
+
+ if is_numpy(xp):
+ self.dilated3x3 = dilated3x3.view(xp.uint8)
+ else:
+ self.dilated3x3 = xp.astype(dilated3x3, xp.uint8)
+
+ @skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/9756")
+ def test_dilation_square_structure(self, xp):
+ self._setup(xp)
+ result = ndimage.grey_dilation(self.array, structure=self.sq3x3)
+ # +1 accounts for difference between grey and binary dilation
+ assert_array_almost_equal(result, self.dilated3x3 + 1)
+
+ def test_dilation_scalar_size(self, xp):
+ self._setup(xp)
+ result = ndimage.grey_dilation(self.array, size=3)
+ assert_array_almost_equal(result, self.dilated3x3)
+
+
+@make_xp_test_case(ndimage.binary_opening, ndimage.binary_closing)
+class TestBinaryOpeningClosing:
+
+ def _setup(self, xp):
+ a = np.zeros((5, 5), dtype=bool)
+ a[1:4, 1:4] = True
+ a[4, 4] = True
+ self.array = xp.asarray(a)
+ self.sq3x3 = xp.ones((3, 3))
+ self.opened_old = ndimage.binary_opening(self.array, self.sq3x3,
+ 1, None, 0)
+ self.closed_old = ndimage.binary_closing(self.array, self.sq3x3,
+ 1, None, 0)
+
+ def test_opening_new_arguments(self, xp):
+ self._setup(xp)
+ opened_new = ndimage.binary_opening(self.array, self.sq3x3, 1, None,
+ 0, None, 0, False)
+ xp_assert_equal(opened_new, self.opened_old)
+
+ def test_closing_new_arguments(self, xp):
+ self._setup(xp)
+ closed_new = ndimage.binary_closing(self.array, self.sq3x3, 1, None,
+ 0, None, 0, False)
+ xp_assert_equal(closed_new, self.closed_old)
+
+
+@make_xp_test_case(ndimage.binary_erosion)
+def test_binary_erosion_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_erosion, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_erosion, data, iterations=1.5)
+
+
+@make_xp_test_case(ndimage.binary_dilation)
+def test_binary_dilation_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_dilation, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_dilation, data, iterations=1.5)
+
+
+@make_xp_test_case(ndimage.binary_opening)
+def test_binary_opening_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_opening, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_opening, data, iterations=1.5)
+
+
+@make_xp_test_case(ndimage.binary_closing)
+def test_binary_closing_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_closing, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_closing, data, iterations=1.5)
+
+
+@xfail_xp_backends(
+ "cupy", reason="CuPy: NotImplementedError: only brute_force iteration"
+)
+@make_xp_test_case(ndimage.binary_erosion)
+def test_binary_closing_noninteger_brute_force_passes_when_true(xp):
+ # regression test for gh-9905, gh-9909: ValueError for non integer iterations
+ data = xp.ones([1])
+ xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=1.5),
+ ndimage.binary_erosion(data, iterations=2, brute_force=bool(1.5))
+ )
+ xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=0.0),
+ ndimage.binary_erosion(data, iterations=2, brute_force=bool(0.0))
+ )
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="inplace output= is numpy-specific")
+@xfail_xp_backends("cupy", reason="NotImplementedError: only brute_force iteration")
+@pytest.mark.parametrize(
+ 'func',
+ [
+ make_xp_pytest_param(ndimage.binary_erosion),
+ make_xp_pytest_param(ndimage.binary_dilation),
+ make_xp_pytest_param(ndimage.binary_opening),
+ make_xp_pytest_param(ndimage.binary_closing),
+ ],
+)
+@pytest.mark.parametrize('iterations', [1, 5])
+@pytest.mark.parametrize('brute_force', [False, True])
+def test_binary_input_as_output(func, iterations, brute_force, xp):
+ rstate = np.random.RandomState(123)
+ data = rstate.randint(low=0, high=2, size=100).astype(bool)
+ data = xp.asarray(data)
+
+ # input data is not modified
+ data_orig = data.copy()
+ expected = func(data, brute_force=brute_force, iterations=iterations)
+ xp_assert_equal(data, data_orig)
+
+ # data should now contain the expected result
+ func(data, brute_force=brute_force, iterations=iterations, output=data)
+ xp_assert_equal(data, expected)
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="inplace output= is numpy-specific")
+@make_xp_test_case(ndimage.binary_hit_or_miss)
+def test_binary_hit_or_miss_input_as_output(xp):
+ rstate = np.random.RandomState(123)
+ data = rstate.randint(low=0, high=2, size=100).astype(bool)
+ data = xp.asarray(data)
+
+ # input data is not modified
+ data_orig = data.copy()
+ expected = ndimage.binary_hit_or_miss(data)
+ xp_assert_equal(data, data_orig)
+
+ # data should now contain the expected result
+ ndimage.binary_hit_or_miss(data, output=data)
+ xp_assert_equal(data, expected)
+
+
+@make_xp_test_case(ndimage.distance_transform_cdt)
+def test_distance_transform_cdt_invalid_metric(xp):
+ msg = 'invalid metric provided'
+ with pytest.raises(ValueError, match=msg):
+ ndimage.distance_transform_cdt(xp.ones((5, 5)),
+ metric="garbage")
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..e857e879c5e507c203cc83cd3807835e477f2757
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py
@@ -0,0 +1,77 @@
+import pytest
+
+import numpy as np
+from .._ni_support import _get_output
+
+
+@pytest.mark.parametrize(
+ 'dtype',
+ [
+ # String specifiers
+ 'f4', 'float32', 'complex64', 'complex128',
+ # Type and dtype specifiers
+ np.float32, float, np.dtype('f4'),
+ # Derive from input
+ None,
+ ],
+)
+def test_get_output_basic(dtype):
+ shape = (2, 3)
+
+ input_ = np.zeros(shape, dtype='float32')
+
+ # For None, derive dtype from input
+ expected_dtype = 'float32' if dtype is None else dtype
+
+ # Output is dtype-specifier, retrieve shape from input
+ result = _get_output(dtype, input_)
+ assert result.shape == shape
+ assert result.dtype == np.dtype(expected_dtype)
+
+ # Output is dtype specifier, with explicit shape, overriding input
+ result = _get_output(dtype, input_, shape=(3, 2))
+ assert result.shape == (3, 2)
+ assert result.dtype == np.dtype(expected_dtype)
+
+ # Output is pre-allocated array, return directly
+ output = np.zeros(shape, dtype=dtype)
+ result = _get_output(output, input_)
+ assert result is output
+
+
+def test_get_output_complex():
+ shape = (2, 3)
+
+ input_ = np.zeros(shape)
+
+ # None, promote input type to complex
+ result = _get_output(None, input_, complex_output=True)
+ assert result.shape == shape
+ assert result.dtype == np.dtype('complex128')
+
+ # Explicit type, promote type to complex
+ with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
+ result = _get_output(float, input_, complex_output=True)
+ assert result.shape == shape
+ assert result.dtype == np.dtype('complex128')
+
+ # String specifier, simply verify complex output
+ result = _get_output('complex64', input_, complex_output=True)
+ assert result.shape == shape
+ assert result.dtype == np.dtype('complex64')
+
+
+def test_get_output_error_cases():
+ input_ = np.zeros((2, 3), 'float32')
+
+ # Two separate paths can raise the same error
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
+ _get_output('float32', input_, complex_output=True)
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
+ _get_output(np.zeros((2, 3)), input_, complex_output=True)
+
+ with pytest.raises(RuntimeError, match='output must have numeric dtype'):
+ _get_output('void', input_)
+
+ with pytest.raises(RuntimeError, match='shape not correct'):
+ _get_output(np.zeros((3, 2)), input_)
diff --git a/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_splines.py b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9fc307871c288013a298ff719609ca5be39e85a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/ndimage/tests/test_splines.py
@@ -0,0 +1,85 @@
+"""Tests for spline filtering."""
+import pytest
+
+import numpy as np
+from scipy._lib._array_api import (
+ assert_almost_equal, xp_assert_close, make_xp_test_case,
+)
+from scipy import ndimage
+
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+
+def get_spline_knot_values(order):
+ """Knot values to the right of a B-spline's center."""
+ knot_values = {0: [1],
+ 1: [1],
+ 2: [6, 1],
+ 3: [4, 1],
+ 4: [230, 76, 1],
+ 5: [66, 26, 1]}
+
+ return knot_values[order]
+
+
+def make_spline_knot_matrix(xp, n, order, mode='mirror'):
+ """Matrix to invert to find the spline coefficients."""
+ knot_values = get_spline_knot_values(order)
+
+ # NB: do computations with numpy, convert to xp as the last step only
+
+ matrix = np.zeros((n, n))
+ for diag, knot_value in enumerate(knot_values):
+ indices = np.arange(diag, n)
+ if diag == 0:
+ matrix[indices, indices] = knot_value
+ else:
+ matrix[indices, indices - diag] = knot_value
+ matrix[indices - diag, indices] = knot_value
+
+ knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:])
+
+ if mode == 'mirror':
+ start, step = 1, 1
+ elif mode == 'reflect':
+ start, step = 0, 1
+ elif mode == 'grid-wrap':
+ start, step = -1, -1
+ else:
+ raise ValueError(f'unsupported mode {mode}')
+
+ for row in range(len(knot_values) - 1):
+ for idx, knot_value in enumerate(knot_values[row + 1:]):
+ matrix[row, start + step*idx] += knot_value
+ matrix[-row - 1, -start - 1 - step*idx] += knot_value
+
+ return xp.asarray(matrix / knot_values_sum)
+
+
+@make_xp_test_case(ndimage.spline_filter1d) # type:ignore[attr-defined]
+@pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5])
+@pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect'])
+def test_spline_filter_vs_matrix_solution(order, mode, xp):
+ n = 100
+ eye = xp.eye(n, dtype=xp.float64)
+ spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order,
+ mode=mode)
+ spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order,
+ mode=mode)
+ matrix = make_spline_knot_matrix(xp, n, order, mode=mode)
+ assert_almost_equal(eye, spline_filter_axis_0 @ matrix)
+ assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T)
+
+
+@make_xp_test_case(ndimage.spline_filter1d) # type:ignore[attr-defined]
+@xfail_xp_backends("cupy", reason="CuPy spline_filter1d has the same aliasing bug")
+@pytest.mark.parametrize('order', [2, 3, 4, 5])
+@pytest.mark.parametrize('n', [2, 3, 4, 5])
+def test_spline_filter_reflect_small_n(order, n, xp):
+ # Regression test for gh-24550: the causal reflect initialization had an
+ # aliasing bug where c[0] was read back after mutation via c[n-1-i].
+ # For large n the error is negligible, but for small n it is significant.
+ eye = xp.eye(n, dtype=xp.float64)
+ filtered = ndimage.spline_filter1d(eye, axis=0, order=order, mode='reflect')
+ matrix = make_spline_knot_matrix(xp, n, order, mode='reflect')
+ xp_assert_close(filtered @ matrix, eye, atol=1e-12)
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/__init__.py b/.venv/lib/python3.12/site-packages/scipy/odr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e3c3addc07bc8797f7fcbdf42ca72dc6f4d424f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/__init__.py
@@ -0,0 +1,177 @@
+"""
+=================================================
+Orthogonal distance regression (:mod:`scipy.odr`)
+=================================================
+
+.. currentmodule:: scipy.odr
+
+.. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ The following example shows a brief comparison of the APIs::
+
+ import numpy as np
+ import scipy.odr
+ import odrpack
+
+ # Classic "Pearson data" that motivates ODR.
+ # Errors are in both variables, and if you don't account for this,
+ # doing a linear fit of X vs. Y or Y vs. X will give you quite
+ # different results.
+ p_x = np.array([0., .9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4])
+ p_y = np.array([5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5])
+ p_sx = np.array([.03, .03, .04, .035, .07, .11, .13, .22, .74, 1.])
+ p_sy = np.array([1., .74, .5, .35, .22, .22, .12, .12, .1, .04])
+
+ # Old-style
+ # The RealData class takes care of details like turning
+ # standard-deviation error bars into weights.
+ p_dat = scipy.odr.RealData(p_x, p_y, sx=p_sx, sy=p_sy)
+ # Note, parameters come before `x` in scipy.odr
+ p_mod = scipy.odr.Model(lambda beta, x: beta[0] + beta[1]*x)
+ p_odr = scipy.odr.ODR(p_dat, p_mod, beta0=[1., 1.])
+ old_out = p_odr.run()
+
+ # New-style
+ # Parameters come after data, in the new API.
+ # We must convert the error bars into weights ourselves.
+ new_out = odrpack.odr_fit(lambda x, beta: beta[0] + beta[1] * x,
+ p_x, p_y, beta0=np.array([1.0, 1.0]),
+ weight_x=p_sx**-2, weight_y=p_sy**-2)
+
+ assert np.isclose(old_out.beta, new_out.beta).all()
+
+
+Package Content
+===============
+
+.. autosummary::
+ :toctree: generated/
+
+ Data -- The data to fit.
+ RealData -- Data with weights as actual std. dev.s and/or covariances.
+ Model -- Stores information about the function to be fit.
+ ODR -- Gathers all info & manages the main fitting routine.
+ Output -- Result from the fit.
+ odr -- Low-level function for ODR.
+
+ OdrWarning -- Warning about potential problems when running ODR.
+ OdrError -- Error exception.
+ OdrStop -- Stop exception.
+
+ polynomial -- Factory function for a general polynomial model.
+ exponential -- Exponential model
+ multilinear -- Arbitrary-dimensional linear model
+ unilinear -- Univariate linear model
+ quadratic -- Quadratic model
+
+Usage information
+=================
+
+Introduction
+------------
+
+Why Orthogonal Distance Regression (ODR)? Sometimes one has
+measurement errors in the explanatory (a.k.a., "independent")
+variable(s), not just the response (a.k.a., "dependent") variable(s).
+Ordinary Least Squares (OLS) fitting procedures treat the data for
+explanatory variables as fixed, i.e., not subject to error of any kind.
+Furthermore, OLS procedures require that the response variables be an
+explicit function of the explanatory variables; sometimes making the
+equation explicit is impractical and/or introduces errors. ODR can
+handle both of these cases with ease, and can even reduce to the OLS
+case if that is sufficient for the problem.
+
+ODRPACK is a FORTRAN-77 library for performing ODR with possibly
+non-linear fitting functions. It uses a modified trust-region
+Levenberg-Marquardt-type algorithm [1]_ to estimate the function
+parameters. The fitting functions are provided by Python functions
+operating on NumPy arrays. The required derivatives may be provided
+by Python functions as well, or may be estimated numerically. ODRPACK
+can do explicit or implicit ODR fits, or it can do OLS. Input and
+output variables may be multidimensional. Weights can be provided to
+account for different variances of the observations, and even
+covariances between dimensions of the variables.
+
+The `scipy.odr` package offers an object-oriented interface to
+ODRPACK, in addition to the low-level `odr` function.
+
+Additional background information about ODRPACK can be found in the
+`ODRPACK User's Guide
+`_, reading
+which is recommended.
+
+Basic usage
+-----------
+
+1. Define the function you want to fit against.::
+
+ def f(B, x):
+ '''Linear function y = m*x + b'''
+ # B is a vector of the parameters.
+ # x is an array of the current x values.
+ # x is in the same format as the x passed to Data or RealData.
+ #
+ # Return an array in the same format as y passed to Data or RealData.
+ return B[0]*x + B[1]
+
+2. Create a Model.::
+
+ linear = Model(f)
+
+3. Create a Data or RealData instance.::
+
+ mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2))
+
+ or, when the actual covariances are known::
+
+ mydata = RealData(x, y, sx=sx, sy=sy)
+
+4. Instantiate ODR with your data, model and initial parameter estimate.::
+
+ myodr = ODR(mydata, linear, beta0=[1., 2.])
+
+5. Run the fit.::
+
+ myoutput = myodr.run()
+
+6. Examine output.::
+
+ myoutput.pprint()
+
+
+References
+----------
+.. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression,"
+ in "Statistical analysis of measurement error models and
+ applications: proceedings of the AMS-IMS-SIAM joint summer research
+ conference held June 10-16, 1989," Contemporary Mathematics,
+ vol. 112, pg. 186, 1990.
+
+"""
+# version: 0.7
+# author: Robert Kern
+# date: 2006-09-21
+
+from ._odrpack import *
+from ._models import *
+from . import _add_newdocs
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import models, odrpack
+
+__all__ = [s for s in dir()
+ if not (s.startswith('_') or s in ('odr_stop', 'odr_error'))]
+
+import warnings
+msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
+warnings.warn(msg, DeprecationWarning, stacklevel=2)
+del warnings
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..d0caaf761499b0e6fb9a27bb7761397f64433210
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a03bb0e4369c150cfbbea4dcc52ebc441cc0acf2dee44e3cc14d7dd020b53675
+size 630745
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/_add_newdocs.py b/.venv/lib/python3.12/site-packages/scipy/odr/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3961b7623e88affeb7514fd702124319a495722e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/_add_newdocs.py
@@ -0,0 +1,39 @@
+from numpy.lib import add_newdoc
+
+add_newdoc('scipy.odr', 'odr',
+ """
+ odr(fcn, beta0, y, x, we=None, wd=None, fjacb=None, fjacd=None, extra_args=None,
+ ifixx=None, ifixb=None, job=0, iprint=0, errfile=None, rptfile=None, ndigit=0,
+ taufac=0.0, sstol=-1.0, partol=-1.0, maxit=-1, stpb=None, stpd=None, sclb=None,
+ scld=None, work=None, iwork=None, full_output=0)
+
+ Low-level function for ODR.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ See Also
+ --------
+ ODR : The ODR class gathers all information and coordinates the running of the
+ main fitting routine.
+ Model : The Model class stores information about the function you wish to fit.
+ Data : The data to fit.
+ RealData : Data with weights as actual std. dev.s and/or covariances.
+
+ Notes
+ -----
+ This is a function performing the same operation as the `ODR`,
+ `Model`, and `Data` classes together. The parameters of this
+ function are explained in the class documentation.
+
+ """)
+
+add_newdoc('scipy.odr.__odrpack', '_set_exceptions',
+ """
+ _set_exceptions(odr_error, odr_stop)
+
+ Internal function: set exception classes.
+
+ """)
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/_models.py b/.venv/lib/python3.12/site-packages/scipy/odr/_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..cabdcbb1987cd9a00a6ffeeb70a19a50ba480df4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/_models.py
@@ -0,0 +1,333 @@
+""" Collection of Model instances for use with the odrpack fitting package.
+"""
+import numpy as np
+from scipy.odr._odrpack import Model
+
+__all__ = ['Model', 'exponential', 'multilinear', 'unilinear', 'quadratic',
+ 'polynomial']
+
+
+def _lin_fcn(B, x):
+ a, b = B[0], B[1:]
+ b = b.reshape((b.shape[0], 1))
+
+ return a + (x*b).sum(axis=0)
+
+
+def _lin_fjb(B, x):
+ a = np.ones(x.shape[-1], float)
+ res = np.concatenate((a, x.ravel()))
+ return res.reshape((B.shape[-1], x.shape[-1]))
+
+
+def _lin_fjd(B, x):
+ b = B[1:]
+ b = np.repeat(b, (x.shape[-1],)*b.shape[-1], axis=0)
+ return b.reshape(x.shape)
+
+
+def _lin_est(data):
+ # Eh. The answer is analytical, so just return all ones.
+ # Don't return zeros since that will interfere with
+ # ODRPACK's auto-scaling procedures.
+
+ if len(data.x.shape) == 2:
+ m = data.x.shape[0]
+ else:
+ m = 1
+
+ return np.ones((m + 1,), float)
+
+
+def _poly_fcn(B, x, powers):
+ a, b = B[0], B[1:]
+ b = b.reshape((b.shape[0], 1))
+
+ return a + np.sum(b * np.power(x, powers), axis=0)
+
+
+def _poly_fjacb(B, x, powers):
+ res = np.concatenate((np.ones(x.shape[-1], float),
+ np.power(x, powers).flat))
+ return res.reshape((B.shape[-1], x.shape[-1]))
+
+
+def _poly_fjacd(B, x, powers):
+ b = B[1:]
+ b = b.reshape((b.shape[0], 1))
+
+ b = b * powers
+
+ return np.sum(b * np.power(x, powers-1), axis=0)
+
+
+def _exp_fcn(B, x):
+ return B[0] + np.exp(B[1] * x)
+
+
+def _exp_fjd(B, x):
+ return B[1] * np.exp(B[1] * x)
+
+
+def _exp_fjb(B, x):
+ res = np.concatenate((np.ones(x.shape[-1], float), x * np.exp(B[1] * x)))
+ return res.reshape((2, x.shape[-1]))
+
+
+def _exp_est(data):
+ # Eh.
+ return np.array([1., 1.])
+
+
+class _MultilinearModel(Model):
+ r"""
+ Arbitrary-dimensional linear model
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+
+ This model is defined by :math:`y=\beta_0 + \sum_{i=1}^m \beta_i x_i`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with an arbitrary
+ dimensional linear model:
+
+ >>> from scipy import odr
+ >>> import numpy as np
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = 10.0 + 5.0 * x
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, odr.multilinear)
+ >>> output = odr_obj.run()
+ >>> print(output.beta)
+ [10. 5.]
+
+ """
+
+ def __init__(self):
+ super().__init__(
+ _lin_fcn, fjacb=_lin_fjb, fjacd=_lin_fjd, estimate=_lin_est,
+ meta={'name': 'Arbitrary-dimensional Linear',
+ 'equ': 'y = B_0 + Sum[i=1..m, B_i * x_i]',
+ 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^m \beta_i x_i$'})
+
+
+multilinear = _MultilinearModel()
+
+
+def polynomial(order):
+ """
+ Factory function for a general polynomial model.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Parameters
+ ----------
+ order : int or sequence
+ If an integer, it becomes the order of the polynomial to fit. If
+ a sequence of numbers, then these are the explicit powers in the
+ polynomial.
+ A constant term (power 0) is always included, so don't include 0.
+ Thus, polynomial(n) is equivalent to polynomial(range(1, n+1)).
+
+ Returns
+ -------
+ polynomial : Model instance
+ Model instance.
+
+ Examples
+ --------
+ We can fit an input data using orthogonal distance regression (ODR) with
+ a polynomial model:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy import odr
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = np.sin(x)
+ >>> poly_model = odr.polynomial(3) # using third order polynomial model
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, poly_model)
+ >>> output = odr_obj.run() # running ODR fitting
+ >>> poly = np.poly1d(output.beta[::-1])
+ >>> poly_y = poly(x)
+ >>> plt.plot(x, y, label="input data")
+ >>> plt.plot(x, poly_y, label="polynomial ODR")
+ >>> plt.legend()
+ >>> plt.show()
+
+ """
+
+ powers = np.asarray(order)
+ if powers.shape == ():
+ # Scalar.
+ powers = np.arange(1, powers + 1)
+
+ powers = powers.reshape((len(powers), 1))
+ len_beta = len(powers) + 1
+
+ def _poly_est(data, len_beta=len_beta):
+ # Eh. Ignore data and return all ones.
+ return np.ones((len_beta,), float)
+
+ return Model(_poly_fcn, fjacd=_poly_fjacd, fjacb=_poly_fjacb,
+ estimate=_poly_est, extra_args=(powers,),
+ meta={'name': 'Sorta-general Polynomial',
+ 'equ': 'y = B_0 + Sum[i=1..%s, B_i * (x**i)]' % (len_beta-1),
+ 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^{%s} \beta_i x^i$' %
+ (len_beta-1)})
+
+
+class _ExponentialModel(Model):
+ r"""
+ Exponential model
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ This model is defined by :math:`y=\beta_0 + e^{\beta_1 x}`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with an exponential model:
+
+ >>> from scipy import odr
+ >>> import numpy as np
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = -10.0 + np.exp(0.5*x)
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, odr.exponential)
+ >>> output = odr_obj.run()
+ >>> print(output.beta)
+ [-10. 0.5]
+
+ """
+
+ def __init__(self):
+ super().__init__(_exp_fcn, fjacd=_exp_fjd, fjacb=_exp_fjb,
+ estimate=_exp_est,
+ meta={'name': 'Exponential',
+ 'equ': 'y= B_0 + exp(B_1 * x)',
+ 'TeXequ': r'$y=\beta_0 + e^{\beta_1 x}$'})
+
+
+exponential = _ExponentialModel()
+
+
+def _unilin(B, x):
+ return x*B[0] + B[1]
+
+
+def _unilin_fjd(B, x):
+ return np.ones(x.shape, float) * B[0]
+
+
+def _unilin_fjb(B, x):
+ _ret = np.concatenate((x, np.ones(x.shape, float)))
+ return _ret.reshape((2,) + x.shape)
+
+
+def _unilin_est(data):
+ return (1., 1.)
+
+
+def _quadratic(B, x):
+ return x*(x*B[0] + B[1]) + B[2]
+
+
+def _quad_fjd(B, x):
+ return 2*x*B[0] + B[1]
+
+
+def _quad_fjb(B, x):
+ _ret = np.concatenate((x*x, x, np.ones(x.shape, float)))
+ return _ret.reshape((3,) + x.shape)
+
+
+def _quad_est(data):
+ return (1.,1.,1.)
+
+
+class _UnilinearModel(Model):
+ r"""
+ Univariate linear model
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ This model is defined by :math:`y = \beta_0 x + \beta_1`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with a unilinear model:
+
+ >>> from scipy import odr
+ >>> import numpy as np
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = 1.0 * x + 2.0
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, odr.unilinear)
+ >>> output = odr_obj.run()
+ >>> print(output.beta)
+ [1. 2.]
+
+ """
+
+ def __init__(self):
+ super().__init__(_unilin, fjacd=_unilin_fjd, fjacb=_unilin_fjb,
+ estimate=_unilin_est,
+ meta={'name': 'Univariate Linear',
+ 'equ': 'y = B_0 * x + B_1',
+ 'TeXequ': '$y = \\beta_0 x + \\beta_1$'})
+
+
+unilinear = _UnilinearModel()
+
+
+class _QuadraticModel(Model):
+ r"""
+ Quadratic model
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ This model is defined by :math:`y = \beta_0 x^2 + \beta_1 x + \beta_2`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with a quadratic model:
+
+ >>> from scipy import odr
+ >>> import numpy as np
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = 1.0 * x ** 2 + 2.0 * x + 3.0
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, odr.quadratic)
+ >>> output = odr_obj.run()
+ >>> print(output.beta)
+ [1. 2. 3.]
+
+ """
+
+ def __init__(self):
+ super().__init__(
+ _quadratic, fjacd=_quad_fjd, fjacb=_quad_fjb, estimate=_quad_est,
+ meta={'name': 'Quadratic',
+ 'equ': 'y = B_0*x**2 + B_1*x + B_2',
+ 'TeXequ': '$y = \\beta_0 x^2 + \\beta_1 x + \\beta_2'})
+
+
+quadratic = _QuadraticModel()
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/_odrpack.py b/.venv/lib/python3.12/site-packages/scipy/odr/_odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ce825eb38ae8182ac06f6d05c76a58b784cd715
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/_odrpack.py
@@ -0,0 +1,1200 @@
+"""
+Python wrappers for Orthogonal Distance Regression (ODRPACK).
+
+Notes
+=====
+
+* Array formats -- FORTRAN stores its arrays in memory column first, i.e., an
+ array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently,
+ NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For
+ efficiency and convenience, the input and output arrays of the fitting
+ function (and its Jacobians) are passed to FORTRAN without transposition.
+ Therefore, where the ODRPACK documentation says that the X array is of shape
+ (N, M), it will be passed to the Python function as an array of shape (M, N).
+ If M==1, the 1-D case, then nothing matters; if M>1, then your
+ Python functions will be dealing with arrays that are indexed in reverse of
+ the ODRPACK documentation. No real issue, but watch out for your indexing of
+ the Jacobians: the i,jth elements (@f_i/@x_j) evaluated at the nth
+ observation will be returned as jacd[j, i, n]. Except for the Jacobians, it
+ really is easier to deal with x[0] and x[1] than x[:,0] and x[:,1]. Of course,
+ you can always use the transpose() function from SciPy explicitly.
+
+* Examples -- See the accompanying file test/test.py for examples of how to set
+ up fits of your own. Some are taken from the User's Guide; some are from
+ other sources.
+
+* Models -- Some common models are instantiated in the accompanying module
+ models.py . Contributions are welcome.
+
+Credits
+=======
+
+* Thanks to Arnold Moene and Gerard Vermeulen for fixing some killer bugs.
+
+Robert Kern
+robert.kern@gmail.com
+
+"""
+import os
+from threading import Lock
+
+import numpy as np
+from warnings import warn
+from scipy.odr import __odrpack
+
+__all__ = ['odr', 'OdrWarning', 'OdrError', 'OdrStop',
+ 'Data', 'RealData', 'Model', 'Output', 'ODR',
+ 'odr_error', 'odr_stop']
+
+odr = __odrpack.odr
+ODR_LOCK = Lock()
+
+
+class OdrWarning(UserWarning):
+ """
+ Warning indicating that the data passed into
+ ODR will cause problems when passed into 'odr'
+ that the user should be aware of.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ """
+ pass
+
+
+class OdrError(Exception):
+ """
+ Exception indicating an error in fitting.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+
+ This is raised by `~scipy.odr.odr` if an error occurs during fitting.
+ """
+ pass
+
+
+class OdrStop(Exception):
+ """
+ Exception stopping fitting.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+
+ You can raise this exception in your objective function to tell
+ `~scipy.odr.odr` to stop fitting.
+ """
+ pass
+
+
+# Backwards compatibility
+odr_error = OdrError
+odr_stop = OdrStop
+
+__odrpack._set_exceptions(OdrError, OdrStop)
+
+
+def _conv(obj, dtype=None):
+ """ Convert an object to the preferred form for input to the odr routine.
+ """
+
+ if obj is None:
+ return obj
+ else:
+ if dtype is None:
+ obj = np.asarray(obj)
+ else:
+ obj = np.asarray(obj, dtype)
+ if obj.shape == ():
+ # Scalar.
+ return obj.dtype.type(obj)
+ else:
+ return obj
+
+
+def _report_error(info):
+ """ Interprets the return code of the odr routine.
+
+ Parameters
+ ----------
+ info : int
+ The return code of the odr routine.
+
+ Returns
+ -------
+ problems : list(str)
+ A list of messages about why the odr() routine stopped.
+ """
+
+ stopreason = ('Blank',
+ 'Sum of squares convergence',
+ 'Parameter convergence',
+ 'Both sum of squares and parameter convergence',
+ 'Iteration limit reached')[info % 5]
+
+ if info >= 5:
+ # questionable results or fatal error
+
+ I = (info//10000 % 10,
+ info//1000 % 10,
+ info//100 % 10,
+ info//10 % 10,
+ info % 10)
+ problems = []
+
+ if I[0] == 0:
+ if I[1] != 0:
+ problems.append('Derivatives possibly not correct')
+ if I[2] != 0:
+ problems.append('Error occurred in callback')
+ if I[3] != 0:
+ problems.append('Problem is not full rank at solution')
+ problems.append(stopreason)
+ elif I[0] == 1:
+ if I[1] != 0:
+ problems.append('N < 1')
+ if I[2] != 0:
+ problems.append('M < 1')
+ if I[3] != 0:
+ problems.append('NP < 1 or NP > N')
+ if I[4] != 0:
+ problems.append('NQ < 1')
+ elif I[0] == 2:
+ if I[1] != 0:
+ problems.append('LDY and/or LDX incorrect')
+ if I[2] != 0:
+ problems.append('LDWE, LD2WE, LDWD, and/or LD2WD incorrect')
+ if I[3] != 0:
+ problems.append('LDIFX, LDSTPD, and/or LDSCLD incorrect')
+ if I[4] != 0:
+ problems.append('LWORK and/or LIWORK too small')
+ elif I[0] == 3:
+ if I[1] != 0:
+ problems.append('STPB and/or STPD incorrect')
+ if I[2] != 0:
+ problems.append('SCLB and/or SCLD incorrect')
+ if I[3] != 0:
+ problems.append('WE incorrect')
+ if I[4] != 0:
+ problems.append('WD incorrect')
+ elif I[0] == 4:
+ problems.append('Error in derivatives')
+ elif I[0] == 5:
+ problems.append('Error occurred in callback')
+ elif I[0] == 6:
+ problems.append('Numerical error detected')
+
+ return problems
+
+ else:
+ return [stopreason]
+
+
+class Data:
+ """
+ The data to fit.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Parameters
+ ----------
+ x : array_like
+ Observed data for the independent variable of the regression
+ y : array_like, optional
+ If array-like, observed data for the dependent variable of the
+ regression. A scalar input implies that the model to be used on
+ the data is implicit.
+ we : array_like, optional
+ If `we` is a scalar, then that value is used for all data points (and
+ all dimensions of the response variable).
+ If `we` is a rank-1 array of length q (the dimensionality of the
+ response variable), then this vector is the diagonal of the covariant
+ weighting matrix for all data points.
+ If `we` is a rank-1 array of length n (the number of data points), then
+ the i'th element is the weight for the i'th response variable
+ observation (single-dimensional only).
+ If `we` is a rank-2 array of shape (q, q), then this is the full
+ covariant weighting matrix broadcast to each observation.
+ If `we` is a rank-2 array of shape (q, n), then `we[:,i]` is the
+ diagonal of the covariant weighting matrix for the i'th observation.
+ If `we` is a rank-3 array of shape (q, q, n), then `we[:,:,i]` is the
+ full specification of the covariant weighting matrix for each
+ observation.
+ If the fit is implicit, then only a positive scalar value is used.
+ wd : array_like, optional
+ If `wd` is a scalar, then that value is used for all data points
+ (and all dimensions of the input variable). If `wd` = 0, then the
+ covariant weighting matrix for each observation is set to the identity
+ matrix (so each dimension of each observation has the same weight).
+ If `wd` is a rank-1 array of length m (the dimensionality of the input
+ variable), then this vector is the diagonal of the covariant weighting
+ matrix for all data points.
+ If `wd` is a rank-1 array of length n (the number of data points), then
+ the i'th element is the weight for the ith input variable observation
+ (single-dimensional only).
+ If `wd` is a rank-2 array of shape (m, m), then this is the full
+ covariant weighting matrix broadcast to each observation.
+ If `wd` is a rank-2 array of shape (m, n), then `wd[:,i]` is the
+ diagonal of the covariant weighting matrix for the ith observation.
+ If `wd` is a rank-3 array of shape (m, m, n), then `wd[:,:,i]` is the
+ full specification of the covariant weighting matrix for each
+ observation.
+ fix : array_like of ints, optional
+ The `fix` argument is the same as ifixx in the class ODR. It is an
+ array of integers with the same shape as data.x that determines which
+ input observations are treated as fixed. One can use a sequence of
+ length m (the dimensionality of the input observations) to fix some
+ dimensions for all observations. A value of 0 fixes the observation,
+ a value > 0 makes it free.
+ meta : dict, optional
+ Free-form dictionary for metadata.
+
+ Notes
+ -----
+ Each argument is attached to the member of the instance of the same name.
+ The structures of `x` and `y` are described in the Model class docstring.
+ If `y` is an integer, then the Data instance can only be used to fit with
+ implicit models where the dimensionality of the response is equal to the
+ specified value of `y`.
+
+ The `we` argument weights the effect a deviation in the response variable
+ has on the fit. The `wd` argument weights the effect a deviation in the
+ input variable has on the fit. To handle multidimensional inputs and
+ responses easily, the structure of these arguments has the n'th
+ dimensional axis first. These arguments heavily use the structured
+ arguments feature of ODRPACK to conveniently and flexibly support all
+ options. See the ODRPACK User's Guide for a full explanation of how these
+ weights are used in the algorithm. Basically, a higher value of the weight
+ for a particular data point makes a deviation at that point more
+ detrimental to the fit.
+
+ """
+
+ def __init__(self, x, y=None, we=None, wd=None, fix=None, meta=None):
+ self.x = _conv(x)
+
+ if not isinstance(self.x, np.ndarray):
+ raise ValueError("Expected an 'ndarray' of data for 'x', "
+ f"but instead got data of type '{type(self.x).__name__}'")
+
+ self.y = _conv(y)
+ self.we = _conv(we)
+ self.wd = _conv(wd)
+ self.fix = _conv(fix)
+ self.meta = {} if meta is None else meta
+
+ def set_meta(self, **kwds):
+ """ Update the metadata dictionary with the keywords and data provided
+ by keywords.
+
+ Examples
+ --------
+ ::
+
+ data.set_meta(lab="Ph 7; Lab 26", title="Ag110 + Ag108 Decay")
+ """
+
+ self.meta.update(kwds)
+
+ def __getattr__(self, attr):
+ """ Dispatch attribute access to the metadata dictionary.
+ """
+ if attr != "meta" and attr in self.meta:
+ return self.meta[attr]
+ else:
+ raise AttributeError(f"'{attr}' not in metadata")
+
+
+class RealData(Data):
+ """
+ The data, with weightings as actual standard deviations and/or
+ covariances.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Parameters
+ ----------
+ x : array_like
+ Observed data for the independent variable of the regression
+ y : array_like, optional
+ If array-like, observed data for the dependent variable of the
+ regression. A scalar input implies that the model to be used on
+ the data is implicit.
+ sx : array_like, optional
+ Standard deviations of `x`.
+ `sx` are standard deviations of `x` and are converted to weights by
+ dividing 1.0 by their squares.
+ sy : array_like, optional
+ Standard deviations of `y`.
+ `sy` are standard deviations of `y` and are converted to weights by
+ dividing 1.0 by their squares.
+ covx : array_like, optional
+ Covariance of `x`
+ `covx` is an array of covariance matrices of `x` and are converted to
+ weights by performing a matrix inversion on each observation's
+ covariance matrix.
+ covy : array_like, optional
+ Covariance of `y`
+ `covy` is an array of covariance matrices and are converted to
+ weights by performing a matrix inversion on each observation's
+ covariance matrix.
+ fix : array_like, optional
+ The argument and member fix is the same as Data.fix and ODR.ifixx:
+ It is an array of integers with the same shape as `x` that
+ determines which input observations are treated as fixed. One can
+ use a sequence of length m (the dimensionality of the input
+ observations) to fix some dimensions for all observations. A value
+ of 0 fixes the observation, a value > 0 makes it free.
+ meta : dict, optional
+ Free-form dictionary for metadata.
+
+ Notes
+ -----
+ The weights `wd` and `we` are computed from provided values as follows:
+
+ `sx` and `sy` are converted to weights by dividing 1.0 by their squares.
+ For example, ``wd = 1./np.power(`sx`, 2)``.
+
+ `covx` and `covy` are arrays of covariance matrices and are converted to
+ weights by performing a matrix inversion on each observation's covariance
+ matrix. For example, ``we[i] = np.linalg.inv(covy[i])``.
+
+ These arguments follow the same structured argument conventions as wd and
+ we only restricted by their natures: `sx` and `sy` can't be rank-3, but
+ `covx` and `covy` can be.
+
+ Only set *either* `sx` or `covx` (not both). Setting both will raise an
+ exception. Same with `sy` and `covy`.
+
+ """
+
+ def __init__(self, x, y=None, sx=None, sy=None, covx=None, covy=None,
+ fix=None, meta=None):
+ if (sx is not None) and (covx is not None):
+ raise ValueError("cannot set both sx and covx")
+ if (sy is not None) and (covy is not None):
+ raise ValueError("cannot set both sy and covy")
+
+ # Set flags for __getattr__
+ self._ga_flags = {}
+ if sx is not None:
+ self._ga_flags['wd'] = 'sx'
+ else:
+ self._ga_flags['wd'] = 'covx'
+ if sy is not None:
+ self._ga_flags['we'] = 'sy'
+ else:
+ self._ga_flags['we'] = 'covy'
+
+ self.x = _conv(x)
+
+ if not isinstance(self.x, np.ndarray):
+ raise ValueError("Expected an 'ndarray' of data for 'x', "
+ f"but instead got data of type '{type(self.x).__name__}'")
+
+ self.y = _conv(y)
+ self.sx = _conv(sx)
+ self.sy = _conv(sy)
+ self.covx = _conv(covx)
+ self.covy = _conv(covy)
+ self.fix = _conv(fix)
+ self.meta = {} if meta is None else meta
+
+ def _sd2wt(self, sd):
+ """ Convert standard deviation to weights.
+ """
+
+ return 1./np.power(sd, 2)
+
+ def _cov2wt(self, cov):
+ """ Convert covariance matrix(-ices) to weights.
+ """
+
+ from scipy.linalg import inv
+
+ if len(cov.shape) == 2:
+ return inv(cov)
+ else:
+ weights = np.zeros(cov.shape, float)
+
+ for i in range(cov.shape[-1]): # n
+ weights[:,:,i] = inv(cov[:,:,i])
+
+ return weights
+
+ def __getattr__(self, attr):
+
+ if attr not in ('wd', 'we'):
+ if attr != "meta" and attr in self.meta:
+ return self.meta[attr]
+ else:
+ raise AttributeError(f"'{attr}' not in metadata")
+ else:
+ lookup_tbl = {('wd', 'sx'): (self._sd2wt, self.sx),
+ ('wd', 'covx'): (self._cov2wt, self.covx),
+ ('we', 'sy'): (self._sd2wt, self.sy),
+ ('we', 'covy'): (self._cov2wt, self.covy)}
+
+ func, arg = lookup_tbl[(attr, self._ga_flags[attr])]
+
+ if arg is not None:
+ return func(*(arg,))
+ else:
+ return None
+
+
+class Model:
+ """
+ The Model class stores information about the function you wish to fit.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ It stores the function itself, at the least, and optionally stores
+ functions which compute the Jacobians used during fitting. Also, one
+ can provide a function that will provide reasonable starting values
+ for the fit parameters possibly given the set of data.
+
+ Parameters
+ ----------
+ fcn : function
+ fcn(beta, x) --> y
+ fjacb : function
+ Jacobian of fcn wrt the fit parameters beta.
+
+ fjacb(beta, x) --> @f_i(x,B)/@B_j
+ fjacd : function
+ Jacobian of fcn wrt the (possibly multidimensional) input
+ variable.
+
+ fjacd(beta, x) --> @f_i(x,B)/@x_j
+ extra_args : tuple, optional
+ If specified, `extra_args` should be a tuple of extra
+ arguments to pass to `fcn`, `fjacb`, and `fjacd`. Each will be called
+ by `apply(fcn, (beta, x) + extra_args)`
+ estimate : array_like of rank-1
+ Provides estimates of the fit parameters from the data
+
+ estimate(data) --> estbeta
+ implicit : bool
+ If TRUE, specifies that the model
+ is implicit; i.e `fcn(beta, x)` ~= 0 and there is no y data to fit
+ against
+ meta : dict, optional
+ freeform dictionary of metadata for the model
+
+ Notes
+ -----
+ Note that the `fcn`, `fjacb`, and `fjacd` operate on NumPy arrays and
+ return a NumPy array. The `estimate` object takes an instance of the
+ Data class.
+
+ Here are the rules for the shapes of the argument and return
+ arrays of the callback functions:
+
+ `x`
+ if the input data is single-dimensional, then `x` is rank-1
+ array; i.e., ``x = array([1, 2, 3, ...]); x.shape = (n,)``
+ If the input data is multi-dimensional, then `x` is a rank-2 array;
+ i.e., ``x = array([[1, 2, ...], [2, 4, ...]]); x.shape = (m, n)``.
+ In all cases, it has the same shape as the input data array passed to
+ `~scipy.odr.odr`. `m` is the dimensionality of the input data,
+ `n` is the number of observations.
+ `y`
+ if the response variable is single-dimensional, then `y` is a
+ rank-1 array, i.e., ``y = array([2, 4, ...]); y.shape = (n,)``.
+ If the response variable is multi-dimensional, then `y` is a rank-2
+ array, i.e., ``y = array([[2, 4, ...], [3, 6, ...]]); y.shape =
+ (q, n)`` where `q` is the dimensionality of the response variable.
+ `beta`
+ rank-1 array of length `p` where `p` is the number of parameters;
+ i.e. ``beta = array([B_1, B_2, ..., B_p])``
+ `fjacb`
+ if the response variable is multi-dimensional, then the
+ return array's shape is ``(q, p, n)`` such that ``fjacb(beta,x)[l,k,i] =
+ d f_l(beta,x)/d B_k`` evaluated at the ith data point. If ``q == 1``, then
+ the return array is only rank-2 and with shape ``(p, n)``.
+ `fjacd`
+ as with fjacb, only the return array's shape is ``(q, m, n)``
+ such that ``fjacd(beta,x)[l,j,i] = d f_l(beta,x)/d X_j`` at the ith data
+ point. If ``q == 1``, then the return array's shape is ``(m, n)``. If
+ ``m == 1``, the shape is (q, n). If `m == q == 1`, the shape is ``(n,)``.
+
+ """
+
+ def __init__(self, fcn, fjacb=None, fjacd=None,
+ extra_args=None, estimate=None, implicit=0, meta=None):
+
+ self.fcn = fcn
+ self.fjacb = fjacb
+ self.fjacd = fjacd
+
+ if extra_args is not None:
+ extra_args = tuple(extra_args)
+
+ self.extra_args = extra_args
+ self.estimate = estimate
+ self.implicit = implicit
+ self.meta = meta if meta is not None else {}
+
+ def set_meta(self, **kwds):
+ """ Update the metadata dictionary with the keywords and data provided
+ here.
+
+ Examples
+ --------
+ set_meta(name="Exponential", equation="y = a exp(b x) + c")
+ """
+
+ self.meta.update(kwds)
+
+ def __getattr__(self, attr):
+ """ Dispatch attribute access to the metadata.
+ """
+
+ if attr != "meta" and attr in self.meta:
+ return self.meta[attr]
+ else:
+ raise AttributeError(f"'{attr}' not in metadata")
+
+
+class Output:
+ """
+ The Output class stores the output of an ODR run.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Attributes
+ ----------
+ beta : ndarray
+ Estimated parameter values, of shape (q,).
+ sd_beta : ndarray
+ Standard deviations of the estimated parameters, of shape (p,).
+ cov_beta : ndarray
+ Covariance matrix of the estimated parameters, of shape (p,p).
+ Note that this `cov_beta` is not scaled by the residual variance
+ `res_var`, whereas `sd_beta` is. This means
+ ``np.sqrt(np.diag(output.cov_beta * output.res_var))`` is the same
+ result as `output.sd_beta`.
+ delta : ndarray, optional
+ Array of estimated errors in input variables, of same shape as `x`.
+ eps : ndarray, optional
+ Array of estimated errors in response variables, of same shape as `y`.
+ xplus : ndarray, optional
+ Array of ``x + delta``.
+ y : ndarray, optional
+ Array ``y = fcn(x + delta)``.
+ res_var : float, optional
+ Residual variance.
+ sum_square : float, optional
+ Sum of squares error.
+ sum_square_delta : float, optional
+ Sum of squares of delta error.
+ sum_square_eps : float, optional
+ Sum of squares of eps error.
+ inv_condnum : float, optional
+ Inverse condition number (cf. ODRPACK UG p. 77).
+ rel_error : float, optional
+ Relative error in function values computed within fcn.
+ work : ndarray, optional
+ Final work array.
+ work_ind : dict, optional
+ Indices into work for drawing out values (cf. ODRPACK UG p. 83).
+ info : int, optional
+ Reason for returning, as output by ODRPACK (cf. ODRPACK UG p. 38).
+ stopreason : list of str, optional
+ `info` interpreted into English.
+
+ Notes
+ -----
+ Takes one argument for initialization, the return value from the
+ function `~scipy.odr.odr`. The attributes listed as "optional" above are
+ only present if `~scipy.odr.odr` was run with ``full_output=1``.
+
+ """
+
+ def __init__(self, output):
+ self.beta = output[0]
+ self.sd_beta = output[1]
+ self.cov_beta = output[2]
+
+ if len(output) == 4:
+ # full output
+ self.__dict__.update(output[3])
+ self.stopreason = _report_error(self.info)
+
+ def pprint(self):
+ """ Pretty-print important results.
+ """
+
+ print('Beta:', self.beta)
+ print('Beta Std Error:', self.sd_beta)
+ print('Beta Covariance:', self.cov_beta)
+ if hasattr(self, 'info'):
+ print('Residual Variance:',self.res_var)
+ print('Inverse Condition #:', self.inv_condnum)
+ print('Reason(s) for Halting:')
+ for r in self.stopreason:
+ print(f' {r}')
+
+
+class ODR:
+ """
+ The ODR class gathers all information and coordinates the running of the
+ main fitting routine.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Members of instances of the ODR class have the same names as the arguments
+ to the initialization routine.
+
+ Parameters
+ ----------
+ data : Data class instance
+ instance of the Data class
+ model : Model class instance
+ instance of the Model class
+
+ Other Parameters
+ ----------------
+ beta0 : array_like of rank-1
+ a rank-1 sequence of initial parameter values. Optional if
+ model provides an "estimate" function to estimate these values.
+ delta0 : array_like of floats of rank-1, optional
+ a (double-precision) float array to hold the initial values of
+ the errors in the input variables. Must be same shape as data.x
+ ifixb : array_like of ints of rank-1, optional
+ sequence of integers with the same length as beta0 that determines
+ which parameters are held fixed. A value of 0 fixes the parameter,
+ a value > 0 makes the parameter free.
+ ifixx : array_like of ints with same shape as data.x, optional
+ an array of integers with the same shape as data.x that determines
+ which input observations are treated as fixed. One can use a sequence
+ of length m (the dimensionality of the input observations) to fix some
+ dimensions for all observations. A value of 0 fixes the observation,
+ a value > 0 makes it free.
+ job : int, optional
+ an integer telling ODRPACK what tasks to perform. See p. 31 of the
+ ODRPACK User's Guide if you absolutely must set the value here. Use the
+ method set_job post-initialization for a more readable interface.
+ iprint : int, optional
+ an integer telling ODRPACK what to print. See pp. 33-34 of the
+ ODRPACK User's Guide if you absolutely must set the value here. Use the
+ method set_iprint post-initialization for a more readable interface.
+ errfile : str, optional
+ string with the filename to print ODRPACK errors to. If the file already
+ exists, an error will be thrown. The `overwrite` argument can be used to
+ prevent this. *Do Not Open This File Yourself!*
+ rptfile : str, optional
+ string with the filename to print ODRPACK summaries to. If the file
+ already exists, an error will be thrown. The `overwrite` argument can be
+ used to prevent this. *Do Not Open This File Yourself!*
+ ndigit : int, optional
+ integer specifying the number of reliable digits in the computation
+ of the function.
+ taufac : float, optional
+ float specifying the initial trust region. The default value is 1.
+ The initial trust region is equal to taufac times the length of the
+ first computed Gauss-Newton step. taufac must be less than 1.
+ sstol : float, optional
+ float specifying the tolerance for convergence based on the relative
+ change in the sum-of-squares. The default value is eps**(1/2) where eps
+ is the smallest value such that 1 + eps > 1 for double precision
+ computation on the machine. sstol must be less than 1.
+ partol : float, optional
+ float specifying the tolerance for convergence based on the relative
+ change in the estimated parameters. The default value is eps**(2/3) for
+ explicit models and ``eps**(1/3)`` for implicit models. partol must be less
+ than 1.
+ maxit : int, optional
+ integer specifying the maximum number of iterations to perform. For
+ first runs, maxit is the total number of iterations performed and
+ defaults to 50. For restarts, maxit is the number of additional
+ iterations to perform and defaults to 10.
+ stpb : array_like, optional
+ sequence (``len(stpb) == len(beta0)``) of relative step sizes to compute
+ finite difference derivatives wrt the parameters.
+ stpd : optional
+ array (``stpd.shape == data.x.shape`` or ``stpd.shape == (m,)``) of relative
+ step sizes to compute finite difference derivatives wrt the input
+ variable errors. If stpd is a rank-1 array with length m (the
+ dimensionality of the input variable), then the values are broadcast to
+ all observations.
+ sclb : array_like, optional
+ sequence (``len(stpb) == len(beta0)``) of scaling factors for the
+ parameters. The purpose of these scaling factors are to scale all of
+ the parameters to around unity. Normally appropriate scaling factors
+ are computed if this argument is not specified. Specify them yourself
+ if the automatic procedure goes awry.
+ scld : array_like, optional
+ array (scld.shape == data.x.shape or scld.shape == (m,)) of scaling
+ factors for the *errors* in the input variables. Again, these factors
+ are automatically computed if you do not provide them. If scld.shape ==
+ (m,), then the scaling factors are broadcast to all observations.
+ work : ndarray, optional
+ array to hold the double-valued working data for ODRPACK. When
+ restarting, takes the value of self.output.work.
+ iwork : ndarray, optional
+ array to hold the integer-valued working data for ODRPACK. When
+ restarting, takes the value of self.output.iwork.
+ overwrite : bool, optional
+ If it is True, output files defined by `errfile` and `rptfile` are
+ overwritten. The default is False.
+
+ Attributes
+ ----------
+ data : Data
+ The data for this fit
+ model : Model
+ The model used in fit
+ output : Output
+ An instance if the Output class containing all of the returned
+ data from an invocation of ODR.run() or ODR.restart()
+
+ """
+
+ def __init__(self, data, model, beta0=None, delta0=None, ifixb=None,
+ ifixx=None, job=None, iprint=None, errfile=None, rptfile=None,
+ ndigit=None, taufac=None, sstol=None, partol=None, maxit=None,
+ stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None,
+ overwrite=False):
+
+ self.data = data
+ self.model = model
+
+ if beta0 is None:
+ if self.model.estimate is not None:
+ self.beta0 = _conv(self.model.estimate(self.data))
+ else:
+ raise ValueError(
+ "must specify beta0 or provide an estimator with the model"
+ )
+ else:
+ self.beta0 = _conv(beta0)
+
+ if ifixx is None and data.fix is not None:
+ ifixx = data.fix
+
+ if overwrite:
+ # remove output files for overwriting.
+ if rptfile is not None and os.path.exists(rptfile):
+ os.remove(rptfile)
+ if errfile is not None and os.path.exists(errfile):
+ os.remove(errfile)
+
+ self.delta0 = _conv(delta0)
+ # These really are 32-bit integers in FORTRAN (gfortran), even on 64-bit
+ # platforms.
+ # XXX: some other FORTRAN compilers may not agree.
+ self.ifixx = _conv(ifixx, dtype=np.int32)
+ self.ifixb = _conv(ifixb, dtype=np.int32)
+ self.job = job
+ self.iprint = iprint
+ self.errfile = errfile
+ self.rptfile = rptfile
+ self.ndigit = ndigit
+ self.taufac = taufac
+ self.sstol = sstol
+ self.partol = partol
+ self.maxit = maxit
+ self.stpb = _conv(stpb)
+ self.stpd = _conv(stpd)
+ self.sclb = _conv(sclb)
+ self.scld = _conv(scld)
+ self.work = _conv(work)
+ self.iwork = _conv(iwork)
+
+ self.output = None
+
+ self._check()
+
+ def _check(self):
+ """ Check the inputs for consistency, but don't bother checking things
+ that the builtin function odr will check.
+ """
+
+ x_s = list(self.data.x.shape)
+
+ if isinstance(self.data.y, np.ndarray):
+ y_s = list(self.data.y.shape)
+ if self.model.implicit:
+ raise OdrError("an implicit model cannot use response data")
+ if self.job is not None and (self.job % 10) == 1:
+ raise OdrError("job parameter requests an implicit model,"
+ " but an explicit model was passed")
+ else:
+ # implicit model with q == self.data.y
+ y_s = [self.data.y, x_s[-1]]
+ if not self.model.implicit:
+ raise OdrError("an explicit model needs response data")
+ self.set_job(fit_type=1)
+
+ if x_s[-1] != y_s[-1]:
+ raise OdrError("number of observations do not match")
+
+ n = x_s[-1]
+
+ if len(x_s) == 2:
+ m = x_s[0]
+ else:
+ m = 1
+ if len(y_s) == 2:
+ q = y_s[0]
+ else:
+ q = 1
+
+ p = len(self.beta0)
+
+ # permissible output array shapes
+
+ fcn_perms = [(q, n)]
+ fjacd_perms = [(q, m, n)]
+ fjacb_perms = [(q, p, n)]
+
+ if q == 1:
+ fcn_perms.append((n,))
+ fjacd_perms.append((m, n))
+ fjacb_perms.append((p, n))
+ if m == 1:
+ fjacd_perms.append((q, n))
+ if p == 1:
+ fjacb_perms.append((q, n))
+ if m == q == 1:
+ fjacd_perms.append((n,))
+ if p == q == 1:
+ fjacb_perms.append((n,))
+
+ # try evaluating the supplied functions to make sure they provide
+ # sensible outputs
+
+ arglist = (self.beta0, self.data.x)
+ if self.model.extra_args is not None:
+ arglist = arglist + self.model.extra_args
+ res = self.model.fcn(*arglist)
+
+ if res.shape not in fcn_perms:
+ print(res.shape)
+ print(fcn_perms)
+ raise OdrError(f"fcn does not output {y_s}-shaped array")
+
+ if self.model.fjacd is not None:
+ res = self.model.fjacd(*arglist)
+ if res.shape not in fjacd_perms:
+ raise OdrError(
+ f"fjacd does not output {repr((q, m, n))}-shaped array")
+ if self.model.fjacb is not None:
+ res = self.model.fjacb(*arglist)
+ if res.shape not in fjacb_perms:
+ raise OdrError(
+ f"fjacb does not output {repr((q, p, n))}-shaped array")
+
+ # check shape of delta0
+
+ if self.delta0 is not None and self.delta0.shape != self.data.x.shape:
+ raise OdrError(
+ f"delta0 is not a {repr(self.data.x.shape)}-shaped array")
+
+ if self.data.x.size == 0:
+ warn("Empty data detected for ODR instance. "
+ "Do not expect any fitting to occur",
+ OdrWarning, stacklevel=3)
+
+ def _gen_work(self):
+ """ Generate a suitable work array if one does not already exist.
+ """
+
+ n = self.data.x.shape[-1]
+ p = self.beta0.shape[0]
+
+ if len(self.data.x.shape) == 2:
+ m = self.data.x.shape[0]
+ else:
+ m = 1
+
+ if self.model.implicit:
+ q = self.data.y
+ elif len(self.data.y.shape) == 2:
+ q = self.data.y.shape[0]
+ else:
+ q = 1
+
+ if self.data.we is None:
+ ldwe = ld2we = 1
+ elif len(self.data.we.shape) == 3:
+ ld2we, ldwe = self.data.we.shape[1:]
+ else:
+ we = self.data.we
+ ldwe = 1
+ ld2we = 1
+ if we.ndim == 1 and q == 1:
+ ldwe = n
+ elif we.ndim == 2:
+ if we.shape == (q, q):
+ ld2we = q
+ elif we.shape == (q, n):
+ ldwe = n
+
+ if self.job % 10 < 2:
+ # ODR not OLS
+ lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 6*n*m + 2*n*q*p +
+ 2*n*q*m + q*q + 5*q + q*(p+m) + ldwe*ld2we*q)
+ else:
+ # OLS not ODR
+ lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 2*n*m + 2*n*q*p +
+ 5*q + q*(p+m) + ldwe*ld2we*q)
+
+ if isinstance(self.work, np.ndarray) and self.work.shape == (lwork,)\
+ and self.work.dtype.str.endswith('f8'):
+ # the existing array is fine
+ return
+ else:
+ self.work = np.zeros((lwork,), float)
+
+ def set_job(self, fit_type=None, deriv=None, var_calc=None,
+ del_init=None, restart=None):
+ """
+ Sets the "job" parameter is a hopefully comprehensible way.
+
+ If an argument is not specified, then the value is left as is. The
+ default value from class initialization is for all of these options set
+ to 0.
+
+ Parameters
+ ----------
+ fit_type : {0, 1, 2} int
+ 0 -> explicit ODR
+
+ 1 -> implicit ODR
+
+ 2 -> ordinary least-squares
+ deriv : {0, 1, 2, 3} int
+ 0 -> forward finite differences
+
+ 1 -> central finite differences
+
+ 2 -> user-supplied derivatives (Jacobians) with results
+ checked by ODRPACK
+
+ 3 -> user-supplied derivatives, no checking
+ var_calc : {0, 1, 2} int
+ 0 -> calculate asymptotic covariance matrix and fit
+ parameter uncertainties (V_B, s_B) using derivatives
+ recomputed at the final solution
+
+ 1 -> calculate V_B and s_B using derivatives from last iteration
+
+ 2 -> do not calculate V_B and s_B
+ del_init : {0, 1} int
+ 0 -> initial input variable offsets set to 0
+
+ 1 -> initial offsets provided by user in variable "work"
+ restart : {0, 1} int
+ 0 -> fit is not a restart
+
+ 1 -> fit is a restart
+
+ Notes
+ -----
+ The permissible values are different from those given on pg. 31 of the
+ ODRPACK User's Guide only in that one cannot specify numbers greater than
+ the last value for each variable.
+
+ If one does not supply functions to compute the Jacobians, the fitting
+ procedure will change deriv to 0, finite differences, as a default. To
+ initialize the input variable offsets by yourself, set del_init to 1 and
+ put the offsets into the "work" variable correctly.
+
+ """
+
+ if self.job is None:
+ job_l = [0, 0, 0, 0, 0]
+ else:
+ job_l = [self.job // 10000 % 10,
+ self.job // 1000 % 10,
+ self.job // 100 % 10,
+ self.job // 10 % 10,
+ self.job % 10]
+
+ if fit_type in (0, 1, 2):
+ job_l[4] = fit_type
+ if deriv in (0, 1, 2, 3):
+ job_l[3] = deriv
+ if var_calc in (0, 1, 2):
+ job_l[2] = var_calc
+ if del_init in (0, 1):
+ job_l[1] = del_init
+ if restart in (0, 1):
+ job_l[0] = restart
+
+ self.job = (job_l[0]*10000 + job_l[1]*1000 +
+ job_l[2]*100 + job_l[3]*10 + job_l[4])
+
+ def set_iprint(self, init=None, so_init=None,
+ iter=None, so_iter=None, iter_step=None, final=None, so_final=None):
+ """ Set the iprint parameter for the printing of computation reports.
+
+ If any of the arguments are specified here, then they are set in the
+ iprint member. If iprint is not set manually or with this method, then
+ ODRPACK defaults to no printing. If no filename is specified with the
+ member rptfile, then ODRPACK prints to stdout. One can tell ODRPACK to
+ print to stdout in addition to the specified filename by setting the
+ so_* arguments to this function, but one cannot specify to print to
+ stdout but not a file since one can do that by not specifying a rptfile
+ filename.
+
+ There are three reports: initialization, iteration, and final reports.
+ They are represented by the arguments init, iter, and final
+ respectively. The permissible values are 0, 1, and 2 representing "no
+ report", "short report", and "long report" respectively.
+
+ The argument iter_step (0 <= iter_step <= 9) specifies how often to make
+ the iteration report; the report will be made for every iter_step'th
+ iteration starting with iteration one. If iter_step == 0, then no
+ iteration report is made, regardless of the other arguments.
+
+ If the rptfile is None, then any so_* arguments supplied will raise an
+ exception.
+ """
+ if self.iprint is None:
+ self.iprint = 0
+
+ ip = [self.iprint // 1000 % 10,
+ self.iprint // 100 % 10,
+ self.iprint // 10 % 10,
+ self.iprint % 10]
+
+ # make a list to convert iprint digits to/from argument inputs
+ # rptfile, stdout
+ ip2arg = [[0, 0], # none, none
+ [1, 0], # short, none
+ [2, 0], # long, none
+ [1, 1], # short, short
+ [2, 1], # long, short
+ [1, 2], # short, long
+ [2, 2]] # long, long
+
+ if (self.rptfile is None and
+ (so_init is not None or
+ so_iter is not None or
+ so_final is not None)):
+ raise OdrError(
+ "no rptfile specified, cannot output to stdout twice")
+
+ iprint_l = ip2arg[ip[0]] + ip2arg[ip[1]] + ip2arg[ip[3]]
+
+ if init is not None:
+ iprint_l[0] = init
+ if so_init is not None:
+ iprint_l[1] = so_init
+ if iter is not None:
+ iprint_l[2] = iter
+ if so_iter is not None:
+ iprint_l[3] = so_iter
+ if final is not None:
+ iprint_l[4] = final
+ if so_final is not None:
+ iprint_l[5] = so_final
+
+ if iter_step in range(10):
+ # 0..9
+ ip[2] = iter_step
+
+ ip[0] = ip2arg.index(iprint_l[0:2])
+ ip[1] = ip2arg.index(iprint_l[2:4])
+ ip[3] = ip2arg.index(iprint_l[4:6])
+
+ self.iprint = ip[0]*1000 + ip[1]*100 + ip[2]*10 + ip[3]
+
+ def run(self):
+ """ Run the fitting routine with all of the information given and with ``full_output=1``.
+
+ Returns
+ -------
+ output : Output instance
+ This object is also assigned to the attribute .output .
+ """ # noqa: E501
+
+ args = (self.model.fcn, self.beta0, self.data.y, self.data.x)
+ kwds = {'full_output': 1}
+ kwd_l = ['ifixx', 'ifixb', 'job', 'iprint', 'errfile', 'rptfile',
+ 'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb',
+ 'stpd', 'sclb', 'scld', 'work', 'iwork']
+
+ if self.delta0 is not None and (self.job // 10000) % 10 == 0:
+ # delta0 provided and fit is not a restart
+ self._gen_work()
+
+ d0 = np.ravel(self.delta0)
+
+ self.work[:len(d0)] = d0
+
+ # set the kwds from other objects explicitly
+ if self.model.fjacb is not None:
+ kwds['fjacb'] = self.model.fjacb
+ if self.model.fjacd is not None:
+ kwds['fjacd'] = self.model.fjacd
+ if self.data.we is not None:
+ kwds['we'] = self.data.we
+ if self.data.wd is not None:
+ kwds['wd'] = self.data.wd
+ if self.model.extra_args is not None:
+ kwds['extra_args'] = self.model.extra_args
+
+ # implicitly set kwds from self's members
+ for attr in kwd_l:
+ obj = getattr(self, attr)
+ if obj is not None:
+ kwds[attr] = obj
+
+ with ODR_LOCK:
+ self.output = Output(odr(*args, **kwds))
+
+ return self.output
+
+ def restart(self, iter=None):
+ """ Restarts the run with iter more iterations.
+
+ Parameters
+ ----------
+ iter : int, optional
+ ODRPACK's default for the number of new iterations is 10.
+
+ Returns
+ -------
+ output : Output instance
+ This object is also assigned to the attribute .output .
+ """
+
+ if self.output is None:
+ raise OdrError("cannot restart: run() has not been called before")
+
+ self.set_job(restart=1)
+ self.work = self.output.work
+ self.iwork = self.output.iwork
+
+ self.maxit = iter
+
+ return self.run()
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/models.py b/.venv/lib/python3.12/site-packages/scipy/odr/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..e144e443a2849b753733a4e604a6c389df70f73a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/models.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.odr` namespace for importing the functions
+# included below.
+
+
+__all__ = [ # noqa: F822
+ 'Model', 'exponential', 'multilinear', 'unilinear',
+ 'quadratic', 'polynomial'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
+ if name not in __all__:
+ raise AttributeError(
+ f"`scipy.odr.models` has no attribute {name}. In addition, {msg}")
+
+ import warnings
+ from . import _models
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
+
+ return getattr(_models, name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/odrpack.py b/.venv/lib/python3.12/site-packages/scipy/odr/odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3c3f029f107eabc5ad78d679cc9b4d22d8b533b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/odrpack.py
@@ -0,0 +1,28 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.odr` namespace for importing the functions
+# included below.
+
+
+__all__ = [ # noqa: F822
+ 'odr', 'OdrWarning', 'OdrError', 'OdrStop',
+ 'Data', 'RealData', 'Model', 'Output', 'ODR',
+ 'odr_error', 'odr_stop'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
+ if name not in __all__:
+ raise AttributeError(
+ f"`scipy.odr.odrpack` has no attribute {name}. In addition, {msg}")
+
+ import warnings
+ from . import _odrpack
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
+
+ return getattr(_odrpack, name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/odr/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/odr/tests/test_odr.py b/.venv/lib/python3.12/site-packages/scipy/odr/tests/test_odr.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d0545b018097237377878fd085960587082903a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/odr/tests/test_odr.py
@@ -0,0 +1,621 @@
+import pickle
+import tempfile
+import shutil
+import os
+
+import numpy as np
+from numpy import pi
+from numpy.testing import (assert_array_almost_equal,
+ assert_equal,
+ assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.odr import (Data, Model, ODR, RealData, OdrStop, OdrWarning,
+ OdrError, multilinear, exponential, unilinear,
+ quadratic, polynomial)
+
+
+class TestODR:
+
+ # Bad Data for 'x'
+
+ def test_bad_data(self):
+ assert_raises(ValueError, Data, 2, 1)
+ assert_raises(ValueError, RealData, 2, 1)
+
+ # Empty Data for 'x'
+ def empty_data_func(self, B, x):
+ return B[0]*x + B[1]
+
+ def test_empty_data(self):
+ beta0 = [0.02, 0.0]
+ linear = Model(self.empty_data_func)
+
+ empty_dat = Data([], [])
+ with pytest.warns(OdrWarning):
+ ODR(empty_dat, linear, beta0=beta0)
+
+ empty_dat = RealData([], [])
+ with pytest.warns(OdrWarning):
+ ODR(empty_dat, linear, beta0=beta0)
+
+ # Explicit Example
+
+ def explicit_fcn(self, B, x):
+ ret = B[0] + B[1] * np.power(np.exp(B[2]*x) - 1.0, 2)
+ return ret
+
+ def explicit_fjd(self, B, x):
+ eBx = np.exp(B[2]*x)
+ ret = B[1] * 2.0 * (eBx-1.0) * B[2] * eBx
+ return ret
+
+ def explicit_fjb(self, B, x):
+ eBx = np.exp(B[2]*x)
+ res = np.vstack([np.ones(x.shape[-1]),
+ np.power(eBx-1.0, 2),
+ B[1]*2.0*(eBx-1.0)*eBx*x])
+ return res
+
+ def test_explicit(self):
+ explicit_mod = Model(
+ self.explicit_fcn,
+ fjacb=self.explicit_fjb,
+ fjacd=self.explicit_fjd,
+ meta=dict(name='Sample Explicit Model',
+ ref='ODRPACK UG, pg. 39'),
+ )
+ explicit_dat = Data([0.,0.,5.,7.,7.5,10.,16.,26.,30.,34.,34.5,100.],
+ [1265.,1263.6,1258.,1254.,1253.,1249.8,1237.,1218.,1220.6,
+ 1213.8,1215.5,1212.])
+ explicit_odr = ODR(explicit_dat, explicit_mod, beta0=[1500.0, -50.0, -0.1],
+ ifixx=[0,0,1,1,1,1,1,1,1,1,1,0])
+ explicit_odr.set_job(deriv=2)
+ explicit_odr.set_iprint(init=0, iter=0, final=0)
+
+ out = explicit_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([1.2646548050648876e+03, -5.4018409956678255e+01,
+ -8.7849712165253724e-02]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([1.0349270280543437, 1.583997785262061, 0.0063321988657267]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[4.4949592379003039e-01, -3.7421976890364739e-01,
+ -8.0978217468468912e-04],
+ [-3.7421976890364739e-01, 1.0529686462751804e+00,
+ -1.9453521827942002e-03],
+ [-8.0978217468468912e-04, -1.9453521827942002e-03,
+ 1.6827336938454476e-05]]),
+ )
+
+ # Implicit Example
+
+ def implicit_fcn(self, B, x):
+ return (B[2]*np.power(x[0]-B[0], 2) +
+ 2.0*B[3]*(x[0]-B[0])*(x[1]-B[1]) +
+ B[4]*np.power(x[1]-B[1], 2) - 1.0)
+
+ def test_implicit(self):
+ implicit_mod = Model(
+ self.implicit_fcn,
+ implicit=1,
+ meta=dict(name='Sample Implicit Model',
+ ref='ODRPACK UG, pg. 49'),
+ )
+ implicit_dat = Data([
+ [0.5,1.2,1.6,1.86,2.12,2.36,2.44,2.36,2.06,1.74,1.34,0.9,-0.28,
+ -0.78,-1.36,-1.9,-2.5,-2.88,-3.18,-3.44],
+ [-0.12,-0.6,-1.,-1.4,-2.54,-3.36,-4.,-4.75,-5.25,-5.64,-5.97,-6.32,
+ -6.44,-6.44,-6.41,-6.25,-5.88,-5.5,-5.24,-4.86]],
+ 1,
+ )
+ implicit_odr = ODR(implicit_dat, implicit_mod,
+ beta0=[-1.0, -3.0, 0.09, 0.02, 0.08])
+
+ out = implicit_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([-0.9993809167281279, -2.9310484652026476, 0.0875730502693354,
+ 0.0162299708984738, 0.0797537982976416]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([0.1113840353364371, 0.1097673310686467, 0.0041060738314314,
+ 0.0027500347539902, 0.0034962501532468]),
+ )
+ assert_allclose(
+ out.cov_beta,
+ np.array([[2.1089274602333052e+00, -1.9437686411979040e+00,
+ 7.0263550868344446e-02, -4.7175267373474862e-02,
+ 5.2515575927380355e-02],
+ [-1.9437686411979040e+00, 2.0481509222414456e+00,
+ -6.1600515853057307e-02, 4.6268827806232933e-02,
+ -5.8822307501391467e-02],
+ [7.0263550868344446e-02, -6.1600515853057307e-02,
+ 2.8659542561579308e-03, -1.4628662260014491e-03,
+ 1.4528860663055824e-03],
+ [-4.7175267373474862e-02, 4.6268827806232933e-02,
+ -1.4628662260014491e-03, 1.2855592885514335e-03,
+ -1.2692942951415293e-03],
+ [5.2515575927380355e-02, -5.8822307501391467e-02,
+ 1.4528860663055824e-03, -1.2692942951415293e-03,
+ 2.0778813389755596e-03]]),
+ rtol=1e-6, atol=2e-6,
+ )
+
+ # Multi-variable Example
+
+ def multi_fcn(self, B, x):
+ if (x < 0.0).any():
+ raise OdrStop
+ theta = pi*B[3]/2.
+ ctheta = np.cos(theta)
+ stheta = np.sin(theta)
+ omega = np.power(2.*pi*x*np.exp(-B[2]), B[3])
+ phi = np.arctan2((omega*stheta), (1.0 + omega*ctheta))
+ r = (B[0] - B[1]) * np.power(np.sqrt(np.power(1.0 + omega*ctheta, 2) +
+ np.power(omega*stheta, 2)), -B[4])
+ ret = np.vstack([B[1] + r*np.cos(B[4]*phi),
+ r*np.sin(B[4]*phi)])
+ return ret
+
+ def test_multi(self):
+ multi_mod = Model(
+ self.multi_fcn,
+ meta=dict(name='Sample Multi-Response Model',
+ ref='ODRPACK UG, pg. 56'),
+ )
+
+ multi_x = np.array([30.0, 50.0, 70.0, 100.0, 150.0, 200.0, 300.0, 500.0,
+ 700.0, 1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 10000.0,
+ 15000.0, 20000.0, 30000.0, 50000.0, 70000.0, 100000.0, 150000.0])
+ multi_y = np.array([
+ [4.22, 4.167, 4.132, 4.038, 4.019, 3.956, 3.884, 3.784, 3.713,
+ 3.633, 3.54, 3.433, 3.358, 3.258, 3.193, 3.128, 3.059, 2.984,
+ 2.934, 2.876, 2.838, 2.798, 2.759],
+ [0.136, 0.167, 0.188, 0.212, 0.236, 0.257, 0.276, 0.297, 0.309,
+ 0.311, 0.314, 0.311, 0.305, 0.289, 0.277, 0.255, 0.24, 0.218,
+ 0.202, 0.182, 0.168, 0.153, 0.139],
+ ])
+ n = len(multi_x)
+ multi_we = np.zeros((2, 2, n), dtype=float)
+ multi_ifixx = np.ones(n, dtype=int)
+ multi_delta = np.zeros(n, dtype=float)
+
+ multi_we[0,0,:] = 559.6
+ multi_we[1,0,:] = multi_we[0,1,:] = -1634.0
+ multi_we[1,1,:] = 8397.0
+
+ for i in range(n):
+ if multi_x[i] < 100.0:
+ multi_ifixx[i] = 0
+ elif multi_x[i] <= 150.0:
+ pass # defaults are fine
+ elif multi_x[i] <= 1000.0:
+ multi_delta[i] = 25.0
+ elif multi_x[i] <= 10000.0:
+ multi_delta[i] = 560.0
+ elif multi_x[i] <= 100000.0:
+ multi_delta[i] = 9500.0
+ else:
+ multi_delta[i] = 144000.0
+ if multi_x[i] == 100.0 or multi_x[i] == 150.0:
+ multi_we[:,:,i] = 0.0
+
+ multi_dat = Data(multi_x, multi_y, wd=1e-4/np.power(multi_x, 2),
+ we=multi_we)
+ multi_odr = ODR(multi_dat, multi_mod, beta0=[4.,2.,7.,.4,.5],
+ delta0=multi_delta, ifixx=multi_ifixx)
+ multi_odr.set_job(deriv=1, del_init=1)
+
+ out = multi_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([4.3799880305938963, 2.4333057577497703, 8.0028845899503978,
+ 0.5101147161764654, 0.5173902330489161]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([0.0130625231081944, 0.0130499785273277, 0.1167085962217757,
+ 0.0132642749596149, 0.0288529201353984]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[0.0064918418231375, 0.0036159705923791, 0.0438637051470406,
+ -0.0058700836512467, 0.011281212888768],
+ [0.0036159705923791, 0.0064793789429006, 0.0517610978353126,
+ -0.0051181304940204, 0.0130726943624117],
+ [0.0438637051470406, 0.0517610978353126, 0.5182263323095322,
+ -0.0563083340093696, 0.1269490939468611],
+ [-0.0058700836512467, -0.0051181304940204, -0.0563083340093696,
+ 0.0066939246261263, -0.0140184391377962],
+ [0.011281212888768, 0.0130726943624117, 0.1269490939468611,
+ -0.0140184391377962, 0.0316733013820852]]),
+ )
+
+ # Pearson's Data
+ # K. Pearson, Philosophical Magazine, 2, 559 (1901)
+
+ def pearson_fcn(self, B, x):
+ return B[0] + B[1]*x
+
+ def test_pearson(self):
+ p_x = np.array([0.,.9,1.8,2.6,3.3,4.4,5.2,6.1,6.5,7.4])
+ p_y = np.array([5.9,5.4,4.4,4.6,3.5,3.7,2.8,2.8,2.4,1.5])
+ p_sx = np.array([.03,.03,.04,.035,.07,.11,.13,.22,.74,1.])
+ p_sy = np.array([1.,.74,.5,.35,.22,.22,.12,.12,.1,.04])
+
+ p_dat = RealData(p_x, p_y, sx=p_sx, sy=p_sy)
+
+ # Reverse the data to test invariance of results
+ pr_dat = RealData(p_y, p_x, sx=p_sy, sy=p_sx)
+
+ p_mod = Model(self.pearson_fcn, meta=dict(name='Uni-linear Fit'))
+
+ p_odr = ODR(p_dat, p_mod, beta0=[1.,1.])
+ pr_odr = ODR(pr_dat, p_mod, beta0=[1.,1.])
+
+ out = p_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([5.4767400299231674, -0.4796082367610305]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([0.3590121690702467, 0.0706291186037444]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[0.0854275622946333, -0.0161807025443155],
+ [-0.0161807025443155, 0.003306337993922]]),
+ )
+
+ rout = pr_odr.run()
+ assert_array_almost_equal(
+ rout.beta,
+ np.array([11.4192022410781231, -2.0850374506165474]),
+ )
+ assert_array_almost_equal(
+ rout.sd_beta,
+ np.array([0.9820231665657161, 0.3070515616198911]),
+ )
+ assert_array_almost_equal(
+ rout.cov_beta,
+ np.array([[0.6391799462548782, -0.1955657291119177],
+ [-0.1955657291119177, 0.0624888159223392]]),
+ )
+
+ # Lorentz Peak
+ # The data is taken from one of the undergraduate physics labs I performed.
+
+ def lorentz(self, beta, x):
+ return (beta[0]*beta[1]*beta[2] / np.sqrt(np.power(x*x -
+ beta[2]*beta[2], 2.0) + np.power(beta[1]*x, 2.0)))
+
+ def test_lorentz(self):
+ l_sy = np.array([.29]*18)
+ l_sx = np.array([.000972971,.000948268,.000707632,.000706679,
+ .000706074, .000703918,.000698955,.000456856,
+ .000455207,.000662717,.000654619,.000652694,
+ .000000859202,.00106589,.00106378,.00125483, .00140818,.00241839])
+
+ l_dat = RealData(
+ [3.9094, 3.85945, 3.84976, 3.84716, 3.84551, 3.83964, 3.82608,
+ 3.78847, 3.78163, 3.72558, 3.70274, 3.6973, 3.67373, 3.65982,
+ 3.6562, 3.62498, 3.55525, 3.41886],
+ [652, 910.5, 984, 1000, 1007.5, 1053, 1160.5, 1409.5, 1430, 1122,
+ 957.5, 920, 777.5, 709.5, 698, 578.5, 418.5, 275.5],
+ sx=l_sx,
+ sy=l_sy,
+ )
+ l_mod = Model(self.lorentz, meta=dict(name='Lorentz Peak'))
+ l_odr = ODR(l_dat, l_mod, beta0=(1000., .1, 3.8))
+
+ out = l_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([1.4306780846149925e+03, 1.3390509034538309e-01,
+ 3.7798193600109009e+00]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([7.3621186811330963e-01, 3.5068899941471650e-04,
+ 2.4451209281408992e-04]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[2.4714409064597873e-01, -6.9067261911110836e-05,
+ -3.1236953270424990e-05],
+ [-6.9067261911110836e-05, 5.6077531517333009e-08,
+ 3.6133261832722601e-08],
+ [-3.1236953270424990e-05, 3.6133261832722601e-08,
+ 2.7261220025171730e-08]]),
+ )
+
+ def test_ticket_1253(self):
+ def linear(c, x):
+ return c[0]*x+c[1]
+
+ c = [2.0, 3.0]
+ x = np.linspace(0, 10)
+ y = linear(c, x)
+
+ model = Model(linear)
+ data = Data(x, y, wd=1.0, we=1.0)
+ job = ODR(data, model, beta0=[1.0, 1.0])
+ result = job.run()
+ assert_equal(result.info, 2)
+
+ # Verify fix for gh-9140
+
+ def test_ifixx(self):
+ x1 = [-2.01, -0.99, -0.001, 1.02, 1.98]
+ x2 = [3.98, 1.01, 0.001, 0.998, 4.01]
+ fix = np.vstack((np.zeros_like(x1, dtype=int), np.ones_like(x2, dtype=int)))
+ data = Data(np.vstack((x1, x2)), y=1, fix=fix)
+ model = Model(lambda beta, x: x[1, :] - beta[0] * x[0, :]**2., implicit=True)
+
+ odr1 = ODR(data, model, beta0=np.array([1.]))
+ sol1 = odr1.run()
+ odr2 = ODR(data, model, beta0=np.array([1.]), ifixx=fix)
+ sol2 = odr2.run()
+ assert_equal(sol1.beta, sol2.beta)
+
+ # verify bugfix for #11800 in #11802
+ def test_ticket_11800(self):
+ # parameters
+ beta_true = np.array([1.0, 2.3, 1.1, -1.0, 1.3, 0.5])
+ nr_measurements = 10
+
+ std_dev_x = 0.01
+ x_error = np.array([[0.00063445, 0.00515731, 0.00162719, 0.01022866,
+ -0.01624845, 0.00482652, 0.00275988, -0.00714734, -0.00929201, -0.00687301],
+ [-0.00831623, -0.00821211, -0.00203459, 0.00938266, -0.00701829,
+ 0.0032169, 0.00259194, -0.00581017, -0.0030283, 0.01014164]])
+
+ std_dev_y = 0.05
+ y_error = np.array([[0.05275304, 0.04519563, -0.07524086, 0.03575642,
+ 0.04745194, 0.03806645, 0.07061601, -0.00753604, -0.02592543, -0.02394929],
+ [0.03632366, 0.06642266, 0.08373122, 0.03988822, -0.0092536,
+ -0.03750469, -0.03198903, 0.01642066, 0.01293648, -0.05627085]])
+
+ beta_solution = np.array([
+ 2.62920235756665876536e+00, -1.26608484996299608838e+02,
+ 1.29703572775403074502e+02, -1.88560985401185465804e+00,
+ 7.83834160771274923718e+01, -7.64124076838087091801e+01])
+
+ # model's function and Jacobians
+ def func(beta, x):
+ y0 = beta[0] + beta[1] * x[0, :] + beta[2] * x[1, :]
+ y1 = beta[3] + beta[4] * x[0, :] + beta[5] * x[1, :]
+
+ return np.vstack((y0, y1))
+
+ def df_dbeta_odr(beta, x):
+ nr_meas = np.shape(x)[1]
+ zeros = np.zeros(nr_meas)
+ ones = np.ones(nr_meas)
+
+ dy0 = np.array([ones, x[0, :], x[1, :], zeros, zeros, zeros])
+ dy1 = np.array([zeros, zeros, zeros, ones, x[0, :], x[1, :]])
+
+ return np.stack((dy0, dy1))
+
+ def df_dx_odr(beta, x):
+ nr_meas = np.shape(x)[1]
+ ones = np.ones(nr_meas)
+
+ dy0 = np.array([beta[1] * ones, beta[2] * ones])
+ dy1 = np.array([beta[4] * ones, beta[5] * ones])
+ return np.stack((dy0, dy1))
+
+ # do measurements with errors in independent and dependent variables
+ x0_true = np.linspace(1, 10, nr_measurements)
+ x1_true = np.linspace(1, 10, nr_measurements)
+ x_true = np.array([x0_true, x1_true])
+
+ y_true = func(beta_true, x_true)
+
+ x_meas = x_true + x_error
+ y_meas = y_true + y_error
+
+ # estimate model's parameters
+ model_f = Model(func, fjacb=df_dbeta_odr, fjacd=df_dx_odr)
+
+ data = RealData(x_meas, y_meas, sx=std_dev_x, sy=std_dev_y)
+
+ odr_obj = ODR(data, model_f, beta0=0.9 * beta_true, maxit=100)
+ #odr_obj.set_iprint(init=2, iter=0, iter_step=1, final=1)
+ odr_obj.set_job(deriv=3)
+
+ odr_out = odr_obj.run()
+
+ # check results
+ assert_equal(odr_out.info, 1)
+ assert_array_almost_equal(odr_out.beta, beta_solution)
+
+ def test_multilinear_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 10.0 + 5.0 * x
+ data = Data(x, y)
+ odr_obj = ODR(data, multilinear)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [10.0, 5.0])
+
+ def test_exponential_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = -10.0 + np.exp(0.5*x)
+ data = Data(x, y)
+ odr_obj = ODR(data, exponential)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [-10.0, 0.5])
+
+ def test_polynomial_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 + 2.0 * x + 3.0 * x ** 2 + 4.0 * x ** 3
+ poly_model = polynomial(3)
+ data = Data(x, y)
+ odr_obj = ODR(data, poly_model)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0, 4.0])
+
+ def test_unilinear_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ data = Data(x, y)
+ odr_obj = ODR(data, unilinear)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [1.0, 2.0])
+
+ def test_quadratic_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x ** 2 + 2.0 * x + 3.0
+ data = Data(x, y)
+ odr_obj = ODR(data, quadratic)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0])
+
+ def test_work_ind(self):
+
+ def func(par, x):
+ b0, b1 = par
+ return b0 + b1 * x
+
+ # generate some data
+ n_data = 4
+ x = np.arange(n_data)
+ y = np.where(x % 2, x + 0.1, x - 0.1)
+ x_err = np.full(n_data, 0.1)
+ y_err = np.full(n_data, 0.1)
+
+ # do the fitting
+ linear_model = Model(func)
+ real_data = RealData(x, y, sx=x_err, sy=y_err)
+ odr_obj = ODR(real_data, linear_model, beta0=[0.4, 0.4])
+ odr_obj.set_job(fit_type=0)
+ out = odr_obj.run()
+
+ sd_ind = out.work_ind['sd']
+ assert_array_almost_equal(out.sd_beta,
+ out.work[sd_ind:sd_ind + len(out.sd_beta)])
+
+ @pytest.mark.skipif(True, reason="Fortran I/O prone to crashing so better "
+ "not to run this test, see gh-13127")
+ def test_output_file_overwrite(self):
+ """
+ Verify fix for gh-1892
+ """
+ def func(b, x):
+ return b[0] + b[1] * x
+
+ p = Model(func)
+ data = Data(np.arange(10), 12 * np.arange(10))
+ tmp_dir = tempfile.mkdtemp()
+ error_file_path = os.path.join(tmp_dir, "error.dat")
+ report_file_path = os.path.join(tmp_dir, "report.dat")
+ try:
+ ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
+ rptfile=report_file_path).run()
+ ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
+ rptfile=report_file_path, overwrite=True).run()
+ finally:
+ # remove output files for clean up
+ shutil.rmtree(tmp_dir)
+
+ def test_odr_model_default_meta(self):
+ def func(b, x):
+ return b[0] + b[1] * x
+
+ p = Model(func)
+ p.set_meta(name='Sample Model Meta', ref='ODRPACK')
+ assert_equal(p.meta, {'name': 'Sample Model Meta', 'ref': 'ODRPACK'})
+
+ def test_work_array_del_init(self):
+ """
+ Verify fix for gh-18739 where del_init=1 fails.
+ """
+ def func(b, x):
+ return b[0] + b[1] * x
+
+ # generate some data
+ n_data = 4
+ x = np.arange(n_data)
+ y = np.where(x % 2, x + 0.1, x - 0.1)
+ x_err = np.full(n_data, 0.1)
+ y_err = np.full(n_data, 0.1)
+
+ linear_model = Model(func)
+ # Try various shapes of the `we` array from various `sy` and `covy`
+ rd0 = RealData(x, y, sx=x_err, sy=y_err)
+ rd1 = RealData(x, y, sx=x_err, sy=0.1)
+ rd2 = RealData(x, y, sx=x_err, sy=[0.1])
+ rd3 = RealData(x, y, sx=x_err, sy=np.full((1, n_data), 0.1))
+ rd4 = RealData(x, y, sx=x_err, covy=[[0.01]])
+ rd5 = RealData(x, y, sx=x_err, covy=np.full((1, 1, n_data), 0.01))
+ for rd in [rd0, rd1, rd2, rd3, rd4, rd5]:
+ odr_obj = ODR(rd, linear_model, beta0=[0.4, 0.4],
+ delta0=np.full(n_data, -0.1))
+ odr_obj.set_job(fit_type=0, del_init=1)
+ # Just make sure that it runs without raising an exception.
+ odr_obj.run()
+
+ def test_pickling_data(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ data = Data(x, y)
+
+ obj_pickle = pickle.dumps(data)
+ del data
+ pickle.loads(obj_pickle)
+
+ def test_pickling_real_data(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ data = RealData(x, y)
+
+ obj_pickle = pickle.dumps(data)
+ del data
+ pickle.loads(obj_pickle)
+
+ def test_pickling_model(self):
+ obj_pickle = pickle.dumps(unilinear)
+ pickle.loads(obj_pickle)
+
+ def test_pickling_odr(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ odr_obj = ODR(Data(x, y), unilinear)
+
+ obj_pickle = pickle.dumps(odr_obj)
+ del odr_obj
+ pickle.loads(obj_pickle)
+
+ def test_pickling_output(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ output = ODR(Data(x, y), unilinear).run
+
+ obj_pickle = pickle.dumps(output)
+ del output
+ pickle.loads(obj_pickle)
+
+ def test_explicit_model_with_implicit_job(self):
+ """
+ Verify fix for gh-23763 that ODR doesn't segfault
+ """
+ x = np.linspace(0, 10, 10)
+ y = 2.0 + 3.0 * x
+
+ data = Data(x, y)
+ model = unilinear # this is an explicit model
+
+ # job=1 is implicit, should raise on explicit model
+ with assert_raises(OdrError):
+ odr = ODR(data, model, job=1)
+ odr.run()
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/__init__.pxd b/.venv/lib/python3.12/site-packages/scipy/optimize/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..2402eeb020d34ad8b82e287e32545423911ff66c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/__init__.pxd
@@ -0,0 +1 @@
+from .optimize cimport cython_optimize
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fce4cecd22b165f9975160fe7c1ed718ed358853
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/__init__.py
@@ -0,0 +1,460 @@
+"""
+=====================================================
+Optimization and root finding (:mod:`scipy.optimize`)
+=====================================================
+
+.. currentmodule:: scipy.optimize
+
+.. toctree::
+ :hidden:
+
+ optimize.cython_optimize
+
+SciPy ``optimize`` provides functions for minimizing (or maximizing)
+objective functions, possibly subject to constraints. It includes
+solvers for nonlinear problems (with support for both local and global
+optimization algorithms), linear programming, constrained
+and nonlinear least-squares, root finding, and curve fitting.
+
+Common functions and objects, shared across different solvers, are:
+
+.. autosummary::
+ :toctree: generated/
+
+ show_options - Show specific options optimization solvers.
+ OptimizeResult - The optimization result returned by some optimizers.
+ OptimizeWarning - The optimization encountered problems.
+
+
+Optimization
+============
+
+Scalar functions optimization
+-----------------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ minimize_scalar - Interface for minimizers of univariate functions
+
+The `minimize_scalar` function supports the following methods:
+
+.. toctree::
+
+ optimize.minimize_scalar-brent
+ optimize.minimize_scalar-bounded
+ optimize.minimize_scalar-golden
+
+Local (multivariate) optimization
+---------------------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ minimize - Interface for minimizers of multivariate functions.
+
+The `minimize` function supports the following methods:
+
+.. toctree::
+
+ optimize.minimize-neldermead
+ optimize.minimize-powell
+ optimize.minimize-cg
+ optimize.minimize-bfgs
+ optimize.minimize-newtoncg
+ optimize.minimize-lbfgsb
+ optimize.minimize-tnc
+ optimize.minimize-cobyla
+ optimize.minimize-cobyqa
+ optimize.minimize-slsqp
+ optimize.minimize-trustconstr
+ optimize.minimize-dogleg
+ optimize.minimize-trustncg
+ optimize.minimize-trustkrylov
+ optimize.minimize-trustexact
+
+Constraints are passed to `minimize` function as a single object or
+as a list of objects from the following classes:
+
+.. autosummary::
+ :toctree: generated/
+
+ NonlinearConstraint - Class defining general nonlinear constraints.
+ LinearConstraint - Class defining general linear constraints.
+
+Simple bound constraints are handled separately and there is a special class
+for them:
+
+.. autosummary::
+ :toctree: generated/
+
+ Bounds - Bound constraints.
+
+Quasi-Newton strategies implementing `HessianUpdateStrategy`
+interface can be used to approximate the Hessian in `minimize`
+function (available only for the 'trust-constr' method). Available
+quasi-Newton methods implementing this interface are:
+
+.. autosummary::
+ :toctree: generated/
+
+ BFGS - Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
+ SR1 - Symmetric-rank-1 Hessian update strategy.
+
+.. _global_optimization:
+
+Global optimization
+-------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ basinhopping - Basinhopping stochastic optimizer.
+ brute - Brute force searching optimizer.
+ differential_evolution - Stochastic optimizer using differential evolution.
+
+ shgo - Simplicial homology global optimizer.
+ dual_annealing - Dual annealing stochastic optimizer.
+ direct - DIRECT (Dividing Rectangles) optimizer.
+
+Least-squares and curve fitting
+===============================
+
+Nonlinear least-squares
+-----------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ least_squares - Solve a nonlinear least-squares problem with bounds on the variables.
+
+Linear least-squares
+--------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ nnls - Linear least-squares problem with non-negativity constraint.
+ lsq_linear - Linear least-squares problem with bound constraints.
+ isotonic_regression - Least squares problem of isotonic regression via PAVA.
+
+Curve fitting
+-------------
+
+.. autosummary::
+ :toctree: generated/
+
+ curve_fit -- Fit curve to a set of points.
+
+Root finding
+============
+
+Scalar functions
+----------------
+.. autosummary::
+ :toctree: generated/
+
+ root_scalar - Unified interface for nonlinear solvers of scalar functions.
+ brentq - quadratic interpolation Brent method.
+ brenth - Brent method, modified by Harris with hyperbolic extrapolation.
+ ridder - Ridder's method.
+ bisect - Bisection method.
+ newton - Newton's method (also Secant and Halley's methods).
+ toms748 - Alefeld, Potra & Shi Algorithm 748.
+ RootResults - The root finding result returned by some root finders.
+
+The `root_scalar` function supports the following methods:
+
+.. toctree::
+
+ optimize.root_scalar-brentq
+ optimize.root_scalar-brenth
+ optimize.root_scalar-bisect
+ optimize.root_scalar-ridder
+ optimize.root_scalar-newton
+ optimize.root_scalar-toms748
+ optimize.root_scalar-secant
+ optimize.root_scalar-halley
+
+
+
+The table below lists situations and appropriate methods, along with
+*asymptotic* convergence rates per iteration (and per function evaluation)
+for successful convergence to a simple root(*).
+Bisection is the slowest of them all, adding one bit of accuracy for each
+function evaluation, but is guaranteed to converge.
+The other bracketing methods all (eventually) increase the number of accurate
+bits by about 50% for every function evaluation.
+The derivative-based methods, all built on `newton`, can converge quite quickly
+if the initial value is close to the root. They can also be applied to
+functions defined on (a subset of) the complex plane.
+
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| Domain of f | Bracket? | Derivatives? | Solvers | Convergence |
++ + +----------+-----------+ +-------------+----------------+
+| | | `fprime` | `fprime2` | | Guaranteed? | Rate(s)(*) |
++=============+==========+==========+===========+=============+=============+================+
+| `R` | Yes | N/A | N/A | - bisection | - Yes | - 1 "Linear" |
+| | | | | - brentq | - Yes | - >=1, <= 1.62 |
+| | | | | - brenth | - Yes | - >=1, <= 1.62 |
+| | | | | - ridder | - Yes | - 2.0 (1.41) |
+| | | | | - toms748 | - Yes | - 2.7 (1.65) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| `R` or `C` | No | No | No | secant | No | 1.62 (1.62) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| `R` or `C` | No | Yes | No | newton | No | 2.00 (1.41) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| `R` or `C` | No | Yes | Yes | halley | No | 3.00 (1.44) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+
+.. seealso::
+
+ `scipy.optimize.cython_optimize` -- Typed Cython versions of root finding functions
+
+Fixed point finding:
+
+.. autosummary::
+ :toctree: generated/
+
+ fixed_point - Single-variable fixed-point solver.
+
+Multidimensional
+----------------
+
+.. autosummary::
+ :toctree: generated/
+
+ root - Unified interface for nonlinear solvers of multivariate functions.
+
+The `root` function supports the following methods:
+
+.. toctree::
+
+ optimize.root-hybr
+ optimize.root-lm
+ optimize.root-broyden1
+ optimize.root-broyden2
+ optimize.root-anderson
+ optimize.root-linearmixing
+ optimize.root-diagbroyden
+ optimize.root-excitingmixing
+ optimize.root-krylov
+ optimize.root-dfsane
+
+Elementwise Minimization and Root Finding
+=========================================
+
+.. toctree::
+ :maxdepth: 3
+
+ optimize.elementwise
+
+Linear programming / MILP
+=========================
+
+.. autosummary::
+ :toctree: generated/
+
+ milp -- Mixed integer linear programming.
+ linprog -- Unified interface for minimizers of linear programming problems.
+
+The `linprog` function supports the following methods:
+
+.. toctree::
+
+ optimize.linprog-simplex
+ optimize.linprog-interior-point
+ optimize.linprog-revised_simplex
+ optimize.linprog-highs-ipm
+ optimize.linprog-highs-ds
+ optimize.linprog-highs
+
+The simplex, interior-point, and revised simplex methods support callback
+functions, such as:
+
+.. autosummary::
+ :toctree: generated/
+
+ linprog_verbose_callback -- Sample callback function for linprog (simplex).
+
+Assignment problems
+===================
+
+.. autosummary::
+ :toctree: generated/
+
+ linear_sum_assignment -- Solves the linear-sum assignment problem.
+ quadratic_assignment -- Solves the quadratic assignment problem.
+
+The `quadratic_assignment` function supports the following methods:
+
+.. toctree::
+
+ optimize.qap-faq
+ optimize.qap-2opt
+
+Utilities
+=========
+
+Finite-difference approximation
+-------------------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ approx_fprime - Approximate the gradient of a scalar function.
+ check_grad - Check the supplied derivative using finite differences.
+
+
+Line search
+-----------
+
+.. autosummary::
+ :toctree: generated/
+
+ bracket - Bracket a minimum, given two starting points.
+ line_search - Return a step that satisfies the strong Wolfe conditions.
+
+Hessian approximation
+---------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ LbfgsInvHessProduct - Linear operator for L-BFGS approximate inverse Hessian.
+ HessianUpdateStrategy - Interface for implementing Hessian update strategies
+
+Benchmark problems
+------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ rosen - The Rosenbrock function.
+ rosen_der - The derivative of the Rosenbrock function.
+ rosen_hess - The Hessian matrix of the Rosenbrock function.
+ rosen_hess_prod - Product of the Rosenbrock Hessian with a vector.
+
+Legacy functions
+================
+
+The functions below are not recommended for use in new scripts;
+all of these methods are accessible via a newer, more consistent
+interfaces, provided by the interfaces above.
+
+Optimization
+------------
+
+General-purpose multivariate methods:
+
+.. autosummary::
+ :toctree: generated/
+
+ fmin - Nelder-Mead Simplex algorithm.
+ fmin_powell - Powell's (modified) conjugate direction method.
+ fmin_cg - Non-linear (Polak-Ribiere) conjugate gradient algorithm.
+ fmin_bfgs - Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno).
+ fmin_ncg - Line-search Newton Conjugate Gradient.
+
+Constrained multivariate methods:
+
+.. autosummary::
+ :toctree: generated/
+
+ fmin_l_bfgs_b - Zhu, Byrd, and Nocedal's constrained optimizer.
+ fmin_tnc - Truncated Newton code.
+ fmin_cobyla - Constrained optimization by linear approximation.
+ fmin_slsqp - Minimization using sequential least-squares programming.
+
+Univariate (scalar) minimization methods:
+
+.. autosummary::
+ :toctree: generated/
+
+ fminbound - Bounded minimization of a scalar function.
+ brent - 1-D function minimization using Brent method.
+ golden - 1-D function minimization using Golden Section method.
+
+Least-squares
+-------------
+
+.. autosummary::
+ :toctree: generated/
+
+ leastsq - Minimize the sum of squares of M equations in N unknowns.
+
+Root finding
+------------
+
+General nonlinear solvers:
+
+.. autosummary::
+ :toctree: generated/
+
+ fsolve - Non-linear multivariable equation solver.
+ broyden1 - Broyden's first method.
+ broyden2 - Broyden's second method.
+ NoConvergence - Exception raised when nonlinear solver does not converge.
+
+Large-scale nonlinear solvers:
+
+.. autosummary::
+ :toctree: generated/
+
+ newton_krylov
+ anderson
+
+ BroydenFirst
+ InverseJacobian
+ KrylovJacobian
+
+Simple iteration solvers:
+
+.. autosummary::
+ :toctree: generated/
+
+ excitingmixing
+ linearmixing
+ diagbroyden
+
+""" # noqa: E501
+
+from ._optimize import *
+from ._minimize import *
+from ._root import *
+from ._root_scalar import *
+from ._minpack_py import *
+from ._zeros_py import *
+from ._lbfgsb_py import fmin_l_bfgs_b, LbfgsInvHessProduct
+from ._tnc import fmin_tnc
+from ._cobyla_py import fmin_cobyla
+from ._nonlin import *
+from ._slsqp_py import fmin_slsqp
+from ._nnls import nnls
+from ._basinhopping import basinhopping
+from ._linprog import linprog, linprog_verbose_callback
+from ._lsap import linear_sum_assignment
+from ._differentialevolution import differential_evolution
+from ._lsq import least_squares, lsq_linear
+from ._isotonic import isotonic_regression
+from ._constraints import (NonlinearConstraint,
+ LinearConstraint,
+ Bounds)
+from ._hessian_update_strategy import HessianUpdateStrategy, BFGS, SR1
+from ._shgo import shgo
+from ._dual_annealing import dual_annealing
+from ._qap import quadratic_assignment
+from ._direct_py import direct
+from ._milp import milp
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+ cobyla, lbfgsb, linesearch, minpack, minpack2, moduleTNC, nonlin, optimize,
+ slsqp, tnc, zeros
+)
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_basinhopping.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ad202373e7c37e4e43d24c6b145cce800b2334b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_basinhopping.py
@@ -0,0 +1,742 @@
+"""
+basinhopping: The basinhopping global optimization algorithm
+"""
+import numpy as np
+import math
+import inspect
+import scipy.optimize
+from scipy._lib._util import (check_random_state, _transition_to_rng,
+ wrapped_inspect_signature)
+
+__all__ = ['basinhopping']
+
+
+_params = (inspect.Parameter('res_new', kind=inspect.Parameter.KEYWORD_ONLY),
+ inspect.Parameter('res_old', kind=inspect.Parameter.KEYWORD_ONLY))
+_new_accept_test_signature = inspect.Signature(parameters=_params)
+
+
+class Storage:
+ """
+ Class used to store the lowest energy structure
+ """
+ def __init__(self, minres):
+ self._add(minres)
+
+ def _add(self, minres):
+ self.minres = minres
+ self.minres.x = np.copy(minres.x)
+
+ def update(self, minres):
+ if minres.success and (minres.fun < self.minres.fun
+ or not self.minres.success):
+ self._add(minres)
+ return True
+ else:
+ return False
+
+ def get_lowest(self):
+ return self.minres
+
+
+class BasinHoppingRunner:
+ """This class implements the core of the basinhopping algorithm.
+
+ x0 : ndarray
+ The starting coordinates.
+ minimizer : callable
+ The local minimizer, with signature ``result = minimizer(x)``.
+ The return value is an `optimize.OptimizeResult` object.
+ step_taking : callable
+ This function displaces the coordinates randomly. Signature should
+ be ``x_new = step_taking(x)``. Note that `x` may be modified in-place.
+ accept_tests : list of callables
+ Each test is passed the kwargs `f_new`, `x_new`, `f_old` and
+ `x_old`. These tests will be used to judge whether or not to accept
+ the step. The acceptable return values are True, False, or ``"force
+ accept"``. If any of the tests return False then the step is rejected.
+ If ``"force accept"``, then this will override any other tests in
+ order to accept the step. This can be used, for example, to forcefully
+ escape from a local minimum that ``basinhopping`` is trapped in.
+ disp : bool, optional
+ Display status messages.
+
+ """
+ def __init__(self, x0, minimizer, step_taking, accept_tests, disp=False):
+ self.x = np.copy(x0)
+ self.minimizer = minimizer
+ self.step_taking = step_taking
+ self.accept_tests = accept_tests
+ self.disp = disp
+
+ self.nstep = 0
+
+ # initialize return object
+ self.res = scipy.optimize.OptimizeResult()
+ self.res.minimization_failures = 0
+
+ # do initial minimization
+ minres = minimizer(self.x)
+ if not minres.success:
+ self.res.minimization_failures += 1
+ if self.disp:
+ print("warning: basinhopping: local minimization failure")
+ self.x = np.copy(minres.x)
+ self.energy = minres.fun
+ self.incumbent_minres = minres # best minimize result found so far
+ if self.disp:
+ print(f"basinhopping step {self.nstep}: f {self.energy:g}")
+
+ # initialize storage class
+ self.storage = Storage(minres)
+
+ if hasattr(minres, "nfev"):
+ self.res.nfev = minres.nfev
+ if hasattr(minres, "njev"):
+ self.res.njev = minres.njev
+ if hasattr(minres, "nhev"):
+ self.res.nhev = minres.nhev
+
+ def _monte_carlo_step(self):
+ """Do one Monte Carlo iteration
+
+ Randomly displace the coordinates, minimize, and decide whether
+ or not to accept the new coordinates.
+ """
+ # Take a random step. Make a copy of x because the step_taking
+ # algorithm might change x in place
+ x_after_step = np.copy(self.x)
+ x_after_step = self.step_taking(x_after_step)
+
+ # do a local minimization
+ minres = self.minimizer(x_after_step)
+ x_after_quench = minres.x
+ energy_after_quench = minres.fun
+ if not minres.success:
+ self.res.minimization_failures += 1
+ if self.disp:
+ print("warning: basinhopping: local minimization failure")
+ if hasattr(minres, "nfev"):
+ self.res.nfev += minres.nfev
+ if hasattr(minres, "njev"):
+ self.res.njev += minres.njev
+ if hasattr(minres, "nhev"):
+ self.res.nhev += minres.nhev
+
+ # accept the move based on self.accept_tests. If any test is False,
+ # then reject the step. If any test returns the special string
+ # 'force accept', then accept the step regardless. This can be used
+ # to forcefully escape from a local minimum if normal basin hopping
+ # steps are not sufficient.
+ accept = True
+ for test in self.accept_tests:
+ if wrapped_inspect_signature(test) == _new_accept_test_signature:
+ testres = test(res_new=minres, res_old=self.incumbent_minres)
+ else:
+ testres = test(f_new=energy_after_quench, x_new=x_after_quench,
+ f_old=self.energy, x_old=self.x)
+
+ if testres == 'force accept':
+ accept = True
+ break
+ elif testres is None:
+ raise ValueError("accept_tests must return True, False, or "
+ "'force accept'")
+ elif not testres:
+ accept = False
+
+ # Report the result of the acceptance test to the take step class.
+ # This is for adaptive step taking
+ if hasattr(self.step_taking, "report"):
+ self.step_taking.report(accept, f_new=energy_after_quench,
+ x_new=x_after_quench, f_old=self.energy,
+ x_old=self.x)
+
+ return accept, minres
+
+ def one_cycle(self):
+ """Do one cycle of the basinhopping algorithm
+ """
+ self.nstep += 1
+ new_global_min = False
+
+ accept, minres = self._monte_carlo_step()
+
+ if accept:
+ self.energy = minres.fun
+ self.x = np.copy(minres.x)
+ self.incumbent_minres = minres # best minimize result found so far
+ new_global_min = self.storage.update(minres)
+
+ # print some information
+ if self.disp:
+ self.print_report(minres.fun, accept)
+ if new_global_min:
+ print(
+ f"found new global minimum on step {self.nstep} with "
+ f"function value {self.energy:g}"
+ )
+
+ # save some variables as BasinHoppingRunner attributes
+ self.xtrial = minres.x
+ self.energy_trial = minres.fun
+ self.accept = accept
+
+ return new_global_min
+
+ def print_report(self, energy_trial, accept):
+ """print a status update"""
+ minres = self.storage.get_lowest()
+ print(
+ f"basinhopping step {self.nstep}: f {self.energy:g} "
+ f"trial_f {energy_trial:g} accepted {accept} "
+ f"lowest_f {minres.fun:g}"
+ )
+
+
+class AdaptiveStepsize:
+ """
+ Class to implement adaptive stepsize.
+
+ This class wraps the step taking class and modifies the stepsize to
+ ensure the true acceptance rate is as close as possible to the target.
+
+ Parameters
+ ----------
+ takestep : callable
+ The step taking routine. Must contain modifiable attribute
+ takestep.stepsize
+ accept_rate : float, optional
+ The target step acceptance rate
+ interval : int, optional
+ Interval for how often to update the stepsize
+ factor : float, optional
+ The step size is multiplied or divided by this factor upon each
+ update.
+ verbose : bool, optional
+ Print information about each update
+
+ """
+ def __init__(self, takestep, accept_rate=0.5, interval=50, factor=0.9,
+ verbose=True):
+ self.takestep = takestep
+ self.target_accept_rate = accept_rate
+ self.interval = interval
+ self.factor = factor
+ self.verbose = verbose
+
+ self.nstep = 0
+ self.nstep_tot = 0
+ self.naccept = 0
+
+ def __call__(self, x):
+ return self.take_step(x)
+
+ def _adjust_step_size(self):
+ old_stepsize = self.takestep.stepsize
+ accept_rate = float(self.naccept) / self.nstep
+ if accept_rate > self.target_accept_rate:
+ # We're accepting too many steps. This generally means we're
+ # trapped in a basin. Take bigger steps.
+ self.takestep.stepsize /= self.factor
+ else:
+ # We're not accepting enough steps. Take smaller steps.
+ self.takestep.stepsize *= self.factor
+ if self.verbose:
+ print(f"adaptive stepsize: acceptance rate {accept_rate:f} target "
+ f"{self.target_accept_rate:f} new stepsize "
+ f"{self.takestep.stepsize:g} old stepsize {old_stepsize:g}")
+
+ def take_step(self, x):
+ self.nstep += 1
+ self.nstep_tot += 1
+ if self.nstep % self.interval == 0:
+ self._adjust_step_size()
+ return self.takestep(x)
+
+ def report(self, accept, **kwargs):
+ "called by basinhopping to report the result of the step"
+ if accept:
+ self.naccept += 1
+
+
+class RandomDisplacement:
+ """Add a random displacement of maximum size `stepsize` to each coordinate.
+
+ Calling this updates `x` in-place.
+
+ Parameters
+ ----------
+ stepsize : float, optional
+ Maximum stepsize in any dimension
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Random number generator
+ """
+
+ def __init__(self, stepsize=0.5, rng=None):
+ self.stepsize = stepsize
+ self.rng = check_random_state(rng)
+
+ def __call__(self, x):
+ x += self.rng.uniform(-self.stepsize, self.stepsize,
+ np.shape(x))
+ return x
+
+
+class MinimizerWrapper:
+ """
+ wrap a minimizer function as a minimizer class
+ """
+ def __init__(self, minimizer, func=None, **kwargs):
+ self.minimizer = minimizer
+ self.func = func
+ self.kwargs = kwargs
+
+ def __call__(self, x0):
+ if self.func is None:
+ return self.minimizer(x0, **self.kwargs)
+ else:
+ return self.minimizer(self.func, x0, **self.kwargs)
+
+
+class Metropolis:
+ """Metropolis acceptance criterion.
+
+ Parameters
+ ----------
+ T : float
+ The "temperature" parameter for the accept or reject criterion.
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Random number generator used for acceptance test.
+
+ """
+
+ def __init__(self, T, rng=None):
+ # Avoid ZeroDivisionError since "MBH can be regarded as a special case
+ # of the BH framework with the Metropolis criterion, where temperature
+ # T = 0." (Reject all steps that increase energy.)
+ self.beta = 1.0 / T if T != 0 else float('inf')
+ self.rng = check_random_state(rng)
+
+ def accept_reject(self, res_new, res_old):
+ """
+ Assuming the local search underlying res_new was successful:
+ If new energy is lower than old, it will always be accepted.
+ If new is higher than old, there is a chance it will be accepted,
+ less likely for larger differences.
+ """
+ with np.errstate(invalid='ignore'):
+ # The energy values being fed to Metropolis are 1-length arrays, and if
+ # they are equal, their difference is 0, which gets multiplied by beta,
+ # which is inf, and array([0]) * float('inf') causes
+ #
+ # RuntimeWarning: invalid value encountered in multiply
+ #
+ # Ignore this warning so when the algorithm is on a flat plane, it always
+ # accepts the step, to try to move off the plane.
+ prod = -(res_new.fun - res_old.fun) * self.beta
+ w = math.exp(min(0, prod))
+
+ rand = self.rng.uniform()
+ return w >= rand and (res_new.success or not res_old.success)
+
+ def __call__(self, *, res_new, res_old):
+ """
+ f_new and f_old are mandatory in kwargs
+ """
+ return bool(self.accept_reject(res_new, res_old))
+
+
+@_transition_to_rng("seed", position_num=12, replace_doc=True)
+def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5,
+ minimizer_kwargs=None, take_step=None, accept_test=None,
+ callback=None, interval=50, disp=False, niter_success=None,
+ rng=None, *, target_accept_rate=0.5, stepwise_factor=0.9):
+ """Find the global minimum of a function using the basin-hopping algorithm.
+
+ Basin-hopping is a two-phase method that combines a global stepping
+ algorithm with local minimization at each step. Designed to mimic
+ the natural process of energy minimization of clusters of atoms, it works
+ well for similar problems with "funnel-like, but rugged" energy landscapes
+ [5]_.
+
+ As the step-taking, step acceptance, and minimization methods are all
+ customizable, this function can also be used to implement other two-phase
+ methods.
+
+ Parameters
+ ----------
+ func : callable ``f(x, *args)``
+ Function to be optimized. ``args`` can be passed as an optional item
+ in the dict `minimizer_kwargs`
+ x0 : array_like
+ Initial guess.
+ niter : int, optional
+ The number of basin-hopping iterations. There will be a total of
+ ``niter + 1`` runs of the local minimizer.
+ T : float, optional
+ The "temperature" parameter for the acceptance or rejection criterion.
+ Higher "temperatures" mean that larger jumps in function value will be
+ accepted. For best results `T` should be comparable to the
+ separation (in function value) between local minima.
+ stepsize : float, optional
+ Maximum step size for use in the random displacement.
+ minimizer_kwargs : dict, optional
+ Extra keyword arguments to be passed to the local minimizer
+ `scipy.optimize.minimize` Some important options could be:
+
+ method : str
+ The minimization method (e.g. ``"L-BFGS-B"``)
+ args : tuple
+ Extra arguments passed to the objective function (`func`) and
+ its derivatives (Jacobian, Hessian).
+
+ take_step : callable ``take_step(x)``, optional
+ Replace the default step-taking routine with this routine. The default
+ step-taking routine is a random displacement of the coordinates, but
+ other step-taking algorithms may be better for some systems.
+ `take_step` can optionally have the attribute ``take_step.stepsize``.
+ If this attribute exists, then `basinhopping` will adjust
+ ``take_step.stepsize`` in order to try to optimize the global minimum
+ search.
+ accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional
+ Define a test which will be used to judge whether to accept the
+ step. This will be used in addition to the Metropolis test based on
+ "temperature" `T`. The acceptable return values are True,
+ False, or ``"force accept"``. If any of the tests return False
+ then the step is rejected. If the latter, then this will override any
+ other tests in order to accept the step. This can be used, for example,
+ to forcefully escape from a local minimum that `basinhopping` is
+ trapped in.
+ callback : callable, ``callback(x, f, accept)``, optional
+ A callback function which will be called for all minima found. ``x``
+ and ``f`` are the coordinates and function value of the trial minimum,
+ and ``accept`` is whether that minimum was accepted. This can
+ be used, for example, to save the lowest N minima found. Also,
+ `callback` can be used to specify a user defined stop criterion by
+ optionally returning True to stop the `basinhopping` routine.
+ interval : int, optional
+ interval for how often to update the `stepsize`
+ disp : bool, optional
+ Set to True to print status messages
+ niter_success : int, optional
+ Stop the run if the global minimum candidate remains the same for this
+ number of iterations.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+ The random numbers generated only affect the default Metropolis
+ `accept_test` and the default `take_step`. If you supply your own
+ `take_step` and `accept_test`, and these functions use random
+ number generation, then those functions are responsible for the state
+ of their random number generator.
+ target_accept_rate : float, optional
+ The target acceptance rate that is used to adjust the `stepsize`.
+ If the current acceptance rate is greater than the target,
+ then the `stepsize` is increased. Otherwise, it is decreased.
+ Range is (0, 1). Default is 0.5.
+
+ .. versionadded:: 1.8.0
+
+ stepwise_factor : float, optional
+ The `stepsize` is multiplied or divided by this stepwise factor upon
+ each update. Range is (0, 1). Default is 0.9.
+
+ .. versionadded:: 1.8.0
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are: ``x`` the solution array, ``fun`` the value
+ of the function at the solution, and ``message`` which describes the
+ cause of the termination. The ``OptimizeResult`` object returned by the
+ selected minimizer at the lowest minimum is also contained within this
+ object and can be accessed through the ``lowest_optimization_result``
+ attribute. ``lowest_optimization_result`` will only be updated if a
+ local minimization was successful.
+ See `OptimizeResult` for a description of other attributes.
+
+ See Also
+ --------
+ minimize :
+ The local minimization function called once for each basinhopping step.
+ `minimizer_kwargs` is passed to this routine.
+
+ Notes
+ -----
+ Basin-hopping is a stochastic algorithm which attempts to find the global
+ minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
+ [4]_. The algorithm in its current form was described by David Wales and
+ Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.
+
+ The algorithm is iterative with each cycle composed of the following
+ features
+
+ 1) random perturbation of the coordinates
+
+ 2) local minimization
+
+ 3) accept or reject the new coordinates based on the minimized function
+ value
+
+ The acceptance test used here is the Metropolis criterion of standard Monte
+ Carlo algorithms, although there are many other possibilities [3]_.
+
+ This global minimization method has been shown to be extremely efficient
+ for a wide variety of problems in physics and chemistry. It is
+ particularly useful when the function has many minima separated by large
+ barriers. See the `Cambridge Cluster Database
+ `_ for databases of molecular
+ systems that have been optimized primarily using basin-hopping. This
+ database includes minimization problems exceeding 300 degrees of freedom.
+
+ See the free software program `GMIN `_
+ for a Fortran implementation of basin-hopping. This implementation has many
+ variations of the procedure described above, including more
+ advanced step taking algorithms and alternate acceptance criterion.
+
+ For stochastic global optimization there is no way to determine if the true
+ global minimum has actually been found. Instead, as a consistency check,
+ the algorithm can be run from a number of different random starting points
+ to ensure the lowest minimum found in each example has converged to the
+ global minimum. For this reason, `basinhopping` will by default simply
+ run for the number of iterations `niter` and return the lowest minimum
+ found. It is left to the user to ensure that this is in fact the global
+ minimum.
+
+ Choosing `stepsize`: This is a crucial parameter in `basinhopping` and
+ depends on the problem being solved. The step is chosen uniformly in the
+ region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it
+ should be comparable to the typical separation (in argument values) between
+ local minima of the function being optimized. `basinhopping` will, by
+ default, adjust `stepsize` to find an optimal value, but this may take
+ many iterations. You will get quicker results if you set a sensible
+ initial value for ``stepsize``.
+
+ Choosing `T`: The parameter `T` is the "temperature" used in the
+ Metropolis criterion. Basinhopping steps are always accepted if
+ ``func(xnew) < func(xold)``. Otherwise, they are accepted with
+ probability::
+
+ exp( -(func(xnew) - func(xold)) / T )
+
+ So, for best results, `T` should to be comparable to the typical
+ difference (in function values) between local minima. (The height of
+ "walls" between local minima is irrelevant.)
+
+ If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all
+ steps that increase energy are rejected.
+
+ .. versionadded:: 0.12.0
+
+ References
+ ----------
+ .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
+ Cambridge, UK.
+ .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
+ the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
+ 110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111.
+ .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
+ multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
+ 1987, 84, 6611.
+ .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
+ crystals, and biomolecules, Science, 1999, 285, 1368.
+ .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as
+ a General and Versatile Optimization Framework for the Characterization
+ of Biological Macromolecules, Advances in Artificial Intelligence,
+ Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832`
+
+ Examples
+ --------
+ The following example is a 1-D minimization problem, with many
+ local minima superimposed on a parabola.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import basinhopping
+ >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
+ >>> x0 = [1.]
+
+ Basinhopping, internally, uses a local minimization algorithm. We will use
+ the parameter `minimizer_kwargs` to tell basinhopping which algorithm to
+ use and how to set up that minimizer. This parameter will be passed to
+ `scipy.optimize.minimize`.
+
+ >>> minimizer_kwargs = {"method": "BFGS"}
+ >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=200)
+ >>> # the global minimum is:
+ >>> ret.x, ret.fun
+ -0.1951, -1.0009
+
+ Next consider a 2-D minimization problem. Also, this time, we
+ will use gradient information to significantly speed up the search.
+
+ >>> def func2d(x):
+ ... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
+ ... 0.2) * x[0]
+ ... df = np.zeros(2)
+ ... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
+ ... df[1] = 2. * x[1] + 0.2
+ ... return f, df
+
+ We'll also use a different local minimization algorithm. Also, we must tell
+ the minimizer that our function returns both energy and gradient (Jacobian).
+
+ >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
+ >>> x0 = [1.0, 1.0]
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=200)
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
+ ... ret.x[1],
+ ... ret.fun))
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
+
+ Here is an example using a custom step-taking routine. Imagine you want
+ the first coordinate to take larger steps than the rest of the coordinates.
+ This can be implemented like so:
+
+ >>> class MyTakeStep:
+ ... def __init__(self, stepsize=0.5):
+ ... self.stepsize = stepsize
+ ... self.rng = np.random.default_rng()
+ ... def __call__(self, x):
+ ... s = self.stepsize
+ ... x[0] += self.rng.uniform(-2.*s, 2.*s)
+ ... x[1:] += self.rng.uniform(-s, s, x[1:].shape)
+ ... return x
+
+ Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
+ of `stepsize` to optimize the search. We'll use the same 2-D function as
+ before
+
+ >>> mytakestep = MyTakeStep()
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=200, take_step=mytakestep)
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
+ ... ret.x[1],
+ ... ret.fun))
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
+
+ Now, let's do an example using a custom callback function which prints the
+ value of every minimum found
+
+ >>> def print_fun(x, f, accepted):
+ ... print("at minimum %.4f accepted %d" % (f, int(accepted)))
+
+ We'll run it for only 10 basinhopping steps this time.
+
+ >>> rng = np.random.default_rng()
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=10, callback=print_fun, rng=rng)
+ at minimum 0.4159 accepted 1
+ at minimum -0.4317 accepted 1
+ at minimum -1.0109 accepted 1
+ at minimum -0.9073 accepted 1
+ at minimum -0.4317 accepted 0
+ at minimum -0.1021 accepted 1
+ at minimum -0.7425 accepted 1
+ at minimum -0.9073 accepted 1
+ at minimum -0.4317 accepted 0
+ at minimum -0.7425 accepted 1
+ at minimum -0.9073 accepted 1
+
+ The minimum at -1.0109 is actually the global minimum, found already on the
+ 8th iteration.
+
+ """ # numpy/numpydoc#87 # noqa: E501
+ if target_accept_rate <= 0. or target_accept_rate >= 1.:
+ raise ValueError('target_accept_rate has to be in range (0, 1)')
+ if stepwise_factor <= 0. or stepwise_factor >= 1.:
+ raise ValueError('stepwise_factor has to be in range (0, 1)')
+
+ x0 = np.array(x0)
+
+ # set up the np.random generator
+ rng = check_random_state(rng)
+
+ # set up minimizer
+ if minimizer_kwargs is None:
+ minimizer_kwargs = dict()
+ wrapped_minimizer = MinimizerWrapper(scipy.optimize.minimize, func,
+ **minimizer_kwargs)
+
+ # set up step-taking algorithm
+ if take_step is not None:
+ if not callable(take_step):
+ raise TypeError("take_step must be callable")
+ # if take_step.stepsize exists then use AdaptiveStepsize to control
+ # take_step.stepsize
+ if hasattr(take_step, "stepsize"):
+ take_step_wrapped = AdaptiveStepsize(
+ take_step, interval=interval,
+ accept_rate=target_accept_rate,
+ factor=stepwise_factor,
+ verbose=disp)
+ else:
+ take_step_wrapped = take_step
+ else:
+ # use default
+ displace = RandomDisplacement(stepsize=stepsize, rng=rng)
+ take_step_wrapped = AdaptiveStepsize(displace, interval=interval,
+ accept_rate=target_accept_rate,
+ factor=stepwise_factor,
+ verbose=disp)
+
+ # set up accept tests
+ accept_tests = []
+ if accept_test is not None:
+ if not callable(accept_test):
+ raise TypeError("accept_test must be callable")
+ accept_tests = [accept_test]
+
+ # use default
+ metropolis = Metropolis(T, rng=rng)
+ accept_tests.append(metropolis)
+
+ if niter_success is None:
+ niter_success = niter + 2
+
+ bh = BasinHoppingRunner(x0, wrapped_minimizer, take_step_wrapped,
+ accept_tests, disp=disp)
+
+ # The wrapped minimizer is called once during construction of
+ # BasinHoppingRunner, so run the callback
+ if callable(callback):
+ callback(bh.storage.minres.x, bh.storage.minres.fun, True)
+
+ # start main iteration loop
+ count, i = 0, 0
+ message = ["requested number of basinhopping iterations completed"
+ " successfully"]
+ for i in range(niter):
+ new_global_min = bh.one_cycle()
+
+ if callable(callback):
+ # should we pass a copy of x?
+ val = callback(bh.xtrial, bh.energy_trial, bh.accept)
+ if val is not None:
+ if val:
+ message = ["callback function requested stop early by"
+ "returning True"]
+ break
+
+ count += 1
+ if new_global_min:
+ count = 0
+ elif count > niter_success:
+ message = ["success condition satisfied"]
+ break
+
+ # prepare return object
+ res = bh.res
+ res.lowest_optimization_result = bh.storage.get_lowest()
+ res.x = np.copy(res.lowest_optimization_result.x)
+ res.fun = res.lowest_optimization_result.fun
+ res.message = message
+ res.nit = i + 1
+ res.success = res.lowest_optimization_result.success
+ return res
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..3b839600b3a8dd002cb4aaa719d8f587717001c9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:18c2834fba6309326fbd70c99e92622669718397c3b965de131894fd99cdab6f
+size 191104
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_bracket.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0f84ef6e07092953b18d448173163ca574c90d5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_bracket.py
@@ -0,0 +1,711 @@
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import array_namespace, xp_ravel, xp_promote
+
+_ELIMITS = -1 # used in _bracket_root
+_ESTOPONESIDE = 2 # used in _bracket_root
+
+def _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, kwargs, maxiter):
+
+ if not callable(func):
+ raise ValueError('`func` must be callable.')
+
+ if not np.iterable(args):
+ args = (args,)
+
+ xp = array_namespace(xl0, xr0, xmin, xmax, factor, *args)
+
+ # If xr0 is not supplied, fill with a dummy value for the sake of
+ # broadcasting. We need to wait until xmax has been validated to
+ # compute the default value.
+ xr0_not_supplied = False
+ if xr0 is None:
+ xr0 = xp.nan
+ xr0_not_supplied = True
+
+ xmin = -xp.inf if xmin is None else xmin
+ xmax = xp.inf if xmax is None else xmax
+ factor = 2. if factor is None else factor
+ xl0, xr0, xmin, xmax, factor = xp_promote(
+ xl0, xr0, xmin, xmax, factor, broadcast=True, force_floating=True, xp=xp)
+
+ if not xp.isdtype(xl0.dtype, ('integral', 'real floating')):
+ raise ValueError('`xl0` must be numeric and real.')
+
+ if (not xp.isdtype(xr0.dtype, "numeric")
+ or xp.isdtype(xr0.dtype, "complex floating")):
+ raise ValueError('`xr0` must be numeric and real.')
+
+ if (not xp.isdtype(xmin.dtype, "numeric")
+ or xp.isdtype(xmin.dtype, "complex floating")):
+ raise ValueError('`xmin` must be numeric and real.')
+
+ if (not xp.isdtype(xmax.dtype, "numeric")
+ or xp.isdtype(xmax.dtype, "complex floating")):
+ raise ValueError('`xmax` must be numeric and real.')
+
+ if (not xp.isdtype(factor.dtype, "numeric")
+ or xp.isdtype(factor.dtype, "complex floating")):
+ raise ValueError('`factor` must be numeric and real.')
+ if not xp.all(factor > 1):
+ raise ValueError('All elements of `factor` must be greater than 1.')
+
+ # Calculate the default value of xr0 if a value has not been supplied.
+ # Be careful to ensure xr0 is not larger than xmax.
+ if xr0_not_supplied:
+ xr0 = xl0 + xp.minimum((xmax - xl0)/ 8, xp.ones_like(xmax))
+ xr0 = xp.astype(xr0, xl0.dtype, copy=False)
+
+ maxiter = xp.asarray(maxiter)
+ message = '`maxiter` must be a non-negative integer.'
+ if (not xp.isdtype(maxiter.dtype, "numeric") or maxiter.shape != tuple()
+ or xp.isdtype(maxiter.dtype, "complex floating")):
+ raise ValueError(message)
+ maxiter_int = int(maxiter[()])
+ if not maxiter == maxiter_int or maxiter < 0:
+ raise ValueError(message)
+
+ return func, xl0, xr0, xmin, xmax, factor, args, kwargs, maxiter, xp
+
+
+def _bracket_root(func, xl0, xr0=None, *, xmin=None, xmax=None, factor=None,
+ args=(), kwargs=None, maxiter=1000):
+ """Bracket the root of a monotonic scalar function of one variable
+
+ This function works elementwise when `xl0`, `xr0`, `xmin`, `xmax`, `factor`, and
+ the elements of `args` are broadcastable arrays.
+
+ Parameters
+ ----------
+ func : callable
+ The function for which the root is to be bracketed.
+ The signature must be::
+
+ func(x: ndarray, *args) -> ndarray
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with `x`. ``func`` must be an elementwise function: each element
+ ``func(x)[i]`` must equal ``func(x[i])`` for all indices ``i``.
+ xl0, xr0: float array_like
+ Starting guess of bracket, which need not contain a root. If `xr0` is
+ not provided, ``xr0 = xl0 + 1``. Must be broadcastable with one another.
+ xmin, xmax : float array_like, optional
+ Minimum and maximum allowable endpoints of the bracket, inclusive. Must
+ be broadcastable with `xl0` and `xr0`.
+ factor : float array_like, default: 2
+ The factor used to grow the bracket. See notes for details.
+ args : tuple, optional
+ Additional positional arguments to be passed to `func`. Must be arrays
+ broadcastable with `xl0`, `xr0`, `xmin`, and `xmax`. If the callable to be
+ bracketed requires arguments that are not broadcastable with these
+ arrays, wrap that callable with `func` such that `func` accepts
+ only `x` and broadcastable arrays.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `func`. See `args`.
+ maxiter : int, optional
+ The maximum number of iterations of the algorithm to perform.
+
+ Returns
+ -------
+ res : _RichResult
+ An instance of `scipy._lib._util._RichResult` with the following
+ attributes. The descriptions are written as though the values will be
+ scalars; however, if `func` returns an array, the outputs will be
+ arrays of the same shape.
+
+ xl, xr : float
+ The lower and upper ends of the bracket, if the algorithm
+ terminated successfully.
+ fl, fr : float
+ The function value at the lower and upper ends of the bracket.
+ nfev : int
+ The number of function evaluations required to find the bracket.
+ This is distinct from the number of times `func` is *called*
+ because the function may evaluated at multiple points in a single
+ call.
+ nit : int
+ The number of iterations of the algorithm that were performed.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm produced a valid bracket.
+ - ``-1`` : The bracket expanded to the allowable limits without finding a bracket.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : Iteration was terminated by `callback`.
+ - ``-5``: The initial bracket does not satisfy `xmin <= xl0 < xr0 < xmax`.
+ - ``1`` : The algorithm is proceeding normally (in `callback` only).
+ - ``2`` : A bracket was found in the opposite search direction (in `callback` only).
+
+ success : bool
+ ``True`` when the algorithm terminated successfully (status ``0``).
+
+ Notes
+ -----
+ This function generalizes an algorithm found in pieces throughout
+ `scipy.stats`. The strategy is to iteratively grow the bracket ``(l, r)``
+ until ``func(l) < 0 < func(r)``. The bracket grows to the left as follows.
+
+ - If `xmin` is not provided, the distance between `xl0` and `l` is iteratively
+ increased by `factor`.
+ - If `xmin` is provided, the distance between `xmin` and `l` is iteratively
+ decreased by `factor`. Note that this also *increases* the bracket size.
+
+ Growth of the bracket to the right is analogous.
+
+ Growth of the bracket in one direction stops when the endpoint is no longer
+ finite, the function value at the endpoint is no longer finite, or the
+ endpoint reaches its limiting value (`xmin` or `xmax`). Iteration terminates
+ when the bracket stops growing in both directions, the bracket surrounds
+ the root, or a root is found (accidentally).
+
+ If two brackets are found - that is, a bracket is found on both sides in
+ the same iteration, the smaller of the two is returned.
+ If roots of the function are found, both `l` and `r` are set to the
+ leftmost root.
+
+ """ # noqa: E501
+ # Todo:
+ # - find bracket with sign change in specified direction
+ # - Add tolerance
+ # - allow factor < 1?
+
+ callback = None # works; I just don't want to test it
+ temp = _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, kwargs, maxiter)
+ func, xl0, xr0, xmin, xmax, factor, args, kwargs, maxiter, xp = temp
+
+ xs = (xl0, xr0)
+ temp = eim._initialize(func, xs, args, kwargs=kwargs)
+ func, xs, fs, args, shape, dtype, xp = temp # line split for PEP8
+ xl0, xr0 = xs
+ xmin = xp_ravel(xp.astype(xp.broadcast_to(xmin, shape), dtype, copy=False), xp=xp)
+ xmax = xp_ravel(xp.astype(xp.broadcast_to(xmax, shape), dtype, copy=False), xp=xp)
+ invalid_bracket = ~((xmin <= xl0) & (xl0 < xr0) & (xr0 <= xmax))
+
+ # The approach is to treat the left and right searches as though they were
+ # (almost) totally independent one-sided bracket searches. (The interaction
+ # is considered when checking for termination and preparing the result
+ # object.)
+ # `x` is the "moving" end of the bracket
+ x = xp.concat(xs)
+ f = xp.concat(fs)
+ invalid_bracket = xp.concat((invalid_bracket, invalid_bracket))
+ n = x.shape[0] // 2
+
+ # `x_last` is the previous location of the moving end of the bracket. If
+ # the signs of `f` and `f_last` are different, `x` and `x_last` form a
+ # bracket.
+ x_last = xp.concat((x[n:], x[:n]))
+ f_last = xp.concat((f[n:], f[:n]))
+ # `x0` is the "fixed" end of the bracket.
+ x0 = x_last
+ # We don't need to retain the corresponding function value, since the
+ # fixed end of the bracket is only needed to compute the new value of the
+ # moving end; it is never returned.
+ limit = xp.concat((xmin, xmax))
+
+ factor = xp_ravel(xp.broadcast_to(factor, shape), xp=xp)
+ factor = xp.astype(factor, dtype, copy=False)
+ factor = xp.concat((factor, factor))
+
+ active = xp.arange(2*n)
+ args = [xp.concat((arg, arg)) for arg in args]
+
+ # This is needed due to inner workings of `eim._loop`.
+ # We're abusing it a tiny bit.
+ shape = shape + (2,)
+
+ # `d` is for "distance".
+ # For searches without a limit, the distance between the fixed end of the
+ # bracket `x0` and the moving end `x` will grow by `factor` each iteration.
+ # For searches with a limit, the distance between the `limit` and moving
+ # end of the bracket `x` will shrink by `factor` each iteration.
+ i = xp.isinf(limit)
+ ni = ~i
+ d = xp.zeros_like(x)
+ d[i] = x[i] - x0[i]
+ d[ni] = limit[ni] - x[ni]
+
+ status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32) # in progress
+ status[invalid_bracket] = eim._EINPUTERR
+ nit, nfev = 0, 1 # one function evaluation per side performed above
+
+ work = _RichResult(x=x, x0=x0, f=f, limit=limit, factor=factor,
+ active=active, d=d, x_last=x_last, f_last=f_last,
+ nit=nit, nfev=nfev, status=status, args=args,
+ xl=xp.nan, xr=xp.nan, fl=xp.nan, fr=xp.nan, n=n)
+ res_work_pairs = [('status', 'status'), ('xl', 'xl'), ('xr', 'xr'),
+ ('nit', 'nit'), ('nfev', 'nfev'), ('fl', 'fl'),
+ ('fr', 'fr'), ('x', 'x'), ('f', 'f'),
+ ('x_last', 'x_last'), ('f_last', 'f_last')]
+
+ def pre_func_eval(work):
+ # Initialize moving end of bracket
+ x = xp.zeros_like(work.x)
+
+ # Unlimited brackets grow by `factor` by increasing distance from fixed
+ # end to moving end.
+ i = xp.isinf(work.limit) # indices of unlimited brackets
+ work.d[i] *= work.factor[i]
+ x[i] = work.x0[i] + work.d[i]
+
+ # Limited brackets grow by decreasing the distance from the limit to
+ # the moving end.
+ ni = ~i # indices of limited brackets
+ work.d[ni] /= work.factor[ni]
+ x[ni] = work.limit[ni] - work.d[ni]
+
+ return x
+
+ def post_func_eval(x, f, work):
+ # Keep track of the previous location of the moving end so that we can
+ # return a narrower bracket. (The alternative is to remember the
+ # original fixed end, but then the bracket would be wider than needed.)
+ work.x_last = work.x
+ work.f_last = work.f
+ work.x = x
+ work.f = f
+
+ def check_termination(work):
+ # Condition 0: initial bracket is invalid
+ stop = (work.status == eim._EINPUTERR)
+
+ # Condition 1: a valid bracket (or the root itself) has been found
+ sf = xp.sign(work.f)
+ sf_last = xp.sign(work.f_last)
+ i = ((sf_last == -sf) | (sf_last == 0) | (sf == 0)) & ~stop
+ work.status[i] = eim._ECONVERGED
+ stop[i] = True
+
+ # Condition 2: the other side's search found a valid bracket.
+ # (If we just found a bracket with the rightward search, we can stop
+ # the leftward search, and vice-versa.)
+ # To do this, we need to set the status of the other side's search;
+ # this is tricky because `work.status` contains only the *active*
+ # elements, so we don't immediately know the index of the element we
+ # need to set - or even if it's still there. (That search may have
+ # terminated already, e.g. by reaching its `limit`.)
+ # To facilitate this, `work.active` contains a unit integer index of
+ # each search. Index `k` (`k < n)` and `k + n` correspond with a
+ # leftward and rightward search, respectively. Elements are removed
+ # from `work.active` just as they are removed from `work.status`, so
+ # we use `work.active` to help find the right location in
+ # `work.status`.
+ # Get the integer indices of the elements that can also stop
+ also_stop = (work.active[i] + work.n) % (2*work.n)
+ # Check whether they are still active. We want to find the indices
+ # in work.active where the associated values in work.active are
+ # contained in also_stop. xp.searchsorted let's us take advantage
+ # of work.active being sorted, but requires some hackery because
+ # searchsorted solves the separate but related problem of finding
+ # the indices where the values in also_stop should be added to
+ # maintain sorted order.
+ j = xp.searchsorted(work.active, also_stop)
+ # If the location exceeds the length of the `work.active`, they are
+ # not there. This happens when a value in also_stop is larger than
+ # the greatest value in work.active. This case needs special handling
+ # because we cannot simply check that also_stop == work.active[j].
+ mask = j < work.active.shape[0]
+ # Note that we also have to use the mask to filter also_stop to ensure
+ # that also_stop and j will still have the same shape.
+ j, also_stop = j[mask], also_stop[mask]
+ j = j[also_stop == work.active[j]]
+ # Now convert these to boolean indices to use with `work.status`.
+ i = xp.zeros_like(stop)
+ i[j] = True # boolean indices of elements that can also stop
+ i = i & ~stop
+ work.status[i] = _ESTOPONESIDE
+ stop[i] = True
+
+ # Condition 3: moving end of bracket reaches limit
+ i = (work.x == work.limit) & ~stop
+ work.status[i] = _ELIMITS
+ stop[i] = True
+
+ # Condition 4: non-finite value encountered
+ i = ~(xp.isfinite(work.x) & xp.isfinite(work.f)) & ~stop
+ work.status[i] = eim._EVALUEERR
+ stop[i] = True
+
+ return stop
+
+ def post_termination_check(work):
+ pass
+
+ def customize_result(res, shape):
+ n = res['x'].shape[0] // 2
+
+ # To avoid ambiguity, below we refer to `xl0`, the initial left endpoint
+ # as `a` and `xr0`, the initial right endpoint, as `b`.
+ # Because we treat the two one-sided searches as though they were
+ # independent, what we keep track of in `work` and what we want to
+ # return in `res` look quite different. Combine the results from the
+ # two one-sided searches before reporting the results to the user.
+ # - "a" refers to the leftward search (the moving end started at `a`)
+ # - "b" refers to the rightward search (the moving end started at `b`)
+ # - "l" refers to the left end of the bracket (closer to -oo)
+ # - "r" refers to the right end of the bracket (closer to +oo)
+ xal = res['x'][:n]
+ xar = res['x_last'][:n]
+ xbl = res['x_last'][n:]
+ xbr = res['x'][n:]
+
+ fal = res['f'][:n]
+ far = res['f_last'][:n]
+ fbl = res['f_last'][n:]
+ fbr = res['f'][n:]
+
+ # Initialize the brackets and corresponding function values to return
+ # to the user. Brackets may not be valid (e.g. there is no root,
+ # there weren't enough iterations, NaN encountered), but we still need
+ # to return something. One option would be all NaNs, but what I've
+ # chosen here is the left- and right-most points at which the function
+ # has been evaluated. This gives the user some information about what
+ # interval of the real line has been searched and shows that there is
+ # no sign change between the two ends.
+ xl = xp.asarray(xal, copy=True)
+ fl = xp.asarray(fal, copy=True)
+ xr = xp.asarray(xbr, copy=True)
+ fr = xp.asarray(fbr, copy=True)
+
+ # `status` indicates whether the bracket is valid or not. If so,
+ # we want to adjust the bracket we return to be the narrowest possible
+ # given the points at which we evaluated the function.
+ # For example if bracket "a" is valid and smaller than bracket "b" OR
+ # if bracket "a" is valid and bracket "b" is not valid, we want to
+ # return bracket "a" (and vice versa).
+ sa = res['status'][:n]
+ sb = res['status'][n:]
+
+ da = xar - xal
+ db = xbr - xbl
+
+ i1 = ((da <= db) & (sa == 0)) | ((sa == 0) & (sb != 0))
+ i2 = ((db <= da) & (sb == 0)) | ((sb == 0) & (sa != 0))
+
+ xr[i1] = xar[i1]
+ fr[i1] = far[i1]
+ xl[i2] = xbl[i2]
+ fl[i2] = fbl[i2]
+
+ # Finish assembling the result object
+ res['xl'] = xl
+ res['xr'] = xr
+ res['fl'] = fl
+ res['fr'] = fr
+
+ res['nit'] = xp.maximum(res['nit'][:n], res['nit'][n:])
+ res['nfev'] = res['nfev'][:n] + res['nfev'][n:]
+ # If the status on one side is zero, the status is zero. In any case,
+ # report the status from one side only.
+ res['status'] = xp.where(sa == 0, sa, sb)
+ res['success'] = (res['status'] == 0)
+
+ del res['x']
+ del res['f']
+ del res['x_last']
+ del res['f_last']
+
+ return shape[:-1]
+
+ return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+ pre_func_eval, post_func_eval, check_termination,
+ post_termination_check, customize_result, res_work_pairs,
+ xp)
+
+
+def _bracket_minimum_iv(func, xm0, xl0, xr0, xmin, xmax, factor, args, kwargs, maxiter):
+
+ if not callable(func):
+ raise ValueError('`func` must be callable.')
+
+ if not np.iterable(args):
+ args = (args,)
+
+ xp = array_namespace(xm0, xl0, xr0, xmin, xmax, factor, *args)
+
+ xmin = -xp.inf if xmin is None else xmin
+ xmax = xp.inf if xmax is None else xmax
+
+ # If xl0 (xr0) is not supplied, fill with a dummy value for the sake
+ # of broadcasting. We need to wait until xmin (xmax) has been validated
+ # to compute the default values.
+ xl0_not_supplied = False
+ if xl0 is None:
+ xl0 = xp.nan
+ xl0_not_supplied = True
+
+ xr0_not_supplied = False
+ if xr0 is None:
+ xr0 = xp.nan
+ xr0_not_supplied = True
+
+ factor = 2.0 if factor is None else factor
+
+ xm0, xl0, xr0, xmin, xmax, factor = xp_promote(
+ xm0, xl0, xr0, xmin, xmax, factor, broadcast=True, force_floating=True, xp=xp)
+
+ if not xp.isdtype(xm0.dtype, ('integral', 'real floating')):
+ raise ValueError('`xm0` must be numeric and real.')
+
+ if (not xp.isdtype(xl0.dtype, "numeric")
+ or xp.isdtype(xl0.dtype, "complex floating")):
+ raise ValueError('`xl0` must be numeric and real.')
+
+ if (not xp.isdtype(xr0.dtype, "numeric")
+ or xp.isdtype(xr0.dtype, "complex floating")):
+ raise ValueError('`xr0` must be numeric and real.')
+
+ if (not xp.isdtype(xmin.dtype, "numeric")
+ or xp.isdtype(xmin.dtype, "complex floating")):
+ raise ValueError('`xmin` must be numeric and real.')
+
+ if (not xp.isdtype(xmax.dtype, "numeric")
+ or xp.isdtype(xmax.dtype, "complex floating")):
+ raise ValueError('`xmax` must be numeric and real.')
+
+ if (not xp.isdtype(factor.dtype, "numeric")
+ or xp.isdtype(factor.dtype, "complex floating")):
+ raise ValueError('`factor` must be numeric and real.')
+ if not xp.all(factor > 1):
+ raise ValueError('All elements of `factor` must be greater than 1.')
+
+ # Calculate default values of xl0 and/or xr0 if they have not been supplied
+ # by the user. We need to be careful to ensure xl0 and xr0 are not outside
+ # of (xmin, xmax).
+ if xl0_not_supplied:
+ xl0 = xm0 - xp.minimum((xm0 - xmin)/16, 0.5)
+ xl0 = xp.astype(xl0, xm0.dtype, copy=False)
+ if xr0_not_supplied:
+ xr0 = xm0 + xp.minimum((xmax - xm0)/16, 0.5)
+ xr0 = xp.astype(xr0, xm0.dtype, copy=False)
+
+ maxiter = xp.asarray(maxiter)
+ message = '`maxiter` must be a non-negative integer.'
+ if (not xp.isdtype(maxiter.dtype, "numeric") or maxiter.shape != tuple()
+ or xp.isdtype(maxiter.dtype, "complex floating")):
+ raise ValueError(message)
+ maxiter_int = int(maxiter[()])
+ if not maxiter == maxiter_int or maxiter < 0:
+ raise ValueError(message)
+
+ return func, xm0, xl0, xr0, xmin, xmax, factor, args, kwargs, maxiter, xp
+
+
+def _bracket_minimum(func, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None,
+ factor=None, args=(), kwargs=None, maxiter=1000):
+ """Bracket the minimum of a unimodal scalar function of one variable
+
+ This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`,
+ and the elements of `args` are broadcastable arrays.
+
+ Parameters
+ ----------
+ func : callable
+ The function for which the minimum is to be bracketed.
+ The signature must be::
+
+ func(x: ndarray, *args) -> ndarray
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with ``x``. `func` must be an elementwise function: each element
+ ``func(x)[i]`` must equal ``func(x[i])`` for all indices `i`.
+ xm0: float array_like
+ Starting guess for middle point of bracket.
+ xl0, xr0: float array_like, optional
+ Starting guesses for left and right endpoints of the bracket. Must be
+ broadcastable with one another and with `xm0`.
+ xmin, xmax : float array_like, optional
+ Minimum and maximum allowable endpoints of the bracket, inclusive. Must
+ be broadcastable with `xl0`, `xm0`, and `xr0`.
+ factor : float array_like, optional
+ Controls expansion of bracket endpoint in downhill direction. Works
+ differently in the cases where a limit is set in the downhill direction
+ with `xmax` or `xmin`. See Notes.
+ args : tuple, optional
+ Additional positional arguments to be passed to `func`. Must be arrays
+ broadcastable with `xl0`, `xm0`, `xr0`, `xmin`, and `xmax`. If the
+ callable to be bracketed requires arguments that are not broadcastable
+ with these arrays, wrap that callable with `func` such that `func`
+ accepts only ``x`` and broadcastable arrays.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `f`. See `args`.
+ maxiter : int, optional
+ The maximum number of iterations of the algorithm to perform. The number
+ of function evaluations is three greater than the number of iterations.
+
+ Returns
+ -------
+ res : _RichResult
+ An instance of `scipy._lib._util._RichResult` with the following
+ attributes. The descriptions are written as though the values will be
+ scalars; however, if `func` returns an array, the outputs will be
+ arrays of the same shape.
+
+ xl, xm, xr : float
+ The left, middle, and right points of the bracket, if the algorithm
+ terminated successfully.
+ fl, fm, fr : float
+ The function value at the left, middle, and right points of the bracket.
+ nfev : int
+ The number of function evaluations required to find the bracket.
+ nit : int
+ The number of iterations of the algorithm that were performed.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm produced a valid bracket.
+ - ``-1`` : The bracket expanded to the allowable limits. Assuming
+ unimodality, this implies the endpoint at the limit is a
+ minimizer.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : ``None`` shall pass.
+ - ``-5`` : The initial bracket does not satisfy
+ `xmin <= xl0 < xm0 < xr0 <= xmax`.
+
+ success : bool
+ ``True`` when the algorithm terminated successfully (status ``0``).
+
+ Notes
+ -----
+ Similar to `scipy.optimize.bracket`, this function seeks to find real
+ points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``,
+ where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`,
+ this function can operate in a vectorized manner on array input, so long as
+ the input arrays are broadcastable with each other. Also unlike
+ `scipy.optimize.bracket`, users may specify minimum and maximum endpoints
+ for the desired bracket.
+
+ Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``,
+ the algorithm checks if these points already give a valid bracket. If not,
+ a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new
+ opposite endpoint, and either `xl` or `xr` becomes the new middle point,
+ depending on which direction is downhill. The algorithm repeats from here.
+
+ The new endpoint `w` is chosen differently depending on whether or not a
+ boundary `xmin` or `xmax` has been set in the downhill direction. Without
+ loss of generality, suppose the downhill direction is to the right, so that
+ ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w`
+ is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by
+ the user (defaults to 2.0) so that step sizes increase in geometric proportion.
+ If there is a boundary, `xmax` in this case, then `w` is chosen to be
+ ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at
+ `xmax`. This cautious approach ensures that a minimum near but distinct from
+ the boundary isn't missed while also detecting whether or not the `xmax` is
+ a minimizer when `xmax` is reached after a finite number of steps.
+ """ # noqa: E501
+ callback = None # works; I just don't want to test it
+
+ temp = _bracket_minimum_iv(func, xm0, xl0, xr0, xmin, xmax,
+ factor, args, kwargs, maxiter)
+ func, xm0, xl0, xr0, xmin, xmax, factor, args, kwargs, maxiter, xp = temp
+
+ xs = (xl0, xm0, xr0)
+ temp = eim._initialize(func, xs, args, kwargs=kwargs)
+ func, xs, fs, args, shape, dtype, xp = temp
+
+ xl0, xm0, xr0 = xs
+ fl0, fm0, fr0 = fs
+ xmin = xp.astype(xp.broadcast_to(xmin, shape), dtype, copy=False)
+ xmin = xp_ravel(xmin, xp=xp)
+ xmax = xp.astype(xp.broadcast_to(xmax, shape), dtype, copy=False)
+ xmax = xp_ravel(xmax, xp=xp)
+ invalid_bracket = ~((xmin <= xl0) & (xl0 < xm0) & (xm0 < xr0) & (xr0 <= xmax))
+ # We will modify factor later on so make a copy. np.broadcast_to returns
+ # a read-only view.
+ factor = xp.astype(xp.broadcast_to(factor, shape), dtype, copy=True)
+ factor = xp_ravel(factor)
+
+ # To simplify the logic, swap xl and xr if f(xl) < f(xr). We should always be
+ # marching downhill in the direction from xl to xr.
+ comp = fl0 < fr0
+ xl0[comp], xr0[comp] = xr0[comp], xl0[comp]
+ fl0[comp], fr0[comp] = fr0[comp], fl0[comp]
+ # We only need the boundary in the direction we're traveling.
+ limit = xp.where(comp, xmin, xmax)
+
+ unlimited = xp.isinf(limit)
+ limited = ~unlimited
+ step = xp.empty_like(xl0)
+
+ step[unlimited] = (xr0[unlimited] - xm0[unlimited])
+ step[limited] = (limit[limited] - xr0[limited])
+
+ # Step size is divided by factor for case where there is a limit.
+ factor[limited] = 1 / factor[limited]
+
+ status = xp.full_like(xl0, eim._EINPROGRESS, dtype=xp.int32)
+ status[invalid_bracket] = eim._EINPUTERR
+ nit, nfev = 0, 3
+
+ work = _RichResult(xl=xl0, xm=xm0, xr=xr0, xr0=xr0, fl=fl0, fm=fm0, fr=fr0,
+ step=step, limit=limit, limited=limited, factor=factor, nit=nit,
+ nfev=nfev, status=status, args=args)
+
+ res_work_pairs = [('status', 'status'), ('xl', 'xl'), ('xm', 'xm'), ('xr', 'xr'),
+ ('nit', 'nit'), ('nfev', 'nfev'), ('fl', 'fl'), ('fm', 'fm'),
+ ('fr', 'fr')]
+
+ def pre_func_eval(work):
+ work.step *= work.factor
+ x = xp.empty_like(work.xr)
+ x[~work.limited] = work.xr0[~work.limited] + work.step[~work.limited]
+ x[work.limited] = work.limit[work.limited] - work.step[work.limited]
+ # Since the new bracket endpoint is calculated from an offset with the
+ # limit, it may be the case that the new endpoint equals the old endpoint,
+ # when the old endpoint is sufficiently close to the limit. We use the
+ # limit itself as the new endpoint in these cases.
+ x[work.limited] = xp.where(
+ x[work.limited] == work.xr[work.limited],
+ work.limit[work.limited],
+ x[work.limited],
+ )
+ return x
+
+ def post_func_eval(x, f, work):
+ work.xl, work.xm, work.xr = work.xm, work.xr, x
+ work.fl, work.fm, work.fr = work.fm, work.fr, f
+
+ def check_termination(work):
+ # Condition 0: Initial bracket is invalid.
+ stop = (work.status == eim._EINPUTERR)
+
+ # Condition 1: A valid bracket has been found.
+ i = (
+ (work.fl >= work.fm) & (work.fr > work.fm)
+ | (work.fl > work.fm) & (work.fr >= work.fm)
+ ) & ~stop
+ work.status[i] = eim._ECONVERGED
+ stop[i] = True
+
+ # Condition 2: Moving end of bracket reaches limit.
+ i = (work.xr == work.limit) & ~stop
+ work.status[i] = _ELIMITS
+ stop[i] = True
+
+ # Condition 3: non-finite value encountered
+ i = ~(xp.isfinite(work.xr) & xp.isfinite(work.fr)) & ~stop
+ work.status[i] = eim._EVALUEERR
+ stop[i] = True
+
+ return stop
+
+ def post_termination_check(work):
+ pass
+
+ def customize_result(res, shape):
+ # Reorder entries of xl and xr if they were swapped due to f(xl0) < f(xr0).
+ comp = res['xl'] > res['xr']
+ res['xl'][comp], res['xr'][comp] = res['xr'][comp], res['xl'][comp]
+ res['fl'][comp], res['fr'][comp] = res['fr'][comp], res['fl'][comp]
+ return shape
+
+ return eim._loop(work, callback, shape,
+ maxiter, func, args, dtype,
+ pre_func_eval, post_func_eval,
+ check_termination, post_termination_check,
+ customize_result, res_work_pairs, xp)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..29e2576758bbe8bfb2a89e59d94d9ca6571a57cd
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.py
@@ -0,0 +1,551 @@
+import math
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import xp_copy
+
+
+def _chandrupatla(func, a, b, *, args=(), kwargs=None, xatol=None, xrtol=None,
+ fatol=None, frtol=0, maxiter=None, callback=None):
+ """Find the root of an elementwise function using Chandrupatla's algorithm.
+
+ For each element of the output of `func`, `chandrupatla` seeks the scalar
+ root that makes the element 0. This function allows for `a`, `b`, and the
+ output of `func` to be of any broadcastable shapes.
+
+ Parameters
+ ----------
+ func : callable
+ The function whose root is desired. The signature must be::
+
+ func(x: ndarray, *args) -> ndarray
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of components of any type(s).
+ ``func`` must be an elementwise function: each element ``func(x)[i]``
+ must equal ``func(x[i])`` for all indices ``i``. `_chandrupatla`
+ seeks an array ``x`` such that ``func(x)`` is an array of zeros.
+ a, b : array_like
+ The lower and upper bounds of the root of the function. Must be
+ broadcastable with one another.
+ args : tuple, optional
+ Additional positional arguments to be passed to `func`.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `func`.
+ xatol, xrtol, fatol, frtol : float, optional
+ Absolute and relative tolerances on the root and function value.
+ See Notes for details.
+ maxiter : int, optional
+ The maximum number of iterations of the algorithm to perform.
+ The default is the maximum possible number of bisections within
+ the (normal) floating point numbers of the relevant dtype.
+ callback : callable, optional
+ An optional user-supplied function to be called before the first
+ iteration and after each iteration.
+ Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+ similar to that returned by `_chandrupatla` (but containing the current
+ iterate's values of all variables). If `callback` raises a
+ ``StopIteration``, the algorithm will terminate immediately and
+ `_chandrupatla` will return a result.
+
+ Returns
+ -------
+ res : _RichResult
+ An instance of `scipy._lib._util._RichResult` with the following
+ attributes. The descriptions are written as though the values will be
+ scalars; however, if `func` returns an array, the outputs will be
+ arrays of the same shape.
+
+ x : float
+ The root of the function, if the algorithm terminated successfully.
+ nfev : int
+ The number of times the function was called to find the root.
+ nit : int
+ The number of iterations of Chandrupatla's algorithm performed.
+ status : int
+ An integer representing the exit status of the algorithm.
+ ``0`` : The algorithm converged to the specified tolerances.
+ ``-1`` : The algorithm encountered an invalid bracket.
+ ``-2`` : The maximum number of iterations was reached.
+ ``-3`` : A non-finite value was encountered.
+ ``-4`` : Iteration was terminated by `callback`.
+ ``1`` : The algorithm is proceeding normally (in `callback` only).
+ success : bool
+ ``True`` when the algorithm terminated successfully (status ``0``).
+ fun : float
+ The value of `func` evaluated at `x`.
+ xl, xr : float
+ The lower and upper ends of the bracket.
+ fl, fr : float
+ The function value at the lower and upper ends of the bracket.
+
+ Notes
+ -----
+ Implemented based on Chandrupatla's original paper [1]_.
+
+ If ``xl`` and ``xr`` are the left and right ends of the bracket,
+ ``xmin = xl if abs(func(xl)) <= abs(func(xr)) else xr``,
+ and ``fmin0 = min(func(a), func(b))``, then the algorithm is considered to
+ have converged when ``abs(xr - xl) < xatol + abs(xmin) * xrtol`` or
+ ``fun(xmin) <= fatol + abs(fmin0) * frtol``. This is equivalent to the
+ termination condition described in [1]_ with ``xrtol = 4e-10``,
+ ``xatol = 1e-5``, and ``fatol = frtol = 0``. The default values are
+ ``xatol = 4*tiny``, ``xrtol = 4*eps``, ``frtol = 0``, and ``fatol = tiny``,
+ where ``eps`` and ``tiny`` are the precision and smallest normal number
+ of the result ``dtype`` of function inputs and outputs.
+
+ References
+ ----------
+
+ .. [1] Chandrupatla, Tirupathi R.
+ "A new hybrid quadratic/bisection algorithm for finding the zero of a
+ nonlinear function without using derivatives".
+ Advances in Engineering Software, 28(3), 145-149.
+ :doi:`10.1016/s0965-9978(96)00051-8`.
+
+ See Also
+ --------
+ brentq, brenth, ridder, bisect, newton
+
+ Examples
+ --------
+ >>> from scipy import optimize
+ >>> def f(x, c):
+ ... return x**3 - 2*x - c
+ >>> c = 5
+ >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,))
+ >>> res.x
+ 2.0945514818937463
+
+ >>> c = [3, 4, 5]
+ >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,))
+ >>> res.x
+ array([1.8932892 , 2. , 2.09455148])
+
+ """
+ res = _chandrupatla_iv(func, args, kwargs, xatol, xrtol,
+ fatol, frtol, maxiter, callback)
+ func, args, kwargs, xatol, xrtol, fatol, frtol, maxiter, callback = res
+
+ # Initialization
+ temp = eim._initialize(func, (a, b), args, kwargs=kwargs)
+ func, xs, fs, args, shape, dtype, xp = temp
+ x1, x2 = xs
+ f1, f2 = fs
+ status = xp.full_like(x1, eim._EINPROGRESS,
+ dtype=xp.int32) # in progress
+ nit, nfev = 0, 2 # two function evaluations performed above
+ finfo = xp.finfo(dtype)
+ xatol = 4*finfo.smallest_normal if xatol is None else xatol
+ xrtol = 4*finfo.eps if xrtol is None else xrtol
+ fatol = finfo.smallest_normal if fatol is None else fatol
+ frtol = frtol * xp.minimum(xp.abs(f1), xp.abs(f2))
+ maxiter = (math.log2(finfo.max) - math.log2(finfo.smallest_normal)
+ if maxiter is None else maxiter)
+ work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=None, f3=None, t=0.5,
+ xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol,
+ nit=nit, nfev=nfev, status=status)
+ res_work_pairs = [('status', 'status'), ('x', 'xmin'), ('fun', 'fmin'),
+ ('nit', 'nit'), ('nfev', 'nfev'), ('xl', 'x1'),
+ ('fl', 'f1'), ('xr', 'x2'), ('fr', 'f2')]
+
+ def pre_func_eval(work):
+ # [1] Figure 1 (first box)
+ x = work.x1 + work.t * (work.x2 - work.x1)
+ return x
+
+ def post_func_eval(x, f, work):
+ # [1] Figure 1 (first diamond and boxes)
+ # Note: y/n are reversed in figure; compare to BASIC in appendix
+ work.x3, work.f3 = (xp.asarray(work.x2, copy=True),
+ xp.asarray(work.f2, copy=True))
+ j = xp.sign(f) == xp.sign(work.f1)
+ nj = ~j
+ work.x3[j], work.f3[j] = work.x1[j], work.f1[j]
+ work.x2[nj], work.f2[nj] = work.x1[nj], work.f1[nj]
+ work.x1, work.f1 = x, f
+
+ def check_termination(work):
+ # [1] Figure 1 (second diamond)
+ # Check for all terminal conditions and record statuses.
+
+ # See [1] Section 4 (first two sentences)
+ i = xp.abs(work.f1) < xp.abs(work.f2)
+ work.xmin = xp.where(i, work.x1, work.x2)
+ work.fmin = xp.where(i, work.f1, work.f2)
+ stop = xp.zeros_like(work.x1, dtype=xp.bool) # termination condition met
+
+ # If function value tolerance is met, report successful convergence,
+ # regardless of other conditions. Note that `frtol` has been redefined
+ # as `frtol = frtol * minimum(f1, f2)`, where `f1` and `f2` are the
+ # function evaluated at the original ends of the bracket.
+ i = xp.abs(work.fmin) <= work.fatol + work.frtol
+ work.status[i] = eim._ECONVERGED
+ stop[i] = True
+
+ # If the bracket is no longer valid, report failure (unless a function
+ # tolerance is met, as detected above).
+ i = (xp.sign(work.f1) == xp.sign(work.f2)) & ~stop
+ NaN = xp.asarray(xp.nan, dtype=work.xmin.dtype)
+ work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._ESIGNERR
+ stop[i] = True
+
+ # If the abscissae are non-finite or either function value is NaN,
+ # report failure.
+ x_nonfinite = ~(xp.isfinite(work.x1) & xp.isfinite(work.x2))
+ f_nan = xp.isnan(work.f1) & xp.isnan(work.f2)
+ i = (x_nonfinite | f_nan) & ~stop
+ work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._EVALUEERR
+ stop[i] = True
+
+ # This is the convergence criterion used in bisect. Chandrupatla's
+ # criterion is equivalent to this except with a factor of 4 on `xrtol`.
+ work.dx = xp.abs(work.x2 - work.x1)
+ work.tol = xp.abs(work.xmin) * work.xrtol + work.xatol
+ i = work.dx < work.tol
+ work.status[i] = eim._ECONVERGED
+ stop[i] = True
+
+ return stop
+
+ def post_termination_check(work):
+ # [1] Figure 1 (third diamond and boxes / Equation 1)
+ xi1 = (work.x1 - work.x2) / (work.x3 - work.x2)
+ with np.errstate(divide='ignore', invalid='ignore'):
+ phi1 = (work.f1 - work.f2) / (work.f3 - work.f2)
+ alpha = (work.x3 - work.x1) / (work.x2 - work.x1)
+ j = ((1 - xp.sqrt(1 - xi1)) < phi1) & (phi1 < xp.sqrt(xi1))
+
+ f1j, f2j, f3j, alphaj = work.f1[j], work.f2[j], work.f3[j], alpha[j]
+ t = xp.full_like(alpha, 0.5)
+ t[j] = (f1j / (f1j - f2j) * f3j / (f3j - f2j)
+ - alphaj * f1j / (f3j - f1j) * f2j / (f2j - f3j))
+
+ # [1] Figure 1 (last box; see also BASIC in appendix with comment
+ # "Adjust T Away from the Interval Boundary")
+ tl = 0.5 * work.tol / work.dx
+ work.t = xp.clip(t, tl, 1 - tl)
+
+ def customize_result(res, shape):
+ xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr']
+ i = res['xl'] < res['xr']
+ res['xl'] = xp.where(i, xl, xr)
+ res['xr'] = xp.where(i, xr, xl)
+ res['fl'] = xp.where(i, fl, fr)
+ res['fr'] = xp.where(i, fr, fl)
+ return shape
+
+ return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+ pre_func_eval, post_func_eval, check_termination,
+ post_termination_check, customize_result, res_work_pairs,
+ xp=xp)
+
+
+def _chandrupatla_iv(func, args, kwargs, xatol, xrtol,
+ fatol, frtol, maxiter, callback):
+ # Input validation for `_chandrupatla`
+
+ if not callable(func):
+ raise ValueError('`func` must be callable.')
+
+ if not np.iterable(args):
+ args = (args,)
+
+ # tolerances are floats, not arrays; OK to use NumPy
+ tols = np.asarray([xatol if xatol is not None else 1,
+ xrtol if xrtol is not None else 1,
+ fatol if fatol is not None else 1,
+ frtol if frtol is not None else 1])
+ if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
+ or np.any(np.isnan(tols)) or tols.shape != (4,)):
+ raise ValueError('Tolerances must be non-negative scalars.')
+
+ if maxiter is not None:
+ maxiter_int = int(maxiter)
+ if maxiter != maxiter_int or maxiter < 0:
+ raise ValueError('`maxiter` must be a non-negative integer.')
+
+ if callback is not None and not callable(callback):
+ raise ValueError('`callback` must be callable.')
+
+ return func, args, kwargs, xatol, xrtol, fatol, frtol, maxiter, callback
+
+
+def _chandrupatla_minimize(func, x1, x2, x3, *, args=(), kwargs=None, xatol=None,
+ xrtol=None, fatol=None, frtol=None, maxiter=100,
+ callback=None):
+ """Find the minimizer of an elementwise function.
+
+ For each element of the output of `func`, `_chandrupatla_minimize` seeks
+ the scalar minimizer that minimizes the element. This function allows for
+ `x1`, `x2`, `x3`, and the elements of `args` to be arrays of any
+ broadcastable shapes.
+
+ Parameters
+ ----------
+ func : callable
+ The function whose minimizer is desired. The signature must be::
+
+ func(x: ndarray, *args) -> ndarray
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with `x`. ``func`` must be an elementwise function: each element
+ ``func(x)[i]`` must equal ``func(x[i])`` for all indices ``i``.
+ `_chandrupatla` seeks an array ``x`` such that ``func(x)`` is an array
+ of minima.
+ x1, x2, x3 : array_like
+ The abscissae of a standard scalar minimization bracket. A bracket is
+ valid if ``x1 < x2 < x3`` and ``func(x1) > func(x2) <= func(x3)``.
+ Must be broadcastable with one another and `args`.
+ args : tuple, optional
+ Additional positional arguments to be passed to `func`. Must be arrays
+ broadcastable with `x1`, `x2`, and `x3`. If the callable to be
+ differentiated requires arguments that are not broadcastable with `x`,
+ wrap that callable with `func` such that `func` accepts only `x` and
+ broadcastable arrays.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `f`. See `args`.
+ xatol, xrtol, fatol, frtol : float, optional
+ Absolute and relative tolerances on the minimizer and function value.
+ See Notes for details.
+ maxiter : int, optional
+ The maximum number of iterations of the algorithm to perform.
+ callback : callable, optional
+ An optional user-supplied function to be called before the first
+ iteration and after each iteration.
+ Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+ similar to that returned by `_chandrupatla_minimize` (but containing
+ the current iterate's values of all variables). If `callback` raises a
+ ``StopIteration``, the algorithm will terminate immediately and
+ `_chandrupatla_minimize` will return a result.
+
+ Returns
+ -------
+ res : _RichResult
+ An instance of `scipy._lib._util._RichResult` with the following
+ attributes. (The descriptions are written as though the values will be
+ scalars; however, if `func` returns an array, the outputs will be
+ arrays of the same shape.)
+
+ success : bool
+ ``True`` when the algorithm terminated successfully (status ``0``).
+ status : int
+ An integer representing the exit status of the algorithm.
+ ``0`` : The algorithm converged to the specified tolerances.
+ ``-1`` : The algorithm encountered an invalid bracket.
+ ``-2`` : The maximum number of iterations was reached.
+ ``-3`` : A non-finite value was encountered.
+ ``-4`` : Iteration was terminated by `callback`.
+ ``1`` : The algorithm is proceeding normally (in `callback` only).
+ x : float
+ The minimizer of the function, if the algorithm terminated
+ successfully.
+ fun : float
+ The value of `func` evaluated at `x`.
+ nfev : int
+ The number of points at which `func` was evaluated.
+ nit : int
+ The number of iterations of the algorithm that were performed.
+ xl, xm, xr : float
+ The final three-point bracket.
+ fl, fm, fr : float
+ The function value at the bracket points.
+
+ Notes
+ -----
+ Implemented based on Chandrupatla's original paper [1]_.
+
+ If ``x1 < x2 < x3`` are the points of the bracket and ``f1 > f2 <= f3``
+ are the values of ``func`` at those points, then the algorithm is
+ considered to have converged when ``x3 - x1 <= abs(x2)*xrtol + xatol``
+ or ``(f1 - 2*f2 + f3)/2 <= abs(f2)*frtol + fatol``. Note that first of
+ these differs from the termination conditions described in [1]_. The
+ default values of `xrtol` is the square root of the precision of the
+ appropriate dtype, and ``xatol = fatol = frtol`` is the smallest normal
+ number of the appropriate dtype.
+
+ References
+ ----------
+ .. [1] Chandrupatla, Tirupathi R. (1998).
+ "An efficient quadratic fit-sectioning algorithm for minimization
+ without derivatives".
+ Computer Methods in Applied Mechanics and Engineering, 152 (1-2),
+ 211-217. :doi:`10.1016/S0045-7825(97)00190-4`.
+
+ See Also
+ --------
+ golden, brent, bounded
+
+ Examples
+ --------
+ >>> from scipy.optimize._chandrupatla import _chandrupatla_minimize
+ >>> def f(x, args=1):
+ ... return (x - args)**2
+ >>> res = _chandrupatla_minimize(f, -5, 0, 5)
+ >>> res.x
+ 1.0
+ >>> c = [1, 1.5, 2]
+ >>> res = _chandrupatla_minimize(f, -5, 0, 5, args=(c,))
+ >>> res.x
+ array([1. , 1.5, 2. ])
+ """
+ res = _chandrupatla_iv(func, args, kwargs, xatol, xrtol,
+ fatol, frtol, maxiter, callback)
+ func, args, kwargs, xatol, xrtol, fatol, frtol, maxiter, callback = res
+
+ # Initialization
+ xs = (x1, x2, x3)
+ temp = eim._initialize(func, xs, args, kwargs=kwargs)
+ func, xs, fs, args, shape, dtype, xp = temp # line split for PEP8
+ x1, x2, x3 = xs
+ f1, f2, f3 = fs
+ phi = xp.asarray(0.5 + 0.5*5**0.5, dtype=dtype)[()] # golden ratio
+ status = xp.full_like(x1, eim._EINPROGRESS, dtype=xp.int32) # in progress
+ nit, nfev = 0, 3 # three function evaluations performed above
+ fatol = xp.finfo(dtype).smallest_normal if fatol is None else fatol
+ frtol = xp.finfo(dtype).smallest_normal if frtol is None else frtol
+ xatol = xp.finfo(dtype).smallest_normal if xatol is None else xatol
+ xrtol = math.sqrt(xp.finfo(dtype).eps) if xrtol is None else xrtol
+
+ # Ensure that x1 < x2 < x3 initially.
+ xs, fs = xp.stack((x1, x2, x3)), xp.stack((f1, f2, f3))
+ i = xp.argsort(xs, axis=0)
+ x1, x2, x3 = xp.take_along_axis(xs, i, axis=0) # data-apis/array-api#808
+ f1, f2, f3 = xp.take_along_axis(fs, i, axis=0) # data-apis/array-api#808
+ q0 = xp_copy(x3) # "At the start, q0 is set at x3..." ([1] after (7))
+
+ work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=x3, f3=f3, phi=phi,
+ xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol,
+ nit=nit, nfev=nfev, status=status, q0=q0, args=args)
+ res_work_pairs = [('status', 'status'),
+ ('x', 'x2'), ('fun', 'f2'),
+ ('nit', 'nit'), ('nfev', 'nfev'),
+ ('xl', 'x1'), ('xm', 'x2'), ('xr', 'x3'),
+ ('fl', 'f1'), ('fm', 'f2'), ('fr', 'f3')]
+
+ def pre_func_eval(work):
+ # `_check_termination` is called first -> `x3 - x2 > x2 - x1`
+ # But let's calculate a few terms that we'll reuse
+ x21 = work.x2 - work.x1
+ x32 = work.x3 - work.x2
+
+ # [1] Section 3. "The quadratic minimum point Q1 is calculated using
+ # the relations developed in the previous section." [1] Section 2 (5/6)
+ A = x21 * (work.f3 - work.f2)
+ B = x32 * (work.f1 - work.f2)
+ C = A / (A + B)
+ # q1 = C * (work.x1 + work.x2) / 2 + (1 - C) * (work.x2 + work.x3) / 2
+ q1 = 0.5 * (C*(work.x1 - work.x3) + work.x2 + work.x3) # much faster
+ # this is an array, so multiplying by 0.5 does not change dtype
+
+ # "If Q1 and Q0 are sufficiently close... Q1 is accepted if it is
+ # sufficiently away from the inside point x2"
+ i = xp.abs(q1 - work.q0) < 0.5 * xp.abs(x21) # [1] (7)
+ xi = q1[i]
+ # Later, after (9), "If the point Q1 is in a +/- xtol neighborhood of
+ # x2, the new point is chosen in the larger interval at a distance
+ # tol away from x2."
+ # See also QBASIC code after "Accept Ql adjust if close to X2".
+ j = xp.abs(q1[i] - work.x2[i]) <= work.xtol[i]
+ xi[j] = work.x2[i][j] + xp.sign(x32[i][j]) * work.xtol[i][j]
+
+ # "If condition (7) is not satisfied, golden sectioning of the larger
+ # interval is carried out to introduce the new point."
+ # (For simplicity, we go ahead and calculate it for all points, but we
+ # change the elements for which the condition was satisfied.)
+ x = work.x2 + (2 - work.phi) * x32
+ x[i] = xi
+
+ # "We define Q0 as the value of Q1 at the previous iteration."
+ work.q0 = q1
+ return x
+
+ def post_func_eval(x, f, work):
+ # Standard logic for updating a three-point bracket based on a new
+ # point. In QBASIC code, see "IF SGN(X-X2) = SGN(X3-X2) THEN...".
+ # There is an awful lot of data copying going on here; this would
+ # probably benefit from code optimization or implementation in Pythran.
+ i = xp.sign(x - work.x2) == xp.sign(work.x3 - work.x2)
+ xi, x1i, x2i, x3i = x[i], work.x1[i], work.x2[i], work.x3[i],
+ fi, f1i, f2i, f3i = f[i], work.f1[i], work.f2[i], work.f3[i]
+ j = fi > f2i
+ x3i[j], f3i[j] = xi[j], fi[j]
+ j = ~j
+ x1i[j], f1i[j], x2i[j], f2i[j] = x2i[j], f2i[j], xi[j], fi[j]
+
+ ni = ~i
+ xni, x1ni, x2ni, x3ni = x[ni], work.x1[ni], work.x2[ni], work.x3[ni],
+ fni, f1ni, f2ni, f3ni = f[ni], work.f1[ni], work.f2[ni], work.f3[ni]
+ j = fni > f2ni
+ x1ni[j], f1ni[j] = xni[j], fni[j]
+ j = ~j
+ x3ni[j], f3ni[j], x2ni[j], f2ni[j] = x2ni[j], f2ni[j], xni[j], fni[j]
+
+ work.x1[i], work.x2[i], work.x3[i] = x1i, x2i, x3i
+ work.f1[i], work.f2[i], work.f3[i] = f1i, f2i, f3i
+ work.x1[ni], work.x2[ni], work.x3[ni] = x1ni, x2ni, x3ni,
+ work.f1[ni], work.f2[ni], work.f3[ni] = f1ni, f2ni, f3ni
+
+ def check_termination(work):
+ # Check for all terminal conditions and record statuses.
+ stop = xp.zeros_like(work.x1, dtype=bool) # termination condition met
+
+ # Bracket is invalid; stop and don't return minimizer/minimum
+ i = ((work.f2 > work.f1) | (work.f2 > work.f3))
+ work.x2[i], work.f2[i] = xp.nan, xp.nan
+ stop[i], work.status[i] = True, eim._ESIGNERR
+
+ # Non-finite values; stop and don't return minimizer/minimum
+ finite = xp.isfinite(work.x1+work.x2+work.x3+work.f1+work.f2+work.f3)
+ i = ~(finite | stop)
+ work.x2[i], work.f2[i] = xp.nan, xp.nan
+ stop[i], work.status[i] = True, eim._EVALUEERR
+
+ # [1] Section 3 "Points 1 and 3 are interchanged if necessary to make
+ # the (x2, x3) the larger interval."
+ # Note: I had used np.choose; this is much faster. This would be a good
+ # place to save e.g. `work.x3 - work.x2` for reuse, but I tried and
+ # didn't notice a speed boost, so let's keep it simple.
+ i = xp.abs(work.x3 - work.x2) < xp.abs(work.x2 - work.x1)
+ temp = work.x1[i]
+ work.x1[i] = work.x3[i]
+ work.x3[i] = temp
+ temp = work.f1[i]
+ work.f1[i] = work.f3[i]
+ work.f3[i] = temp
+
+ # [1] Section 3 (bottom of page 212)
+ # "We set a tolerance value xtol..."
+ work.xtol = xp.abs(work.x2) * work.xrtol + work.xatol # [1] (8)
+ # "The convergence based on interval is achieved when..."
+ # Note: Equality allowed in case of `xtol=0`
+ i = xp.abs(work.x3 - work.x2) <= 2 * work.xtol # [1] (9)
+
+ # "We define ftol using..."
+ ftol = xp.abs(work.f2) * work.frtol + work.fatol # [1] (10)
+ # "The convergence based on function values is achieved when..."
+ # Note 1: modify in place to incorporate tolerance on function value.
+ # Note 2: factor of 2 is not in the text; see QBASIC start of DO loop
+ i |= (work.f1 - 2 * work.f2 + work.f3) <= 2*ftol # [1] (11)
+ i &= ~stop
+ stop[i], work.status[i] = True, eim._ECONVERGED
+
+ return stop
+
+ def post_termination_check(work):
+ pass
+
+ def customize_result(res, shape):
+ xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr']
+ i = res['xl'] >= res['xr']
+ res['xl'] = xp.where(i, xr, xl)
+ res['xr'] = xp.where(i, xl, xr)
+ res['fl'] = xp.where(i, fr, fl)
+ res['fr'] = xp.where(i, fl, fr)
+ return shape
+
+ return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+ pre_func_eval, post_func_eval, check_termination,
+ post_termination_check, customize_result, res_work_pairs,
+ xp=xp)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_cobyla_py.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_cobyla_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d8377fd2a22f82582f27cf82f646c7350de628e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_cobyla_py.py
@@ -0,0 +1,296 @@
+"""
+Interface to Constrained Optimization By Linear Approximation
+
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ fmin_cobyla
+
+"""
+
+import numpy as np
+from scipy._lib._util import wrapped_inspect_signature
+from ._optimize import (OptimizeResult, _check_unknown_options,
+ _prepare_scalar_function)
+from ._constraints import NonlinearConstraint
+
+
+__all__ = ['fmin_cobyla']
+
+
+def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0,
+ rhoend=1e-4, maxfun=1000, disp=None, catol=2e-4,
+ *, callback=None):
+ """
+ Minimize a function using the Constrained Optimization By Linear
+ Approximation (COBYLA) method. This method uses the pure-python implementation
+ of the algorithm from PRIMA.
+
+ Parameters
+ ----------
+ func : callable
+ Function to minimize. In the form func(x, \\*args).
+ x0 : ndarray
+ Initial guess.
+ cons : sequence
+ Constraint functions; must all be ``>=0`` (a single function
+ if only 1 constraint). Each function takes the parameters `x`
+ as its first argument, and it can return either a single number or
+ an array or list of numbers.
+ args : tuple, optional
+ Extra arguments to pass to function.
+ consargs : tuple, optional
+ Extra arguments to pass to constraint functions (default of None means
+ use same extra arguments as those passed to func).
+ Use ``()`` for no extra arguments.
+ rhobeg : float, optional
+ Reasonable initial changes to the variables.
+ rhoend : float, optional
+ Final accuracy in the optimization (not precisely guaranteed). This
+ is a lower bound on the size of the trust region.
+ disp : {0, 1, 2, 3}, optional
+ Controls the frequency of output; 0 implies no output.
+ maxfun : int, optional
+ Maximum number of function evaluations.
+ catol : float, optional
+ Absolute tolerance for constraint violations.
+ callback : callable, optional
+ Called after each iteration, as ``callback(x)``, where ``x`` is the
+ current parameter vector.
+
+ Returns
+ -------
+ x : ndarray
+ The argument that minimises `f`.
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'COBYLA' `method` in particular.
+
+ Notes
+ -----
+ This algorithm is based on linear approximations to the objective
+ function and each constraint. We briefly describe the algorithm.
+
+ Suppose the function is being minimized over k variables. At the
+ jth iteration the algorithm has k+1 points v_1, ..., v_(k+1),
+ an approximate solution x_j, and a radius RHO_j.
+ (i.e., linear plus a constant) approximations to the objective
+ function and constraint functions such that their function values
+ agree with the linear approximation on the k+1 points v_1,.., v_(k+1).
+ This gives a linear program to solve (where the linear approximations
+ of the constraint functions are constrained to be non-negative).
+
+ However, the linear approximations are likely only good
+ approximations near the current simplex, so the linear program is
+ given the further requirement that the solution, which
+ will become x_(j+1), must be within RHO_j from x_j. RHO_j only
+ decreases, never increases. The initial RHO_j is rhobeg and the
+ final RHO_j is rhoend. In this way COBYLA's iterations behave
+ like a trust region algorithm.
+
+ Additionally, the linear program may be inconsistent, or the
+ approximation may give poor improvement. For details about
+ how these issues are resolved, as well as how the points v_i are
+ updated, refer to the source code or the references below.
+
+ .. versionchanged:: 1.16.0
+ The original Powell implementation was replaced by a pure
+ Python version from the PRIMA package, with bug fixes and
+ improvements being made.
+
+
+ References
+ ----------
+ Powell M.J.D. (1994), "A direct search optimization method that models
+ the objective and constraint functions by linear interpolation.", in
+ Advances in Optimization and Numerical Analysis, eds. S. Gomez and
+ J-P Hennart, Kluwer Academic (Dordrecht), pp. 51-67
+
+ Powell M.J.D. (1998), "Direct search algorithms for optimization
+ calculations", Acta Numerica 7, 287-336
+
+ Powell M.J.D. (2007), "A view of algorithms for optimization without
+ derivatives", Cambridge University Technical Report DAMTP 2007/NA03
+
+ Zhang Z. (2023), "PRIMA: Reference Implementation for Powell's Methods with
+ Modernization and Amelioration", https://www.libprima.net,
+ :doi:`10.5281/zenodo.8052654`
+
+ Examples
+ --------
+ Minimize the objective function f(x,y) = x*y subject
+ to the constraints x**2 + y**2 < 1 and y > 0::
+
+ >>> def objective(x):
+ ... return x[0]*x[1]
+ ...
+ >>> def constr1(x):
+ ... return 1 - (x[0]**2 + x[1]**2)
+ ...
+ >>> def constr2(x):
+ ... return x[1]
+ ...
+ >>> from scipy.optimize import fmin_cobyla
+ >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e-7)
+ array([-0.70710685, 0.70710671])
+
+ The exact solution is (-sqrt(2)/2, sqrt(2)/2).
+
+
+
+ """
+ err = "cons must be a sequence of callable functions or a single"\
+ " callable function."
+ try:
+ len(cons)
+ except TypeError as e:
+ if callable(cons):
+ cons = [cons]
+ else:
+ raise TypeError(err) from e
+ else:
+ for thisfunc in cons:
+ if not callable(thisfunc):
+ raise TypeError(err)
+
+ if consargs is None:
+ consargs = args
+
+ # build constraints
+ nlcs = []
+ for con in cons:
+ # Use default argument, otherwise the last `con` is captured by all wrapped_con
+ def wrapped_con(x, confunc=con):
+ return confunc(x, *consargs)
+ nlcs.append(NonlinearConstraint(wrapped_con, 0, np.inf))
+
+ # options
+ opts = {'rhobeg': rhobeg,
+ 'tol': rhoend,
+ 'disp': disp,
+ 'maxiter': maxfun,
+ 'catol': catol,
+ 'callback': callback}
+
+ sol = _minimize_cobyla(func, x0, args, constraints=nlcs,
+ **opts)
+ if disp and not sol['success']:
+ print(f"COBYLA failed to find a solution: {sol.message}")
+ return sol['x']
+
+
+def _minimize_cobyla(fun, x0, args=(), constraints=(),
+ rhobeg=1.0, tol=1e-4, maxiter=1000,
+ disp=0, catol=None, f_target=-np.inf,
+ callback=None, bounds=None, **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using the
+ Constrained Optimization BY Linear Approximation (COBYLA) algorithm.
+ This method uses the pure-python implementation of the algorithm from PRIMA.
+
+ Options
+ -------
+ rhobeg : float
+ Reasonable initial changes to the variables.
+ tol : float
+ Final accuracy in the optimization (not precisely guaranteed).
+ This is a lower bound on the size of the trust region.
+ disp : int
+ Controls the frequency of output:
+ 0. (default) There will be no printing
+ 1. A message will be printed to the screen at the end of iteration, showing
+ the best vector of variables found and its objective function value
+ 2. in addition to 1, each new value of RHO is printed to the screen,
+ with the best vector of variables so far and its objective function
+ value.
+ 3. in addition to 2, each function evaluation with its variables will
+ be printed to the screen.
+ maxiter : int
+ Maximum number of function evaluations.
+ catol : float
+ Tolerance (absolute) for constraint violations
+ f_target : float
+ Stop if the objective function is less than `f_target`.
+
+ .. versionchanged:: 1.16.0
+ The original Powell implementation was replaced by a pure
+ Python version from the PRIMA package, with bug fixes and
+ improvements being made.
+
+
+ References
+ ----------
+ Zhang Z. (2023), "PRIMA: Reference Implementation for Powell's Methods with
+ Modernization and Amelioration", https://www.libprima.net,
+ :doi:`10.5281/zenodo.8052654`
+ """
+ from .._external.pyprima import minimize
+ from .._external.pyprima.common.infos import SMALL_TR_RADIUS, FTARGET_ACHIEVED
+ from .._external.pyprima.common.message import get_info_string
+ _check_unknown_options(unknown_options)
+ rhoend = tol
+ iprint = disp if disp is not None else 0
+ if iprint != 0 and iprint != 1 and iprint != 2 and iprint != 3:
+ raise ValueError(f'disp argument to minimize must be 0, 1, 2, or 3,\
+ received {iprint}')
+
+ # create the ScalarFunction, cobyla doesn't require derivative function
+ def _jac(x, *args):
+ return None
+
+ sf = _prepare_scalar_function(fun, x0, args=args, jac=_jac)
+
+ if callback is not None:
+ sig = wrapped_inspect_signature(callback)
+ if set(sig.parameters) == {"intermediate_result"}:
+ def wrapped_callback_intermediate(x, f, nf, tr, cstrv, nlconstrlist):
+ intermediate_result = OptimizeResult(x=np.copy(x), fun=f, nfev=nf,
+ nit=tr, maxcv=cstrv)
+ callback(intermediate_result=intermediate_result)
+ else:
+ def wrapped_callback_intermediate(x, f, nf, tr, cstrv, nlconstrlist):
+ callback(np.copy(x))
+ def wrapped_callback(x, f, nf, tr, cstrv, nlconstrlist):
+ try:
+ wrapped_callback_intermediate(x, f, nf, tr, cstrv, nlconstrlist)
+ return False
+ except StopIteration:
+ return True
+ else:
+ wrapped_callback = None
+
+
+ ctol = catol if catol is not None else np.sqrt(np.finfo(float).eps)
+ options = {
+ 'rhobeg': rhobeg,
+ 'rhoend': rhoend,
+ 'maxfev': maxiter,
+ 'iprint': iprint,
+ 'ctol': ctol,
+ 'ftarget': f_target,
+ }
+
+ result = minimize(sf.fun, x0, method='cobyla', bounds=bounds,
+ constraints=constraints, callback=wrapped_callback,
+ options=options)
+
+
+ if result.cstrv > ctol:
+ success = False
+ message = ('Did not converge to a solution satisfying the constraints. See '
+ '`maxcv` for the magnitude of the violation.')
+ else:
+ success = result.info == SMALL_TR_RADIUS or result.info == FTARGET_ACHIEVED
+ message = get_info_string('COBYLA', result.info)
+
+ return OptimizeResult(x=result.x,
+ status=result.info,
+ success=success,
+ message=message,
+ nfev=result.nf,
+ fun=result.f,
+ maxcv=result.cstrv)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_cobyqa_py.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_cobyqa_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..c88cbf3ea4b186164f9bb056dfa04b0fd9bf8df9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_cobyqa_py.py
@@ -0,0 +1,68 @@
+import numpy as np
+
+from ._optimize import _check_unknown_options
+
+
+def _minimize_cobyqa(fun, x0, args=(), bounds=None, constraints=(),
+ callback=None, disp=False, maxfev=None, maxiter=None,
+ f_target=-np.inf, feasibility_tol=1e-8,
+ initial_tr_radius=1.0, final_tr_radius=1e-6, scale=False,
+ **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using the
+ Constrained Optimization BY Quadratic Approximations (COBYQA) algorithm [1]_.
+
+ .. versionadded:: 1.14.0
+
+ Options
+ -------
+ disp : bool
+ Set to True to print information about the optimization procedure.
+ Default is ``False``.
+ maxfev : int
+ Maximum number of function evaluations. Default is ``500 * n``, where
+ ``n`` is the number of variables.
+ maxiter : int
+ Maximum number of iterations. Default is ``1000 * n``, where ``n`` is
+ the number of variables.
+ f_target : float
+ Target value for the objective function. The optimization procedure is
+ terminated when the objective function value of a feasible point (see
+ `feasibility_tol` below) is less than or equal to this target. Default
+ is ``-numpy.inf``.
+ feasibility_tol : float
+ Absolute tolerance for the constraint violation. Default is ``1e-8``.
+ initial_tr_radius : float
+ Initial trust-region radius. Typically, this value should be in the
+ order of one tenth of the greatest expected change to the variables.
+ Default is ``1.0``.
+ final_tr_radius : float
+ Final trust-region radius. It should indicate the accuracy required in
+ the final values of the variables. If provided, this option overrides
+ the value of `tol` in the `minimize` function. Default is ``1e-6``.
+ scale : bool
+ Set to True to scale the variables according to the bounds. If True and
+ if all the lower and upper bounds are finite, the variables are scaled
+ to be within the range :math:`[-1, 1]`. If any of the lower or upper
+ bounds is infinite, the variables are not scaled. Default is ``False``.
+
+ References
+ ----------
+ .. [1] COBYQA
+ https://www.cobyqa.com/stable/
+ """
+ # Import here to avoid circular imports
+ from .._external.cobyqa import minimize as _cobyqa_minimize
+
+ _check_unknown_options(unknown_options)
+ options = {
+ 'disp': bool(disp),
+ 'maxfev': int(maxfev) if maxfev is not None else 500 * len(x0),
+ 'maxiter': int(maxiter) if maxiter is not None else 1000 * len(x0),
+ 'target': float(f_target),
+ 'feasibility_tol': float(feasibility_tol),
+ 'radius_init': float(initial_tr_radius),
+ 'radius_final': float(final_tr_radius),
+ 'scale': bool(scale),
+ }
+ return _cobyqa_minimize(fun, x0, args, bounds, constraints, callback, options)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_constraints.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..75f81735dfd0feaff3865025467c859fd3b98ff6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_constraints.py
@@ -0,0 +1,645 @@
+"""Constraints definition for minimize."""
+from warnings import warn, catch_warnings, simplefilter, filterwarnings
+from types import GenericAlias
+
+import numpy as np
+
+from ._differentiable_functions import (
+ VectorFunction, LinearVectorFunction, IdentityVectorFunction
+)
+from ._hessian_update_strategy import BFGS
+from ._optimize import OptimizeWarning
+
+from scipy._lib._sparse import issparse
+
+
+def _arr_to_scalar(x):
+ # If x is a numpy array, return x.item(). This will
+ # fail if the array has more than one element.
+ return x.item() if isinstance(x, np.ndarray) else x
+
+
+class NonlinearConstraint:
+ """Nonlinear constraint on the variables.
+
+ The constraint has the general inequality form::
+
+ lb <= fun(x) <= ub
+
+ Here the vector of independent variables x is passed as ndarray of shape
+ (n,) and ``fun`` returns a vector with m components.
+
+ It is possible to use equal bounds to represent an equality constraint or
+ infinite bounds to represent a one-sided constraint.
+
+ Parameters
+ ----------
+ fun : callable
+ The function defining the constraint.
+ The signature is ``fun(x) -> array_like, shape (m,)``.
+ lb, ub : array_like
+ Lower and upper bounds on the constraint. Each array must have the
+ shape (m,) or be a scalar, in the latter case a bound will be the same
+ for all components of the constraint. Use ``np.inf`` with an
+ appropriate sign to specify a one-sided constraint.
+ Set components of `lb` and `ub` equal to represent an equality
+ constraint. Note that you can mix constraints of different types:
+ interval, one-sided or equality, by setting different components of
+ `lb` and `ub` as necessary.
+ jac : {callable, '2-point', '3-point', 'cs'}, optional
+ Method of computing the Jacobian matrix (an m-by-n matrix,
+ where element (i, j) is the partial derivative of f[i] with
+ respect to x[j]). The keywords {'2-point', '3-point',
+ 'cs'} select a finite difference scheme for the numerical estimation.
+ A callable must have the following signature::
+
+ jac(x) -> {ndarray, sparse array}, shape (m, n)
+
+ Default is '2-point'.
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional
+ Method for computing the Hessian matrix. The keywords
+ {'2-point', '3-point', 'cs'} select a finite difference scheme for
+ numerical estimation. Alternatively, objects implementing
+ `HessianUpdateStrategy` interface can be used to approximate the
+ Hessian. Currently available implementations are:
+
+ - `BFGS` (default option)
+ - `SR1`
+
+ A callable must return the Hessian matrix of ``dot(fun, v)`` and
+ must have the following signature:
+ ``hess(x, v) -> {LinearOperator, sparse array, array_like}, shape (n, n)``.
+ Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers.
+ keep_feasible : array_like of bool, optional
+ Whether to keep the constraint components feasible throughout
+ iterations. A single value sets this property for all components.
+ Default is False. Has no effect for equality constraints. Note that
+ finite difference approximation of the Jacobian may still violate
+ the constraint; it is recommended to provide an analytical Jacobian
+ function to handle this case.
+ finite_diff_rel_step : None or array_like, optional
+ Relative step size for the finite difference approximation. Default is
+ None, which will select a reasonable value automatically depending
+ on a finite difference scheme.
+ finite_diff_jac_sparsity : {None, array_like, sparse array}, optional
+ Defines the sparsity structure of the Jacobian matrix for finite
+ difference estimation, its shape must be (m, n). If the Jacobian has
+ only few non-zero elements in *each* row, providing the sparsity
+ structure will greatly speed up the computations. A zero entry means
+ that a corresponding element in the Jacobian is identically zero.
+ If provided, forces the use of 'lsmr' trust-region solver.
+ If None (default) then dense differencing will be used.
+
+ Notes
+ -----
+ Finite difference schemes {'2-point', '3-point', 'cs'} may be used for
+ approximating either the Jacobian or the Hessian. We, however, do not allow
+ its use for approximating both simultaneously. Hence whenever the Jacobian
+ is estimated via finite-differences, we require the Hessian to be estimated
+ using one of the quasi-Newton strategies.
+
+ The scheme 'cs' is potentially the most accurate, but requires the function
+ to correctly handles complex inputs and be analytically continuable to the
+ complex plane. The scheme '3-point' is more accurate than '2-point' but
+ requires twice as many operations.
+
+ Whilst `NonlinearConstraint` can be used to specify constraints for many
+ different optimizers, the class is not responsible for enforcing those constraints,
+ that is done by the individual minimizer. Importantly, the `keep_feasible` keyword
+ is only ever used within the :ref:`trust-constr `
+ optimizer, the `keep_feasible` keyword is not used by other `minimize` methods.
+ The other methods may, or may not, keep solutions strictly feasible during
+ operation.
+
+ Examples
+ --------
+ Constrain ``x[0] < sin(x[1]) + 1.9``
+
+ >>> from scipy.optimize import NonlinearConstraint
+ >>> import numpy as np
+ >>> con = lambda x: x[0] - np.sin(x[1])
+ >>> nlc = NonlinearConstraint(con, -np.inf, 1.9)
+
+ """
+ def __init__(self, fun, lb, ub, jac='2-point', hess=None,
+ keep_feasible=False, finite_diff_rel_step=None,
+ finite_diff_jac_sparsity=None):
+ if hess is None:
+ hess = BFGS()
+ self.fun = fun
+ self.lb = lb
+ self.ub = ub
+ self.finite_diff_rel_step = finite_diff_rel_step
+ self.finite_diff_jac_sparsity = finite_diff_jac_sparsity
+ self.jac = jac
+ self.hess = hess
+ self.keep_feasible = keep_feasible
+
+
+class LinearConstraint:
+ """Linear constraint on the variables.
+
+ The constraint has the general inequality form::
+
+ lb <= A.dot(x) <= ub
+
+ Here the vector of independent variables x is passed as ndarray of shape
+ (n,) and the matrix A has shape (m, n).
+
+ It is possible to use equal bounds to represent an equality constraint or
+ infinite bounds to represent a one-sided constraint.
+
+ Parameters
+ ----------
+ A : {array_like, sparse array}, shape (m, n)
+ Matrix defining the constraint.
+ lb, ub : dense array_like, optional
+ Lower and upper limits on the constraint. Each array must have the
+ shape (m,) or be a scalar, in the latter case a bound will be the same
+ for all components of the constraint. Use ``np.inf`` with an
+ appropriate sign to specify a one-sided constraint.
+ Set components of `lb` and `ub` equal to represent an equality
+ constraint. Note that you can mix constraints of different types:
+ interval, one-sided or equality, by setting different components of
+ `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
+ and ``ub = np.inf`` (no limits).
+ keep_feasible : dense array_like of bool, optional
+ Whether to keep the constraint components feasible throughout
+ iterations. A single value sets this property for all components.
+ Default is False. Has no effect for equality constraints. Note that
+ finite difference approximation of the Jacobian may still violate
+ the constraint; it is recommended to provide an analytical Jacobian
+ function to handle this case.
+
+ Notes
+ -----
+ Whilst `LinearConstraint` can be used to specify constraints for many
+ different optimizers, the class is not responsible for enforcing those constraints,
+ that is done by the individual minimizer. Importantly, the `keep_feasible` keyword
+ is only ever used within the :ref:`trust-constr `
+ optimizer, the `keep_feasible` keyword is not used by other `minimize` methods.
+ The other methods may, or may not, keep solutions strictly feasible during
+ operation.
+
+ """
+ def _input_validation(self):
+ if self.A.ndim != 2:
+ message = "`A` must have exactly two dimensions."
+ raise ValueError(message)
+
+ try:
+ shape = self.A.shape[0:1]
+ self.lb = np.broadcast_to(self.lb, shape)
+ self.ub = np.broadcast_to(self.ub, shape)
+ self.keep_feasible = np.broadcast_to(self.keep_feasible, shape)
+ except ValueError:
+ message = ("`lb`, `ub`, and `keep_feasible` must be broadcastable "
+ "to shape `A.shape[0:1]`")
+ raise ValueError(message)
+
+ def __init__(self, A, lb=-np.inf, ub=np.inf, keep_feasible=False):
+ if not issparse(A):
+ # In some cases, if the constraint is not valid, this emits a
+ # VisibleDeprecationWarning about ragged nested sequences
+ # before eventually causing an error. `scipy.optimize.milp` would
+ # prefer that this just error out immediately so it can handle it
+ # rather than concerning the user.
+ with catch_warnings():
+ simplefilter("error")
+ self.A = np.atleast_2d(A).astype(np.float64)
+ else:
+ self.A = A
+ if issparse(lb) or issparse(ub):
+ raise ValueError("Constraint limits must be dense arrays.")
+ self.lb = np.atleast_1d(lb).astype(np.float64)
+ self.ub = np.atleast_1d(ub).astype(np.float64)
+
+ if issparse(keep_feasible):
+ raise ValueError("`keep_feasible` must be a dense array.")
+ self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool)
+ self._input_validation()
+
+ def residual(self, x):
+ """
+ Calculate the residual between the constraint function and the limits.
+
+ For a linear constraint of the form::
+
+ lb <= A@x <= ub
+
+ the lower and upper residuals between ``A@x`` and the limits are values
+ ``sl`` and ``sb`` such that::
+
+ lb + sl == A@x == ub - sb
+
+ When all elements of ``sl`` and ``sb`` are positive, all elements of
+ the constraint are satisfied; a negative element in ``sl`` or ``sb``
+ indicates that the corresponding element of the constraint is not
+ satisfied.
+
+ Parameters
+ ----------
+ x : array_like
+ Vector of independent variables
+
+ Returns
+ -------
+ sl, sb : array-like
+ The lower and upper residuals
+ """
+ return self.A@x - self.lb, self.ub - self.A@x
+
+
+class Bounds:
+ """Bounds constraint on the variables.
+
+ The constraint has the general inequality form::
+
+ lb <= x <= ub
+
+ It is possible to use equal bounds to represent an equality constraint or
+ infinite bounds to represent a one-sided constraint.
+
+ Parameters
+ ----------
+ lb, ub : dense array_like, optional
+ Lower and upper bounds on independent variables. `lb`, `ub`, and
+ `keep_feasible` must be the same shape or broadcastable.
+ Set components of `lb` and `ub` equal
+ to fix a variable. Use ``np.inf`` with an appropriate sign to disable
+ bounds on all or some variables. Note that you can mix constraints of
+ different types: interval, one-sided or equality, by setting different
+ components of `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
+ and ``ub = np.inf`` (no bounds).
+ keep_feasible : dense array_like of bool, optional
+ Whether to keep the constraint components feasible throughout
+ iterations. Must be broadcastable with `lb` and `ub`.
+ Default is False. Has no effect for equality constraints.
+
+ Notes
+ -----
+ Whilst `Bounds` can be used to specify box-bounds for many
+ different optimizers, the class is not responsible for enforcing those constraints,
+ that is done by the individual minimizer. Importantly, the `keep_feasible` keyword
+ is only ever used within the :ref:`trust-constr `
+ optimizer, the `keep_feasible` keyword is not used by other `minimize` methods.
+ The other methods may, or may not, keep solutions strictly feasible during
+ operation.
+
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def _input_validation(self):
+ if self.lb.size == 0 or self.ub.size == 0:
+ raise ValueError("`lb` and `ub` must be non-empty.")
+ try:
+ res = np.broadcast_arrays(self.lb, self.ub, self.keep_feasible)
+ self.lb, self.ub, self.keep_feasible = res
+ except ValueError:
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
+ raise ValueError(message)
+
+ def __init__(self, lb=-np.inf, ub=np.inf, keep_feasible=False):
+ if issparse(lb) or issparse(ub):
+ raise ValueError("Lower and upper bounds must be dense arrays.")
+ self.lb = np.atleast_1d(lb)
+ self.ub = np.atleast_1d(ub)
+
+ if issparse(keep_feasible):
+ raise ValueError("`keep_feasible` must be a dense array.")
+ self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool)
+ self._input_validation()
+
+ def __repr__(self):
+ start = f"{type(self).__name__}({self.lb!r}, {self.ub!r}"
+ if np.any(self.keep_feasible):
+ end = f", keep_feasible={self.keep_feasible!r})"
+ else:
+ end = ")"
+ return start + end
+
+ def residual(self, x):
+ """Calculate the residual (slack) between the input and the bounds.
+
+ For a bound constraint of the form::
+
+ lb <= x <= ub
+
+ the lower and upper residuals between `x` and the bounds are values
+ ``sl`` and ``sb`` such that::
+
+ lb + sl == x == ub - sb
+
+ When all elements of ``sl`` and ``sb`` are positive, all elements of
+ ``x`` lie within the bounds; a negative element in ``sl`` or ``sb``
+ indicates that the corresponding element of ``x`` is out of bounds.
+
+ Parameters
+ ----------
+ x : array_like
+ Vector of independent variables
+
+ Returns
+ -------
+ sl, sb : array-like
+ The lower and upper residuals
+ """
+ return x - self.lb, self.ub - x
+
+
+class PreparedConstraint:
+ """Constraint prepared from a user defined constraint.
+
+ On creation it will check whether a constraint definition is valid and
+ the initial point is feasible. If created successfully, it will contain
+ the attributes listed below.
+
+ Parameters
+ ----------
+ constraint : {NonlinearConstraint, LinearConstraint`, Bounds}
+ Constraint to check and prepare.
+ x0 : array_like
+ Initial vector of independent variables.
+ sparse_jacobian : bool or None, optional
+ If bool, then the Jacobian of the constraint will be converted
+ to the corresponded format if necessary. If None (default), such
+ conversion is not made.
+ finite_diff_bounds : 2-tuple, optional
+ Lower and upper bounds on the independent variables for the finite
+ difference approximation, if applicable. Defaults to no bounds.
+
+ Attributes
+ ----------
+ fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction}
+ Function defining the constraint wrapped by one of the convenience
+ classes.
+ bounds : 2-tuple
+ Contains lower and upper bounds for the constraints --- lb and ub.
+ These are converted to ndarray and have a size equal to the number of
+ the constraints.
+ keep_feasible : ndarray
+ Array indicating which components must be kept feasible with a size
+ equal to the number of the constraints.
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def __init__(self, constraint, x0, sparse_jacobian=None,
+ finite_diff_bounds=(-np.inf, np.inf)):
+ if isinstance(constraint, NonlinearConstraint):
+ fun = VectorFunction(constraint.fun, x0,
+ constraint.jac, constraint.hess,
+ constraint.finite_diff_rel_step,
+ constraint.finite_diff_jac_sparsity,
+ finite_diff_bounds, sparse_jacobian)
+ elif isinstance(constraint, LinearConstraint):
+ fun = LinearVectorFunction(constraint.A, x0, sparse_jacobian)
+ elif isinstance(constraint, Bounds):
+ fun = IdentityVectorFunction(x0, sparse_jacobian)
+ else:
+ raise ValueError("`constraint` of an unknown type is passed.")
+
+ m = fun.m
+
+ lb = np.asarray(constraint.lb, dtype=float)
+ ub = np.asarray(constraint.ub, dtype=float)
+ keep_feasible = np.asarray(constraint.keep_feasible, dtype=bool)
+
+ lb = np.broadcast_to(lb, m)
+ ub = np.broadcast_to(ub, m)
+ keep_feasible = np.broadcast_to(keep_feasible, m)
+
+ if keep_feasible.shape != (m,):
+ raise ValueError("`keep_feasible` has a wrong shape.")
+
+ mask = keep_feasible & (lb != ub)
+ f0 = fun.f
+ if np.any(f0[mask] < lb[mask]) or np.any(f0[mask] > ub[mask]):
+ raise ValueError("`x0` is infeasible with respect to some "
+ "inequality constraint with `keep_feasible` "
+ "set to True.")
+
+ self.fun = fun
+ self.bounds = (lb, ub)
+ self.keep_feasible = keep_feasible
+
+ def violation(self, x):
+ """How much the constraint is exceeded by.
+
+ Parameters
+ ----------
+ x : array-like
+ Vector of independent variables
+
+ Returns
+ -------
+ excess : array-like
+ How much the constraint is exceeded by, for each of the
+ constraints specified by `PreparedConstraint.fun`.
+ """
+ with catch_warnings():
+ # Ignore the following warning, it's not important when
+ # figuring out total violation
+ # UserWarning: delta_grad == 0.0. Check if the approximated
+ # function is linear
+ filterwarnings("ignore", "delta_grad", UserWarning)
+ ev = self.fun.fun(np.asarray(x))
+
+ excess_lb = np.maximum(self.bounds[0] - ev, 0)
+ excess_ub = np.maximum(ev - self.bounds[1], 0)
+
+ return excess_lb + excess_ub
+
+
+def new_bounds_to_old(lb, ub, n):
+ """Convert the new bounds representation to the old one.
+
+ The new representation is a tuple (lb, ub) and the old one is a list
+ containing n tuples, ith containing lower and upper bounds on the ith
+ variable.
+ If any of the entries in lb/ub are -np.inf/np.inf they are replaced by
+ None.
+ """
+ lb = np.broadcast_to(lb, n)
+ ub = np.broadcast_to(ub, n)
+
+ lb = [float(x) if x > -np.inf else None for x in lb]
+ ub = [float(x) if x < np.inf else None for x in ub]
+
+ return list(zip(lb, ub))
+
+
+def old_bound_to_new(bounds):
+ """Convert the old bounds representation to the new one.
+
+ The new representation is a tuple (lb, ub) and the old one is a list
+ containing n tuples, ith containing lower and upper bounds on the ith
+ variable.
+ If any of the entries in lb/ub are None they are replaced by
+ -np.inf/np.inf.
+ """
+ lb, ub = zip(*bounds)
+
+ # Convert occurrences of None to -inf or inf, and replace occurrences of
+ # any numpy array x with x.item(). Then wrap the results in numpy arrays.
+ lb = np.array([float(_arr_to_scalar(x)) if x is not None else -np.inf
+ for x in lb])
+ ub = np.array([float(_arr_to_scalar(x)) if x is not None else np.inf
+ for x in ub])
+
+ return lb, ub
+
+
+def strict_bounds(lb, ub, keep_feasible, n_vars):
+ """Remove bounds which are not asked to be kept feasible."""
+ strict_lb = np.resize(lb, n_vars).astype(float)
+ strict_ub = np.resize(ub, n_vars).astype(float)
+ keep_feasible = np.resize(keep_feasible, n_vars)
+ strict_lb[~keep_feasible] = -np.inf
+ strict_ub[~keep_feasible] = np.inf
+ return strict_lb, strict_ub
+
+
+def new_constraint_to_old(con, x0):
+ """
+ Converts new-style constraint objects to old-style constraint dictionaries.
+ """
+ if isinstance(con, NonlinearConstraint):
+ if (con.finite_diff_jac_sparsity is not None or
+ con.finite_diff_rel_step is not None or
+ not isinstance(con.hess, BFGS) or # misses user specified BFGS
+ con.keep_feasible):
+ warn("Constraint options `finite_diff_jac_sparsity`, "
+ "`finite_diff_rel_step`, `keep_feasible`, and `hess`"
+ "are ignored by this method.",
+ OptimizeWarning, stacklevel=3)
+
+ fun = con.fun
+ if callable(con.jac):
+ jac = con.jac
+ else:
+ jac = None
+
+ else: # LinearConstraint
+ if np.any(con.keep_feasible):
+ warn("Constraint option `keep_feasible` is ignored by this method.",
+ OptimizeWarning, stacklevel=3)
+
+ A = con.A
+ if issparse(A):
+ A = A.toarray()
+ def fun(x):
+ return np.dot(A, x)
+ def jac(x):
+ return A
+
+ # FIXME: when bugs in VectorFunction/LinearVectorFunction are worked out,
+ # use pcon.fun.fun and pcon.fun.jac. Until then, get fun/jac above.
+ pcon = PreparedConstraint(con, x0)
+ lb, ub = pcon.bounds
+
+ i_eq = lb == ub
+ i_bound_below = np.logical_xor(lb != -np.inf, i_eq)
+ i_bound_above = np.logical_xor(ub != np.inf, i_eq)
+ i_unbounded = np.logical_and(lb == -np.inf, ub == np.inf)
+
+ if np.any(i_unbounded):
+ warn("At least one constraint is unbounded above and below. Such "
+ "constraints are ignored.",
+ OptimizeWarning, stacklevel=3)
+
+ ceq = []
+ if np.any(i_eq):
+ def f_eq(x):
+ y = np.array(fun(x)).flatten()
+ return y[i_eq] - lb[i_eq]
+ ceq = [{"type": "eq", "fun": f_eq}]
+
+ if jac is not None:
+ def j_eq(x):
+ dy = jac(x)
+ if issparse(dy):
+ dy = dy.toarray()
+ dy = np.atleast_2d(dy)
+ return dy[i_eq, :]
+ ceq[0]["jac"] = j_eq
+
+ cineq = []
+ n_bound_below = np.sum(i_bound_below)
+ n_bound_above = np.sum(i_bound_above)
+ if n_bound_below + n_bound_above:
+ def f_ineq(x):
+ y = np.zeros(n_bound_below + n_bound_above)
+ y_all = np.array(fun(x)).flatten()
+ y[:n_bound_below] = y_all[i_bound_below] - lb[i_bound_below]
+ y[n_bound_below:] = -(y_all[i_bound_above] - ub[i_bound_above])
+ return y
+ cineq = [{"type": "ineq", "fun": f_ineq}]
+
+ if jac is not None:
+ def j_ineq(x):
+ dy = np.zeros((n_bound_below + n_bound_above, len(x0)))
+ dy_all = jac(x)
+ if issparse(dy_all):
+ dy_all = dy_all.toarray()
+ dy_all = np.atleast_2d(dy_all)
+ dy[:n_bound_below, :] = dy_all[i_bound_below]
+ dy[n_bound_below:, :] = -dy_all[i_bound_above]
+ return dy
+ cineq[0]["jac"] = j_ineq
+
+ old_constraints = ceq + cineq
+
+ if len(old_constraints) > 1:
+ warn("Equality and inequality constraints are specified in the same "
+ "element of the constraint list. For efficient use with this "
+ "method, equality and inequality constraints should be specified "
+ "in separate elements of the constraint list. ",
+ OptimizeWarning, stacklevel=3)
+ return old_constraints
+
+
+def old_constraint_to_new(ic, con):
+ """
+ Converts old-style constraint dictionaries to new-style constraint objects.
+ """
+ # check type
+ try:
+ ctype = con['type'].lower()
+ except KeyError as e:
+ raise KeyError(f'Constraint {ic} has no type defined.') from e
+ except TypeError as e:
+ raise TypeError(
+ 'Constraints must be a sequence of dictionaries.'
+ ) from e
+ except AttributeError as e:
+ raise TypeError("Constraint's type must be a string.") from e
+ else:
+ if ctype not in ['eq', 'ineq']:
+ raise ValueError(f"Unknown constraint type '{con['type']}'.")
+ if 'fun' not in con:
+ raise ValueError(f'Constraint {ic} has no function defined.')
+
+ lb = 0
+ if ctype == 'eq':
+ ub = 0
+ else:
+ ub = np.inf
+
+ jac = '2-point'
+ if 'args' in con:
+ args = con['args']
+ def fun(x):
+ return con["fun"](x, *args)
+ if 'jac' in con:
+ def jac(x):
+ return con["jac"](x, *args)
+ else:
+ fun = con['fun']
+ if 'jac' in con:
+ jac = con['jac']
+
+ return NonlinearConstraint(fun, lb, ub, jac)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_dcsrch.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_dcsrch.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5bd95527500faa8671159454ee4514312b486b6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_dcsrch.py
@@ -0,0 +1,728 @@
+import numpy as np
+
+"""
+# 2023 - ported from minpack2.dcsrch, dcstep (Fortran) to Python
+c MINPACK-1 Project. June 1983.
+c Argonne National Laboratory.
+c Jorge J. More' and David J. Thuente.
+c
+c MINPACK-2 Project. November 1993.
+c Argonne National Laboratory and University of Minnesota.
+c Brett M. Averick, Richard G. Carter, and Jorge J. More'.
+"""
+
+# NOTE this file was linted by black on first commit, and can be kept that way.
+
+
+class DCSRCH:
+ """
+ Parameters
+ ----------
+ phi : callable phi(alpha)
+ Function at point `alpha`
+ derphi : callable phi'(alpha)
+ Objective function derivative. Returns a scalar.
+ ftol : float
+ A nonnegative tolerance for the sufficient decrease condition.
+ gtol : float
+ A nonnegative tolerance for the curvature condition.
+ xtol : float
+ A nonnegative relative tolerance for an acceptable step. The
+ subroutine exits with a warning if the relative difference between
+ sty and stx is less than xtol.
+ stpmin : float
+ A nonnegative lower bound for the step.
+ stpmax :
+ A nonnegative upper bound for the step.
+
+ Notes
+ -----
+
+ This subroutine finds a step that satisfies a sufficient
+ decrease condition and a curvature condition.
+
+ Each call of the subroutine updates an interval with
+ endpoints stx and sty. The interval is initially chosen
+ so that it contains a minimizer of the modified function
+
+ psi(stp) = f(stp) - f(0) - ftol*stp*f'(0).
+
+ If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
+ interval is chosen so that it contains a minimizer of f.
+
+ The algorithm is designed to find a step that satisfies
+ the sufficient decrease condition
+
+ f(stp) <= f(0) + ftol*stp*f'(0),
+
+ and the curvature condition
+
+ abs(f'(stp)) <= gtol*abs(f'(0)).
+
+ If ftol is less than gtol and if, for example, the function
+ is bounded below, then there is always a step which satisfies
+ both conditions.
+
+ If no step can be found that satisfies both conditions, then
+ the algorithm stops with a warning. In this case stp only
+ satisfies the sufficient decrease condition.
+
+ A typical invocation of dcsrch has the following outline:
+
+ Evaluate the function at stp = 0.0d0; store in f.
+ Evaluate the gradient at stp = 0.0d0; store in g.
+ Choose a starting step stp.
+
+ task = 'START'
+ 10 continue
+ call dcsrch(stp,f,g,ftol,gtol,xtol,task,stpmin,stpmax,
+ isave,dsave)
+ if (task .eq. 'FG') then
+ Evaluate the function and the gradient at stp
+ go to 10
+ end if
+
+ NOTE: The user must not alter work arrays between calls.
+
+ The subroutine statement is
+
+ subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax,
+ task,isave,dsave)
+ where
+
+ stp is a double precision variable.
+ On entry stp is the current estimate of a satisfactory
+ step. On initial entry, a positive initial estimate
+ must be provided.
+ On exit stp is the current estimate of a satisfactory step
+ if task = 'FG'. If task = 'CONV' then stp satisfies
+ the sufficient decrease and curvature condition.
+
+ f is a double precision variable.
+ On initial entry f is the value of the function at 0.
+ On subsequent entries f is the value of the
+ function at stp.
+ On exit f is the value of the function at stp.
+
+ g is a double precision variable.
+ On initial entry g is the derivative of the function at 0.
+ On subsequent entries g is the derivative of the
+ function at stp.
+ On exit g is the derivative of the function at stp.
+
+ ftol is a double precision variable.
+ On entry ftol specifies a nonnegative tolerance for the
+ sufficient decrease condition.
+ On exit ftol is unchanged.
+
+ gtol is a double precision variable.
+ On entry gtol specifies a nonnegative tolerance for the
+ curvature condition.
+ On exit gtol is unchanged.
+
+ xtol is a double precision variable.
+ On entry xtol specifies a nonnegative relative tolerance
+ for an acceptable step. The subroutine exits with a
+ warning if the relative difference between sty and stx
+ is less than xtol.
+
+ On exit xtol is unchanged.
+
+ task is a character variable of length at least 60.
+ On initial entry task must be set to 'START'.
+ On exit task indicates the required action:
+
+ If task(1:2) = 'FG' then evaluate the function and
+ derivative at stp and call dcsrch again.
+
+ If task(1:4) = 'CONV' then the search is successful.
+
+ If task(1:4) = 'WARN' then the subroutine is not able
+ to satisfy the convergence conditions. The exit value of
+ stp contains the best point found during the search.
+
+ If task(1:5) = 'ERROR' then there is an error in the
+ input arguments.
+
+ On exit with convergence, a warning or an error, the
+ variable task contains additional information.
+
+ stpmin is a double precision variable.
+ On entry stpmin is a nonnegative lower bound for the step.
+ On exit stpmin is unchanged.
+
+ stpmax is a double precision variable.
+ On entry stpmax is a nonnegative upper bound for the step.
+ On exit stpmax is unchanged.
+
+ isave is an integer work array of dimension 2.
+
+ dsave is a double precision work array of dimension 13.
+
+ Subprograms called
+
+ MINPACK-2 ... dcstep
+ MINPACK-1 Project. June 1983.
+ Argonne National Laboratory.
+ Jorge J. More' and David J. Thuente.
+
+ MINPACK-2 Project. November 1993.
+ Argonne National Laboratory and University of Minnesota.
+ Brett M. Averick, Richard G. Carter, and Jorge J. More'.
+ """
+
+ def __init__(self, phi, derphi, ftol, gtol, xtol, stpmin, stpmax):
+ self.stage = None
+ self.ginit = None
+ self.gtest = None
+ self.gx = None
+ self.gy = None
+ self.finit = None
+ self.fx = None
+ self.fy = None
+ self.stx = None
+ self.sty = None
+ self.stmin = None
+ self.stmax = None
+ self.width = None
+ self.width1 = None
+
+ # leave all assessment of tolerances/limits to the first call of
+ # this object
+ self.ftol = ftol
+ self.gtol = gtol
+ self.xtol = xtol
+ self.stpmin = stpmin
+ self.stpmax = stpmax
+
+ self.phi = phi
+ self.derphi = derphi
+
+ def __call__(self, alpha1, phi0=None, derphi0=None, maxiter=100):
+ """
+ Parameters
+ ----------
+ alpha1 : float
+ alpha1 is the current estimate of a satisfactory
+ step. A positive initial estimate must be provided.
+ phi0 : float
+ the value of `phi` at 0 (if known).
+ derphi0 : float
+ the derivative of `derphi` at 0 (if known).
+ maxiter : int
+
+ Returns
+ -------
+ alpha : float
+ Step size, or None if no suitable step was found.
+ phi : float
+ Value of `phi` at the new point `alpha`.
+ phi0 : float
+ Value of `phi` at `alpha=0`.
+ task : bytes
+ On exit task indicates status information.
+
+ If task[:4] == b'CONV' then the search is successful.
+
+ If task[:4] == b'WARN' then the subroutine is not able
+ to satisfy the convergence conditions. The exit value of
+ stp contains the best point found during the search.
+
+ If task[:5] == b'ERROR' then there is an error in the
+ input arguments.
+ """
+ if phi0 is None:
+ phi0 = self.phi(0.0)
+ if derphi0 is None:
+ derphi0 = self.derphi(0.0)
+
+ phi1 = phi0
+ derphi1 = derphi0
+
+ task = b"START"
+ for i in range(maxiter):
+ stp, phi1, derphi1, task = self._iterate(
+ alpha1, phi1, derphi1, task
+ )
+
+ if not np.isfinite(stp):
+ task = b"WARN"
+ stp = None
+ break
+
+ if task[:2] == b"FG":
+ alpha1 = stp
+ phi1 = self.phi(stp)
+ derphi1 = self.derphi(stp)
+ else:
+ break
+ else:
+ # maxiter reached, the line search did not converge
+ stp = None
+ task = b"WARNING: dcsrch did not converge within max iterations"
+
+ if task[:5] == b"ERROR" or task[:4] == b"WARN":
+ stp = None # failed
+
+ return stp, phi1, phi0, task
+
+ def _iterate(self, stp, f, g, task):
+ """
+ Parameters
+ ----------
+ stp : float
+ The current estimate of a satisfactory step. On initial entry, a
+ positive initial estimate must be provided.
+ f : float
+ On first call f is the value of the function at 0. On subsequent
+ entries f should be the value of the function at stp.
+ g : float
+ On initial entry g is the derivative of the function at 0. On
+ subsequent entries g is the derivative of the function at stp.
+ task : bytes
+ On initial entry task must be set to 'START'.
+
+ On exit with convergence, a warning or an error, the
+ variable task contains additional information.
+
+
+ Returns
+ -------
+ stp, f, g, task: tuple
+
+ stp : float
+ the current estimate of a satisfactory step if task = 'FG'. If
+ task = 'CONV' then stp satisfies the sufficient decrease and
+ curvature condition.
+ f : float
+ the value of the function at stp.
+ g : float
+ the derivative of the function at stp.
+ task : bytes
+ On exit task indicates the required action:
+
+ If task(1:2) == b'FG' then evaluate the function and
+ derivative at stp and call dcsrch again.
+
+ If task(1:4) == b'CONV' then the search is successful.
+
+ If task(1:4) == b'WARN' then the subroutine is not able
+ to satisfy the convergence conditions. The exit value of
+ stp contains the best point found during the search.
+
+ If task(1:5) == b'ERROR' then there is an error in the
+ input arguments.
+ """
+ p5 = 0.5
+ p66 = 0.66
+ xtrapl = 1.1
+ xtrapu = 4.0
+
+ if task[:5] == b"START":
+ if stp < self.stpmin:
+ task = b"ERROR: STP .LT. STPMIN"
+ if stp > self.stpmax:
+ task = b"ERROR: STP .GT. STPMAX"
+ if g >= 0:
+ task = b"ERROR: INITIAL G .GE. ZERO"
+ if self.ftol < 0:
+ task = b"ERROR: FTOL .LT. ZERO"
+ if self.gtol < 0:
+ task = b"ERROR: GTOL .LT. ZERO"
+ if self.xtol < 0:
+ task = b"ERROR: XTOL .LT. ZERO"
+ if self.stpmin < 0:
+ task = b"ERROR: STPMIN .LT. ZERO"
+ if self.stpmax < self.stpmin:
+ task = b"ERROR: STPMAX .LT. STPMIN"
+
+ if task[:5] == b"ERROR":
+ return stp, f, g, task
+
+ # Initialize local variables.
+
+ self.brackt = False
+ self.stage = 1
+ self.finit = f
+ self.ginit = g
+ self.gtest = self.ftol * self.ginit
+ self.width = self.stpmax - self.stpmin
+ self.width1 = self.width / p5
+
+ # The variables stx, fx, gx contain the values of the step,
+ # function, and derivative at the best step.
+ # The variables sty, fy, gy contain the value of the step,
+ # function, and derivative at sty.
+ # The variables stp, f, g contain the values of the step,
+ # function, and derivative at stp.
+
+ self.stx = 0.0
+ self.fx = self.finit
+ self.gx = self.ginit
+ self.sty = 0.0
+ self.fy = self.finit
+ self.gy = self.ginit
+ self.stmin = 0
+ self.stmax = stp + xtrapu * stp
+ task = b"FG"
+ return stp, f, g, task
+
+ # in the original Fortran this was a location to restore variables
+ # we don't need to do that because they're attributes.
+
+ # If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
+ # algorithm enters the second stage.
+ ftest = self.finit + stp * self.gtest
+
+ if self.stage == 1 and f <= ftest and g >= 0:
+ self.stage = 2
+
+ # test for warnings
+ if self.brackt and (stp <= self.stmin or stp >= self.stmax):
+ task = b"WARNING: ROUNDING ERRORS PREVENT PROGRESS"
+ if self.brackt and self.stmax - self.stmin <= self.xtol * self.stmax:
+ task = b"WARNING: XTOL TEST SATISFIED"
+ if stp == self.stpmax and f <= ftest and g <= self.gtest:
+ task = b"WARNING: STP = STPMAX"
+ if stp == self.stpmin and (f > ftest or g >= self.gtest):
+ task = b"WARNING: STP = STPMIN"
+
+ # test for convergence
+ if f <= ftest and abs(g) <= self.gtol * -self.ginit:
+ task = b"CONVERGENCE"
+
+ # test for termination
+ if task[:4] == b"WARN" or task[:4] == b"CONV":
+ return stp, f, g, task
+
+ # A modified function is used to predict the step during the
+ # first stage if a lower function value has been obtained but
+ # the decrease is not sufficient.
+ if self.stage == 1 and f <= self.fx and f > ftest:
+ # Define the modified function and derivative values.
+ fm = f - stp * self.gtest
+ fxm = self.fx - self.stx * self.gtest
+ fym = self.fy - self.sty * self.gtest
+ gm = g - self.gtest
+ gxm = self.gx - self.gtest
+ gym = self.gy - self.gtest
+
+ # Call dcstep to update stx, sty, and to compute the new step.
+ # dcstep can have several operations which can produce NaN
+ # e.g. inf/inf. Filter these out.
+ with np.errstate(invalid="ignore", over="ignore"):
+ tup = dcstep(
+ self.stx,
+ fxm,
+ gxm,
+ self.sty,
+ fym,
+ gym,
+ stp,
+ fm,
+ gm,
+ self.brackt,
+ self.stmin,
+ self.stmax,
+ )
+ self.stx, fxm, gxm, self.sty, fym, gym, stp, self.brackt = tup
+
+ # Reset the function and derivative values for f
+ self.fx = fxm + self.stx * self.gtest
+ self.fy = fym + self.sty * self.gtest
+ self.gx = gxm + self.gtest
+ self.gy = gym + self.gtest
+
+ else:
+ # Call dcstep to update stx, sty, and to compute the new step.
+ # dcstep can have several operations which can produce NaN
+ # e.g. inf/inf. Filter these out.
+
+ with np.errstate(invalid="ignore", over="ignore"):
+ tup = dcstep(
+ self.stx,
+ self.fx,
+ self.gx,
+ self.sty,
+ self.fy,
+ self.gy,
+ stp,
+ f,
+ g,
+ self.brackt,
+ self.stmin,
+ self.stmax,
+ )
+ (
+ self.stx,
+ self.fx,
+ self.gx,
+ self.sty,
+ self.fy,
+ self.gy,
+ stp,
+ self.brackt,
+ ) = tup
+
+ # Decide if a bisection step is needed
+ if self.brackt:
+ if abs(self.sty - self.stx) >= p66 * self.width1:
+ stp = self.stx + p5 * (self.sty - self.stx)
+ self.width1 = self.width
+ self.width = abs(self.sty - self.stx)
+
+ # Set the minimum and maximum steps allowed for stp.
+ if self.brackt:
+ self.stmin = min(self.stx, self.sty)
+ self.stmax = max(self.stx, self.sty)
+ else:
+ self.stmin = stp + xtrapl * (stp - self.stx)
+ self.stmax = stp + xtrapu * (stp - self.stx)
+
+ # Force the step to be within the bounds stpmax and stpmin.
+ stp = np.clip(stp, self.stpmin, self.stpmax)
+
+ # If further progress is not possible, let stp be the best
+ # point obtained during the search.
+ if (
+ self.brackt
+ and (stp <= self.stmin or stp >= self.stmax)
+ or (
+ self.brackt
+ and self.stmax - self.stmin <= self.xtol * self.stmax
+ )
+ ):
+ stp = self.stx
+
+ # Obtain another function and derivative
+ task = b"FG"
+ return stp, f, g, task
+
+
+def dcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax):
+ """
+ Subroutine dcstep
+
+ This subroutine computes a safeguarded step for a search
+ procedure and updates an interval that contains a step that
+ satisfies a sufficient decrease and a curvature condition.
+
+ The parameter stx contains the step with the least function
+ value. If brackt is set to .true. then a minimizer has
+ been bracketed in an interval with endpoints stx and sty.
+ The parameter stp contains the current step.
+ The subroutine assumes that if brackt is set to .true. then
+
+ min(stx,sty) < stp < max(stx,sty),
+
+ and that the derivative at stx is negative in the direction
+ of the step.
+
+ The subroutine statement is
+
+ subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt,
+ stpmin,stpmax)
+
+ where
+
+ stx is a double precision variable.
+ On entry stx is the best step obtained so far and is an
+ endpoint of the interval that contains the minimizer.
+ On exit stx is the updated best step.
+
+ fx is a double precision variable.
+ On entry fx is the function at stx.
+ On exit fx is the function at stx.
+
+ dx is a double precision variable.
+ On entry dx is the derivative of the function at
+ stx. The derivative must be negative in the direction of
+ the step, that is, dx and stp - stx must have opposite
+ signs.
+ On exit dx is the derivative of the function at stx.
+
+ sty is a double precision variable.
+ On entry sty is the second endpoint of the interval that
+ contains the minimizer.
+ On exit sty is the updated endpoint of the interval that
+ contains the minimizer.
+
+ fy is a double precision variable.
+ On entry fy is the function at sty.
+ On exit fy is the function at sty.
+
+ dy is a double precision variable.
+ On entry dy is the derivative of the function at sty.
+ On exit dy is the derivative of the function at the exit sty.
+
+ stp is a double precision variable.
+ On entry stp is the current step. If brackt is set to .true.
+ then on input stp must be between stx and sty.
+ On exit stp is a new trial step.
+
+ fp is a double precision variable.
+ On entry fp is the function at stp
+ On exit fp is unchanged.
+
+ dp is a double precision variable.
+ On entry dp is the derivative of the function at stp.
+ On exit dp is unchanged.
+
+ brackt is a logical variable.
+ On entry brackt specifies if a minimizer has been bracketed.
+ Initially brackt must be set to .false.
+ On exit brackt specifies if a minimizer has been bracketed.
+ When a minimizer is bracketed brackt is set to .true.
+
+ stpmin is a double precision variable.
+ On entry stpmin is a lower bound for the step.
+ On exit stpmin is unchanged.
+
+ stpmax is a double precision variable.
+ On entry stpmax is an upper bound for the step.
+ On exit stpmax is unchanged.
+
+ MINPACK-1 Project. June 1983
+ Argonne National Laboratory.
+ Jorge J. More' and David J. Thuente.
+
+ MINPACK-2 Project. November 1993.
+ Argonne National Laboratory and University of Minnesota.
+ Brett M. Averick and Jorge J. More'.
+
+ """
+ sgn_dp = np.sign(dp)
+ sgn_dx = np.sign(dx)
+
+ # sgnd = dp * (dx / abs(dx))
+ sgnd = sgn_dp * sgn_dx
+
+ # First case: A higher function value. The minimum is bracketed.
+ # If the cubic step is closer to stx than the quadratic step, the
+ # cubic step is taken, otherwise the average of the cubic and
+ # quadratic steps is taken.
+ if fp > fx:
+ theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp
+ s = max(abs(theta), abs(dx), abs(dp))
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
+ if stp < stx:
+ gamma *= -1
+ p = (gamma - dx) + theta
+ q = ((gamma - dx) + gamma) + dp
+ r = p / q
+ stpc = stx + r * (stp - stx)
+ stpq = stx + ((dx / ((fx - fp) / (stp - stx) + dx)) / 2.0) * (stp - stx)
+ if abs(stpc - stx) <= abs(stpq - stx):
+ stpf = stpc
+ else:
+ stpf = stpc + (stpq - stpc) / 2.0
+ brackt = True
+ elif sgnd < 0.0:
+ # Second case: A lower function value and derivatives of opposite
+ # sign. The minimum is bracketed. If the cubic step is farther from
+ # stp than the secant step, the cubic step is taken, otherwise the
+ # secant step is taken.
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
+ s = max(abs(theta), abs(dx), abs(dp))
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
+ if stp > stx:
+ gamma *= -1
+ p = (gamma - dp) + theta
+ q = ((gamma - dp) + gamma) + dx
+ r = p / q
+ stpc = stp + r * (stx - stp)
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
+ if abs(stpc - stp) > abs(stpq - stp):
+ stpf = stpc
+ else:
+ stpf = stpq
+ brackt = True
+ elif abs(dp) < abs(dx):
+ # Third case: A lower function value, derivatives of the same sign,
+ # and the magnitude of the derivative decreases.
+
+ # The cubic step is computed only if the cubic tends to infinity
+ # in the direction of the step or if the minimum of the cubic
+ # is beyond stp. Otherwise the cubic step is defined to be the
+ # secant step.
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
+ s = max(abs(theta), abs(dx), abs(dp))
+
+ # The case gamma = 0 only arises if the cubic does not tend
+ # to infinity in the direction of the step.
+ gamma = s * np.sqrt(max(0, (theta / s) ** 2 - (dx / s) * (dp / s)))
+ if stp > stx:
+ gamma = -gamma
+ p = (gamma - dp) + theta
+ q = (gamma + (dx - dp)) + gamma
+ r = p / q
+ if r < 0 and gamma != 0:
+ stpc = stp + r * (stx - stp)
+ elif stp > stx:
+ stpc = stpmax
+ else:
+ stpc = stpmin
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
+
+ if brackt:
+ # A minimizer has been bracketed. If the cubic step is
+ # closer to stp than the secant step, the cubic step is
+ # taken, otherwise the secant step is taken.
+ if abs(stpc - stp) < abs(stpq - stp):
+ stpf = stpc
+ else:
+ stpf = stpq
+
+ if stp > stx:
+ stpf = min(stp + 0.66 * (sty - stp), stpf)
+ else:
+ stpf = max(stp + 0.66 * (sty - stp), stpf)
+ else:
+ # A minimizer has not been bracketed. If the cubic step is
+ # farther from stp than the secant step, the cubic step is
+ # taken, otherwise the secant step is taken.
+ if abs(stpc - stp) > abs(stpq - stp):
+ stpf = stpc
+ else:
+ stpf = stpq
+ stpf = np.clip(stpf, stpmin, stpmax)
+
+ else:
+ # Fourth case: A lower function value, derivatives of the same sign,
+ # and the magnitude of the derivative does not decrease. If the
+ # minimum is not bracketed, the step is either stpmin or stpmax,
+ # otherwise the cubic step is taken.
+ if brackt:
+ theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp
+ s = max(abs(theta), abs(dy), abs(dp))
+ gamma = s * np.sqrt((theta / s) ** 2 - (dy / s) * (dp / s))
+ if stp > sty:
+ gamma = -gamma
+ p = (gamma - dp) + theta
+ q = ((gamma - dp) + gamma) + dy
+ r = p / q
+ stpc = stp + r * (sty - stp)
+ stpf = stpc
+ elif stp > stx:
+ stpf = stpmax
+ else:
+ stpf = stpmin
+
+ # Update the interval which contains a minimizer.
+ if fp > fx:
+ sty = stp
+ fy = fp
+ dy = dp
+ else:
+ if sgnd < 0:
+ sty = stx
+ fy = fx
+ dy = dx
+ stx = stp
+ fx = fp
+ dx = dp
+
+ # Compute the new step.
+ stp = stpf
+
+ return stx, fx, dx, sty, fy, dy, stp, brackt
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_differentiable_functions.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..2af98149e55c1dcf40c78024e6768730102d7b27
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_differentiable_functions.py
@@ -0,0 +1,844 @@
+from collections import namedtuple
+
+import numpy as np
+import scipy.sparse as sps
+from ._numdiff import approx_derivative, group_columns
+from ._hessian_update_strategy import HessianUpdateStrategy
+from scipy.sparse.linalg import LinearOperator
+from scipy._lib._array_api import array_namespace, xp_copy
+from scipy._external import array_api_extra as xpx
+from scipy._lib._util import _ScalarFunctionWrapper
+
+
+FD_METHODS = ('2-point', '3-point', 'cs')
+
+
+class _ScalarGradWrapper:
+ """
+ Wrapper class for gradient calculation
+ """
+ def __init__(
+ self,
+ grad,
+ fun=None,
+ args=None,
+ finite_diff_options=None,
+ ):
+ self.fun = fun
+ self.grad = grad
+ self.args = [] if args is None else args
+ self.finite_diff_options = finite_diff_options
+ self.ngev = 0
+ # number of function evaluations consumed by finite difference
+ self.nfev = 0
+
+ def __call__(self, x, f0=None, **kwds):
+ # Send a copy because the user may overwrite it.
+ # The user of this class might want `x` to remain unchanged.
+ if callable(self.grad):
+ g = np.atleast_1d(self.grad(np.copy(x), *self.args))
+ elif self.grad in FD_METHODS:
+ g, dct = approx_derivative(
+ self.fun,
+ x,
+ f0=f0,
+ **self.finite_diff_options,
+ )
+ self.nfev += dct['nfev']
+
+ self.ngev += 1
+ return g
+
+
+class _ScalarHessWrapper:
+ """
+ Wrapper class for hess calculation via finite differences
+ """
+ def __init__(
+ self,
+ hess,
+ x0=None,
+ grad=None,
+ args=None,
+ finite_diff_options=None,
+ ):
+ self.hess = hess
+ self.grad = grad
+ self.args = [] if args is None else args
+ self.finite_diff_options = finite_diff_options
+ # keep track of any finite difference function evaluations for grad
+ self.ngev = 0
+ self.nhev = 0
+ self.H = None
+ self._hess_func = None
+
+ if callable(hess):
+ self.H = hess(np.copy(x0), *args)
+ self.nhev += 1
+
+ if sps.issparse(self.H):
+ self._hess_func = "sparse_callable"
+ self.H = sps.csr_array(self.H)
+ elif isinstance(self.H, LinearOperator):
+ self._hess_func = "linearoperator_callable"
+ else:
+ # dense
+ self._hess_func = "dense_callable"
+ self.H = np.atleast_2d(np.asarray(self.H))
+ elif hess in FD_METHODS:
+ self._hess_func = "fd_hess"
+
+ def __call__(self, x, f0=None, **kwds):
+ match self._hess_func:
+ case "sparse_callable":
+ _h = self._sparse_callable
+ case "linearoperator_callable":
+ _h = self._linearoperator_callable
+ case "dense_callable":
+ _h = self._dense_callable
+ case "fd_hess":
+ _h = self._fd_hess
+
+ return _h(np.copy(x), f0=f0)
+
+ def _fd_hess(self, x, f0=None, **kwds):
+ self.H, dct = approx_derivative(
+ self.grad, x, f0=f0, **self.finite_diff_options
+ )
+ self.ngev += dct["nfev"]
+ return self.H
+
+ def _sparse_callable(self, x, **kwds):
+ self.nhev += 1
+ self.H = sps.csr_array(self.hess(x, *self.args))
+ return self.H
+
+ def _dense_callable(self, x, **kwds):
+ self.nhev += 1
+ self.H = np.atleast_2d(
+ np.asarray(self.hess(x, *self.args))
+ )
+ return self.H
+
+ def _linearoperator_callable(self, x, **kwds):
+ self.nhev += 1
+ self.H = self.hess(x, *self.args)
+ return self.H
+
+class ScalarFunction:
+ """Scalar function and its derivatives.
+
+ This class defines a scalar function F: R^n->R and methods for
+ computing or approximating its first and second derivatives.
+
+ Parameters
+ ----------
+ fun : callable
+ evaluates the scalar function. Must be of the form ``fun(x, *args)``,
+ where ``x`` is the argument in the form of a 1-D array and ``args`` is
+ a tuple of any additional fixed parameters needed to completely specify
+ the function. Should return a scalar.
+ x0 : array-like
+ Provides an initial set of variables for evaluating fun. Array of real
+ elements of size (n,), where 'n' is the number of independent
+ variables.
+ args : tuple, optional
+ Any additional fixed parameters needed to completely specify the scalar
+ function.
+ grad : {callable, '2-point', '3-point', 'cs'}
+ Method for computing the gradient vector.
+ If it is a callable, it should be a function that returns the gradient
+ vector:
+
+ ``grad(x, *args) -> array_like, shape (n,)``
+
+ where ``x`` is an array with shape (n,) and ``args`` is a tuple with
+ the fixed parameters.
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used
+ to select a finite difference scheme for numerical estimation of the
+ gradient with a relative step size. These finite difference schemes
+ obey any specified `bounds`.
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}
+ Method for computing the Hessian matrix. If it is callable, it should
+ return the Hessian matrix:
+
+ ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``
+
+ where x is a (n,) ndarray and `args` is a tuple with the fixed
+ parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'}
+ select a finite difference scheme for numerical estimation. Or, objects
+ implementing `HessianUpdateStrategy` interface can be used to
+ approximate the Hessian.
+ Whenever the gradient is estimated via finite-differences, the Hessian
+ cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
+ to be estimated using one of the quasi-Newton strategies.
+ finite_diff_rel_step : None or array_like
+ Relative step size to use. The absolute step size is computed as
+ ``h = finite_diff_rel_step * sign(x0) * max(1, abs(x0))``, possibly
+ adjusted to fit into the bounds. For ``method='3-point'`` the sign
+ of `h` is ignored. If None then finite_diff_rel_step is selected
+ automatically,
+ finite_diff_bounds : tuple of array_like
+ Lower and upper bounds on independent variables. Defaults to no bounds,
+ (-np.inf, np.inf). Each bound must match the size of `x0` or be a
+ scalar, in the latter case the bound will be the same for all
+ variables. Use it to limit the range of function evaluation.
+ epsilon : None or array_like, optional
+ Absolute step size to use, possibly adjusted to fit into the bounds.
+ For ``method='3-point'`` the sign of `epsilon` is ignored. By default
+ relative steps are used, only if ``epsilon is not None`` are absolute
+ steps used.
+ workers : map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``, or
+ ``workers(grad, iterable)``, depending on what is being numerically
+ differentiated.
+ Alternatively, if `workers` is an int the task is subdivided into `workers`
+ sections and the function evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ It is recommended that a map-like be used instead of int, as repeated
+ calls to `approx_derivative` will incur large overhead from setting up
+ new processes.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ This class implements a memoization logic. There are methods `fun`,
+ `grad`, hess` and corresponding attributes `f`, `g` and `H`. The following
+ things should be considered:
+
+ 1. Use only public methods `fun`, `grad` and `hess`.
+ 2. After one of the methods is called, the corresponding attribute
+ will be set. However, a subsequent call with a different argument
+ of *any* of the methods may overwrite the attribute.
+ """
+ def __init__(self, fun, x0, args, grad, hess, finite_diff_rel_step=None,
+ finite_diff_bounds=(-np.inf, np.inf), epsilon=None, workers=None):
+
+ if not callable(grad) and grad not in FD_METHODS:
+ raise ValueError(
+ f"`grad` must be either callable or one of {FD_METHODS}."
+ )
+
+ if not (callable(hess) or hess in FD_METHODS
+ or isinstance(hess, HessianUpdateStrategy)):
+ raise ValueError(
+ f"`hess` must be either callable, HessianUpdateStrategy"
+ f" or one of {FD_METHODS}."
+ )
+
+ if grad in FD_METHODS and hess in FD_METHODS:
+ raise ValueError("Whenever the gradient is estimated via "
+ "finite-differences, we require the Hessian "
+ "to be estimated using one of the "
+ "quasi-Newton strategies.")
+ self.xp = xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # original arguments
+ self._wrapped_fun = _ScalarFunctionWrapper(fun, args)
+ self._orig_fun = fun
+ self._orig_grad = grad
+ self._orig_hess = hess
+ self._args = args
+
+ # promotes to floating
+ self.x = xp.astype(_x, _dtype)
+ self.x_dtype = _dtype
+ self.n = self.x.size
+ self.f_updated = False
+ self.g_updated = False
+ self.H_updated = False
+
+ self._lowest_x = None
+ self._lowest_f = np.inf
+
+ # normalize workers
+ workers = workers or map
+
+ finite_diff_options = {}
+ if grad in FD_METHODS:
+ finite_diff_options["method"] = grad
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ finite_diff_options["abs_step"] = epsilon
+ finite_diff_options["bounds"] = finite_diff_bounds
+ finite_diff_options["workers"] = workers
+ finite_diff_options["full_output"] = True
+ if hess in FD_METHODS:
+ finite_diff_options["method"] = hess
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ finite_diff_options["abs_step"] = epsilon
+ finite_diff_options["as_linear_operator"] = True
+ finite_diff_options["workers"] = workers
+ finite_diff_options["full_output"] = True
+
+ # Initial function evaluation
+ self._nfev = 0
+ self._update_fun()
+
+ # Initial gradient evaluation
+ self._wrapped_grad = _ScalarGradWrapper(
+ grad,
+ fun=self._wrapped_fun,
+ args=args,
+ finite_diff_options=finite_diff_options,
+ )
+ self._update_grad()
+
+ # Hessian evaluation
+ if isinstance(hess, HessianUpdateStrategy):
+ self.H = hess
+ self.H.initialize(self.n, 'hess')
+ self.H_updated = True
+ self.x_prev = None
+ self.g_prev = None
+ _FakeCounter = namedtuple('_FakeCounter', ['ngev', 'nhev'])
+ self._wrapped_hess = _FakeCounter(ngev=0, nhev=0)
+ else:
+ if callable(hess):
+ self._wrapped_hess = _ScalarHessWrapper(
+ hess,
+ x0=x0,
+ args=args,
+ finite_diff_options=finite_diff_options
+ )
+ self.H = self._wrapped_hess.H
+ self.H_updated = True
+ elif hess in FD_METHODS:
+ self._wrapped_hess = _ScalarHessWrapper(
+ hess,
+ x0=x0,
+ args=args,
+ grad=self._wrapped_grad,
+ finite_diff_options=finite_diff_options
+ )
+ self._update_grad()
+ self.H = self._wrapped_hess(self.x, f0=self.g)
+ self.H_updated = True
+
+ @property
+ def nfev(self):
+ return self._nfev + self._wrapped_grad.nfev
+
+ @property
+ def ngev(self):
+ return self._wrapped_grad.ngev #+ self._wrapped_hess.ngev
+
+ @property
+ def nhev(self):
+ return self._wrapped_hess.nhev
+
+ def _update_x(self, x):
+ if isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_grad()
+ self.x_prev = self.x
+ self.g_prev = self.g
+ # ensure that self.x is a copy of x. Don't store a reference
+ # otherwise the memoization doesn't work properly.
+
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.g_updated = False
+ self.H_updated = False
+ self._update_hess()
+ else:
+ # ensure that self.x is a copy of x. Don't store a reference
+ # otherwise the memoization doesn't work properly.
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.g_updated = False
+ self.H_updated = False
+
+ def _update_fun(self):
+ if not self.f_updated:
+ fx = self._wrapped_fun(self.x)
+ self._nfev += 1
+ if fx < self._lowest_f:
+ self._lowest_x = self.x
+ self._lowest_f = fx
+
+ self.f = fx
+ self.f_updated = True
+
+ def _update_grad(self):
+ if not self.g_updated:
+ if self._orig_grad in FD_METHODS:
+ self._update_fun()
+ self.g = self._wrapped_grad(self.x, f0=self.f)
+ self.g_updated = True
+
+ def _update_hess(self):
+ if not self.H_updated:
+ if self._orig_hess in FD_METHODS:
+ self._update_grad()
+ self.H = self._wrapped_hess(self.x, f0=self.g)
+ elif isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_grad()
+ self.H.update(self.x - self.x_prev, self.g - self.g_prev)
+ else: # should be callable(hess)
+ self.H = self._wrapped_hess(self.x)
+
+ self.H_updated = True
+
+ def fun(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_fun()
+ return self.f
+
+ def grad(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_grad()
+ return self.g
+
+ def hess(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_hess()
+ return self.H
+
+ def fun_and_grad(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_fun()
+ self._update_grad()
+ return self.f, self.g
+
+
+class _VectorFunWrapper:
+ def __init__(self, fun):
+ self.fun = fun
+ self.nfev = 0
+
+ def __call__(self, x):
+ self.nfev += 1
+ return np.atleast_1d(self.fun(x))
+
+
+class _VectorJacWrapper:
+ """
+ Wrapper class for Jacobian calculation
+ """
+ def __init__(
+ self,
+ jac,
+ fun=None,
+ finite_diff_options=None,
+ sparse_jacobian=None
+ ):
+ self.fun = fun
+ self.jac = jac
+ self.finite_diff_options = finite_diff_options
+ self.sparse_jacobian = sparse_jacobian
+
+ self.njev = 0
+ # number of function evaluations consumed by finite difference
+ self.nfev = 0
+
+ def __call__(self, x, f0=None, **kwds):
+ # Send a copy because the user may overwrite it.
+ # The user of this class might want `x` to remain unchanged.
+ if callable(self.jac):
+ J = self.jac(x)
+ self.njev += 1
+ elif self.jac in FD_METHODS:
+ J, dct = approx_derivative(
+ self.fun,
+ x,
+ f0=f0,
+ **self.finite_diff_options,
+ )
+ self.nfev += dct['nfev']
+
+ if self.sparse_jacobian:
+ return sps.csr_array(J)
+ elif sps.issparse(J):
+ return J.toarray()
+ elif isinstance(J, LinearOperator):
+ return J
+ else:
+ return np.atleast_2d(J)
+
+
+class _VectorHessWrapper:
+ """
+ Wrapper class for Jacobian calculation
+ """
+ def __init__(
+ self,
+ hess,
+ jac=None,
+ finite_diff_options=None,
+ ):
+ self.jac = jac
+ self.hess = hess
+ self.finite_diff_options = finite_diff_options
+ self.nhev = 0
+ # number of jac evaluations consumed by finite difference
+ self.njev = 0
+
+ def __call__(self, x, v, J0=None, **kwds):
+ # Send a copy because the user may overwrite it.
+ # The user of this class might want `x` to remain unchanged.
+ if callable(self.hess):
+ self.nhev += 1
+ return self._callable_hess(x, v)
+ elif self.hess in FD_METHODS:
+ return self._fd_hess(x, v, J0=J0)
+
+ def _fd_hess(self, x, v, J0=None):
+ if J0 is None:
+ J0 = self.jac(x)
+ self.njev += 1
+
+ # H will be a LinearOperator
+ H = approx_derivative(self.jac_dot_v, x,
+ f0=J0.T.dot(v),
+ args=(v,),
+ **self.finite_diff_options)
+ return H
+
+ def jac_dot_v(self, x, v):
+ self.njev += 1
+ return self.jac(x).T.dot(v)
+
+ def _callable_hess(self, x, v):
+ H = self.hess(x, v)
+
+ if sps.issparse(H):
+ return sps.csr_array(H)
+ elif isinstance(H, LinearOperator):
+ return H
+ else:
+ return np.atleast_2d(np.asarray(H))
+
+
+class VectorFunction:
+ """Vector function and its derivatives.
+
+ This class defines a vector function F: R^n->R^m and methods for
+ computing or approximating its first and second derivatives.
+
+ Notes
+ -----
+ This class implements a memoization logic. There are methods `fun`,
+ `jac`, hess` and corresponding attributes `f`, `J` and `H`. The following
+ things should be considered:
+
+ 1. Use only public methods `fun`, `jac` and `hess`.
+ 2. After one of the methods is called, the corresponding attribute
+ will be set. However, a subsequent call with a different argument
+ of *any* of the methods may overwrite the attribute.
+ """
+ def __init__(self, fun, x0, jac, hess,
+ finite_diff_rel_step=None, finite_diff_jac_sparsity=None,
+ finite_diff_bounds=(-np.inf, np.inf), sparse_jacobian=None,
+ workers=None):
+ if not callable(jac) and jac not in FD_METHODS:
+ raise ValueError(f"`jac` must be either callable or one of {FD_METHODS}.")
+
+ if not (callable(hess) or hess in FD_METHODS
+ or isinstance(hess, HessianUpdateStrategy)):
+ raise ValueError("`hess` must be either callable,"
+ f"HessianUpdateStrategy or one of {FD_METHODS}.")
+
+ if jac in FD_METHODS and hess in FD_METHODS:
+ raise ValueError("Whenever the Jacobian is estimated via "
+ "finite-differences, we require the Hessian to "
+ "be estimated using one of the quasi-Newton "
+ "strategies.")
+
+ self.xp = xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # store original functions
+ self._orig_fun = fun
+ self._orig_jac = jac
+ self._orig_hess = hess
+
+ # promotes to floating, ensures that it's a copy
+ self.x = xp.astype(_x, _dtype)
+ self.x_dtype = _dtype
+
+ self.n = self.x.size
+ self._nfev = 0
+ self._njev = 0
+ self._nhev = 0
+ self.f_updated = False
+ self.J_updated = False
+ self.H_updated = False
+
+ # normalize workers
+ workers = workers or map
+
+ finite_diff_options = {}
+ if jac in FD_METHODS:
+ finite_diff_options["method"] = jac
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ if finite_diff_jac_sparsity is not None:
+ sparsity_groups = group_columns(finite_diff_jac_sparsity)
+ finite_diff_options["sparsity"] = (finite_diff_jac_sparsity,
+ sparsity_groups)
+ finite_diff_options["bounds"] = finite_diff_bounds
+ finite_diff_options["workers"] = workers
+ finite_diff_options["full_output"] = True
+ self.x_diff = np.copy(self.x)
+ if hess in FD_METHODS:
+ finite_diff_options["method"] = hess
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ finite_diff_options["as_linear_operator"] = True
+ # workers is not useful for evaluation of the LinearOperator
+ # produced by approx_derivative. Only two/three function
+ # evaluations are used, and the LinearOperator may persist
+ # outside the scope that workers is valid in.
+ self.x_diff = np.copy(self.x)
+ if jac in FD_METHODS and hess in FD_METHODS:
+ raise ValueError("Whenever the Jacobian is estimated via "
+ "finite-differences, we require the Hessian to "
+ "be estimated using one of the quasi-Newton "
+ "strategies.")
+
+ self.fun_wrapped = _VectorFunWrapper(fun)
+ self._update_fun()
+
+ self.v = np.zeros_like(self.f)
+ self.m = self.v.size
+
+ # Initial Jacobian Evaluation
+ if callable(jac):
+ self.J = jac(xp_copy(self.x))
+ self.J_updated = True
+ self._njev += 1
+ elif jac in FD_METHODS:
+ self.J, dct = approx_derivative(
+ self.fun_wrapped, self.x, f0=self.f, **finite_diff_options
+ )
+ self.J_updated = True
+ self._nfev += dct['nfev']
+
+ self.sparse_jacobian = False
+ if (sparse_jacobian or
+ sparse_jacobian is None and sps.issparse(self.J)):
+ # something truthy was specified for sparse_jacobian,
+ # or it turns out that the Jacobian was sparse.
+ self.J = sps.csr_array(self.J)
+ self.sparse_jacobian = True
+ elif sps.issparse(self.J):
+ self.J = self.J.toarray()
+ elif isinstance(self.J, LinearOperator):
+ pass
+ else:
+ self.J = np.atleast_2d(self.J)
+
+ self.jac_wrapped = _VectorJacWrapper(
+ jac,
+ fun=self.fun_wrapped,
+ finite_diff_options=finite_diff_options,
+ sparse_jacobian=self.sparse_jacobian
+ )
+
+ self.hess_wrapped = _VectorHessWrapper(
+ hess, jac=self.jac_wrapped, finite_diff_options=finite_diff_options
+ )
+
+ # Define Hessian
+ if callable(hess) or hess in FD_METHODS:
+ self.H = self.hess_wrapped(xp_copy(self.x), self.v, J0=self.J)
+ self.H_updated = True
+ if callable(hess):
+ self._nhev += 1
+ elif isinstance(hess, HessianUpdateStrategy):
+ self.H = hess
+ self.H.initialize(self.n, 'hess')
+ self.H_updated = True
+ self.x_prev = None
+ self.J_prev = None
+
+ @property
+ def nfev(self):
+ return self._nfev + self.jac_wrapped.nfev
+
+ @property
+ def njev(self):
+ return self._njev + self.hess_wrapped.njev
+
+ @property
+ def nhev(self):
+ return self._nhev
+
+ def _update_v(self, v):
+ if not np.array_equal(v, self.v):
+ self.v = v
+ self.H_updated = False
+
+ def _update_x(self, x):
+ if not np.array_equal(x, self.x):
+ if isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_jac()
+ self.x_prev = self.x
+ self.J_prev = self.J
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.J_updated = False
+ self.H_updated = False
+ self._update_hess()
+ else:
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.J_updated = False
+ self.H_updated = False
+
+ def _update_fun(self):
+ if not self.f_updated:
+ self.f = self.fun_wrapped(xp_copy(self.x))
+ self._nfev += 1
+ self.f_updated = True
+
+ def _update_jac(self):
+ if not self.J_updated:
+ if self._orig_jac in FD_METHODS:
+ # need to update fun to get f0
+ self._update_fun()
+ else:
+ self._njev += 1
+
+ self.J = self.jac_wrapped(xp_copy(self.x), f0=self.f)
+ self.J_updated = True
+
+ def _update_hess(self):
+ if not self.H_updated:
+ if callable(self._orig_hess):
+ self.H = self.hess_wrapped(xp_copy(self.x), self.v)
+ self._nhev += 1
+ elif self._orig_hess in FD_METHODS:
+ self._update_jac()
+ self.H = self.hess_wrapped(xp_copy(self.x), self.v, J0=self.J)
+ elif isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_jac()
+ # When v is updated before x was updated, then x_prev and
+ # J_prev are None and we need this check.
+ if self.x_prev is not None and self.J_prev is not None:
+ delta_x = self.x - self.x_prev
+ delta_g = self.J.T.dot(self.v) - self.J_prev.T.dot(self.v)
+ self.H.update(delta_x, delta_g)
+
+ self.H_updated = True
+
+ def fun(self, x):
+ self._update_x(x)
+ self._update_fun()
+ # returns a copy so that downstream can't overwrite the
+ # internal attribute
+ return xp_copy(self.f)
+
+ def jac(self, x):
+ self._update_x(x)
+ self._update_jac()
+ if hasattr(self.J, "astype"):
+ # returns a copy so that downstream can't overwrite the
+ # internal attribute. But one can't copy a LinearOperator
+ return self.J.astype(self.J.dtype)
+ return self.J
+
+ def hess(self, x, v):
+ # v should be updated before x.
+ self._update_v(v)
+ self._update_x(x)
+ self._update_hess()
+ if hasattr(self.H, "astype"):
+ # returns a copy so that downstream can't overwrite the
+ # internal attribute. But one can't copy non-arrays
+ return self.H.astype(self.H.dtype)
+ return self.H
+
+
+class LinearVectorFunction:
+ """Linear vector function and its derivatives.
+
+ Defines a linear function F = A x, where x is N-D vector and
+ A is m-by-n matrix. The Jacobian is constant and equals to A. The Hessian
+ is identically zero and it is returned as a csr matrix.
+ """
+ def __init__(self, A, x0, sparse_jacobian):
+ if sparse_jacobian or sparse_jacobian is None and sps.issparse(A):
+ self.J = sps.csr_array(A)
+ self.sparse_jacobian = True
+ elif sps.issparse(A):
+ self.J = A.toarray()
+ self.sparse_jacobian = False
+ else:
+ # np.asarray makes sure A is ndarray and not matrix
+ self.J = np.atleast_2d(np.asarray(A))
+ self.sparse_jacobian = False
+
+ self.m, self.n = self.J.shape
+
+ self.xp = xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # promotes to floating
+ self.x = xp.astype(_x, _dtype)
+ self.x_dtype = _dtype
+
+ self.f = self.J.dot(self.x)
+ self.f_updated = True
+
+ self.v = np.zeros(self.m, dtype=float)
+ self.H = sps.csr_array((self.n, self.n))
+
+ def _update_x(self, x):
+ if not np.array_equal(x, self.x):
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+
+ def fun(self, x):
+ self._update_x(x)
+ if not self.f_updated:
+ self.f = self.J.dot(x)
+ self.f_updated = True
+ return self.f
+
+ def jac(self, x):
+ self._update_x(x)
+ return self.J
+
+ def hess(self, x, v):
+ self._update_x(x)
+ self.v = v
+ return self.H
+
+
+class IdentityVectorFunction(LinearVectorFunction):
+ """Identity vector function and its derivatives.
+
+ The Jacobian is the identity matrix, returned as a dense array when
+ `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is
+ identically zero and it is returned as a csr matrix.
+ """
+ def __init__(self, x0, sparse_jacobian):
+ n = len(x0)
+ if sparse_jacobian or sparse_jacobian is None:
+ A = sps.eye_array(n, format='csr')
+ sparse_jacobian = True
+ else:
+ A = np.eye(n)
+ sparse_jacobian = False
+ super().__init__(A, x0, sparse_jacobian)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_differentialevolution.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_differentialevolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6982aa582d60062693d24aac7e506d5e230299f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_differentialevolution.py
@@ -0,0 +1,2037 @@
+"""
+differential_evolution: The differential evolution global optimization algorithm
+Added by Andrew Nelson 2014
+"""
+from functools import partial
+import warnings
+
+import numpy as np
+
+from scipy.optimize import OptimizeResult, minimize
+from scipy.optimize._constraints import (Bounds, new_bounds_to_old,
+ NonlinearConstraint, LinearConstraint)
+from scipy.optimize._optimize import _status_message, _wrap_callback
+from scipy._lib._util import (check_random_state, MapWrapper, _FunctionWrapper,
+ rng_integers, _transition_to_rng)
+from scipy._lib._sparse import issparse
+
+
+__all__ = ['differential_evolution']
+
+
+_MACHEPS = np.finfo(np.float64).eps
+
+
+@_transition_to_rng("seed", position_num=9)
+def differential_evolution(func, bounds, args=(), strategy='best1bin',
+ maxiter=1000, popsize=15, tol=0.01,
+ mutation=(0.5, 1), recombination=0.7, rng=None,
+ callback=None, disp=False, polish=True,
+ init='latinhypercube', atol=0, updating='immediate',
+ workers=1, constraints=(), x0=None, *,
+ integrality=None, vectorized=False):
+ r"""Finds the global minimum of a multivariate function.
+
+ The differential evolution method [1]_ is stochastic in nature. It does
+ not use gradient methods to find the minimum, and can search large areas
+ of candidate space, but often requires larger numbers of function
+ evaluations than conventional gradient-based techniques.
+
+ The algorithm is due to Storn and Price [2]_.
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the form
+ ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+ and ``args`` is a tuple of any additional fixed parameters needed to
+ completely specify the function. The number of parameters, N, is equal
+ to ``len(x)``.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. ``(min, max)`` pairs for each element in ``x``, defining the
+ finite lower and upper bounds for the optimizing argument of
+ `func`.
+
+ The total number of bounds is used to determine the number of
+ parameters, N. If there are parameters whose bounds are equal the total
+ number of free parameters is ``N - N_equal``.
+
+ args : tuple, optional
+ Any additional fixed parameters needed to
+ completely specify the objective function.
+ strategy : {str, callable}, optional
+ The differential evolution strategy to use. Should be one of:
+
+ - 'best1bin'
+ - 'best1exp'
+ - 'rand1bin'
+ - 'rand1exp'
+ - 'rand2bin'
+ - 'rand2exp'
+ - 'randtobest1bin'
+ - 'randtobest1exp'
+ - 'currenttobest1bin'
+ - 'currenttobest1exp'
+ - 'best2exp'
+ - 'best2bin'
+
+ The default is 'best1bin'. Strategies that may be implemented are
+ outlined in 'Notes'.
+ Alternatively the differential evolution strategy can be customized by
+ providing a callable that constructs a trial vector. The callable must
+ have the form ``strategy(candidate: int, population: np.ndarray, rng=None)``,
+ where ``candidate`` is an integer specifying which entry of the
+ population is being evolved, ``population`` is an array of shape
+ ``(S, N)`` containing all the population members (where S is the
+ total population size), and ``rng`` is the random number generator
+ being used within the solver.
+ ``candidate`` will be in the range ``[0, S)``.
+ ``strategy`` must return a trial vector with shape ``(N,)``. The
+ fitness of this trial vector is compared against the fitness of
+ ``population[candidate]``.
+
+ .. versionchanged:: 1.12.0
+ Customization of evolution strategy via a callable.
+
+ maxiter : int, optional
+ The maximum number of generations over which the entire population is
+ evolved. The maximum number of function evaluations (with no polishing)
+ is: ``(maxiter + 1) * popsize * (N - N_equal)``
+ popsize : int, optional
+ A multiplier for setting the total population size. The population has
+ ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
+ an initial population is supplied via the `init` keyword. When using
+ ``init='sobol'`` the population size is calculated as the next power
+ of 2 after ``popsize * (N - N_equal)``.
+ tol : float, optional
+ Relative tolerance for convergence, the solving stops when
+ ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+ where and `atol` and `tol` are the absolute and relative tolerance
+ respectively.
+ mutation : float or tuple(float, float), optional
+ The mutation constant. In the literature this is also known as
+ differential weight, being denoted by :math:`F`.
+ If specified as a float it should be in the range [0, 2).
+ If specified as a tuple ``(min, max)`` dithering is employed. Dithering
+ randomly changes the mutation constant on a generation by generation
+ basis. The mutation constant for that generation is taken from
+ ``U[min, max)``. Dithering can help speed convergence significantly.
+ Increasing the mutation constant increases the search radius, but will
+ slow down convergence.
+ recombination : float, optional
+ The recombination constant, should be in the range [0, 1]. In the
+ literature this is also known as the crossover probability, being
+ denoted by CR. Increasing this value allows a larger number of mutants
+ to progress into the next generation, but at the risk of population
+ stability.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+ disp : bool, optional
+ Prints the evaluated `func` at every iteration.
+ callback : callable, optional
+ A callable called after each iteration. Has the signature::
+
+ callback(intermediate_result: OptimizeResult)
+
+ where ``intermediate_result`` is a keyword parameter containing an
+ `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
+ found so far and the objective function. Note that the name
+ of the parameter must be ``intermediate_result`` for the callback
+ to be passed an `OptimizeResult`.
+
+ The callback also supports a signature like::
+
+ callback(x, convergence: float=val)
+
+ ``val`` represents the fractional value of the population convergence.
+ When ``val`` is greater than ``1.0``, the function halts.
+
+ Introspection is used to determine which of the signatures is invoked.
+
+ Global minimization will halt if the callback raises ``StopIteration``
+ or returns ``True``; any polishing is still carried out.
+
+ .. versionchanged:: 1.12.0
+ callback accepts the ``intermediate_result`` keyword.
+
+ polish : {bool, callable}, optional
+ If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
+ method is used to polish the best population member at the end, which
+ can improve the minimization slightly. If a constrained problem is
+ being studied then the `trust-constr` method is used instead. For large
+ problems with many constraints, polishing can take a long time due to
+ the Jacobian computations.
+ Alternatively supply a callable that has a `minimize`-like signature,
+ ``polish_func(func, x0, **kwds)`` and returns an `OptimizeResult`. This
+ allows the user to have fine control over how the polishing occurs.
+ `bounds` and `constraints` will be present in ``kwds``. Extra keywords
+ could be supplied to `polish_func` using `functools.partial`. It is the
+ user's responsibility to ensure that the polishing function obeys
+ bounds, any constraints (including integrality constraints), and that
+ appropriate attributes are set in the `OptimizeResult`, such as ``fun``,
+ ``x``, ``nfev``, ``jac``.
+
+ .. versionchanged:: 1.15.0
+ If `workers` is specified then the map-like callable that wraps
+ `func` is supplied to `minimize` instead of it using `func`
+ directly. This allows the caller to control how and where the
+ invocations actually run.
+
+ .. versionchanged:: 1.17.0
+ A callable obeying the `minimize` signature can be supplied to
+ polish the best population member.
+
+ init : str or array-like, optional
+ Specify which type of population initialization is performed. Should be
+ one of:
+
+ - 'latinhypercube'
+ - 'sobol'
+ - 'halton'
+ - 'random'
+ - array specifying the initial population. The array should have
+ shape ``(S, N)``, where S is the total population size and N is
+ the number of parameters.
+
+ `init` is clipped to `bounds` before use.
+
+ The default is 'latinhypercube'. Latin Hypercube sampling tries to
+ maximize coverage of the available parameter space.
+
+ 'sobol' and 'halton' are superior alternatives and maximize even more
+ the parameter space. 'sobol' will enforce an initial population
+ size which is calculated as the next power of 2 after
+ ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
+ less efficient. See `scipy.stats.qmc` for more details.
+
+ 'random' initializes the population randomly - this has the drawback
+ that clustering can occur, preventing the whole of parameter space
+ being covered. Use of an array to specify a population could be used,
+ for example, to create a tight bunch of initial guesses in a location
+ where the solution is known to exist, thereby reducing time for
+ convergence.
+ atol : float, optional
+ Absolute tolerance for convergence, the solving stops when
+ ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+ where and `atol` and `tol` are the absolute and relative tolerance
+ respectively.
+ updating : {'immediate', 'deferred'}, optional
+ If ``'immediate'``, the best solution vector is continuously updated
+ within a single generation [4]_. This can lead to faster convergence as
+ trial vectors can take advantage of continuous improvements in the best
+ solution.
+ With ``'deferred'``, the best solution vector is updated once per
+ generation. Only ``'deferred'`` is compatible with parallelization or
+ vectorization, and the `workers` and `vectorized` keywords can
+ over-ride this option.
+
+ .. versionadded:: 1.2.0
+
+ workers : int or map-like callable, optional
+ If `workers` is an int the population is subdivided into `workers`
+ sections and evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ Alternatively supply a map-like callable, such as
+ `multiprocessing.Pool.map` for evaluating the population in parallel.
+ This evaluation is carried out as ``workers(func, iterable)``.
+ This option will override the `updating` keyword to
+ ``updating='deferred'`` if ``workers != 1``.
+ This option overrides the `vectorized` keyword if ``workers != 1``.
+ Requires that `func` be pickleable.
+
+ .. versionadded:: 1.2.0
+
+ constraints : {NonLinearConstraint, LinearConstraint, Bounds}
+ Constraints on the solver, over and above those applied by the `bounds`
+ kwd. Uses the approach by Lampinen [5]_.
+
+ .. versionadded:: 1.4.0
+
+ x0 : None or array-like, optional
+ Provides an initial guess to the minimization. Once the population has
+ been initialized this vector replaces the first (best) member. This
+ replacement is done even if `init` is given an initial population.
+ ``x0.shape == (N,)``.
+
+ .. versionadded:: 1.7.0
+
+ integrality : 1-D array, optional
+ For each decision variable, a boolean value indicating whether the
+ decision variable is constrained to integer values. The array is
+ broadcast to ``(N,)``.
+ If any decision variables are constrained to be integral, they will not
+ be changed during polishing.
+ Only integer values lying between the lower and upper bounds are used.
+ If there are no integer values lying between the bounds then a
+ `ValueError` is raised.
+
+ .. versionadded:: 1.9.0
+
+ vectorized : bool, optional
+ If ``vectorized is True``, `func` is sent an `x` array with
+ ``x.shape == (N, S)``, and is expected to return an array of shape
+ ``(S,)``, where `S` is the number of solution vectors to be calculated.
+ If constraints are applied, each of the functions used to construct
+ a `Constraint` object should accept an `x` array with
+ ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where
+ `M` is the number of constraint components.
+ This option is an alternative to the parallelization offered by
+ `workers`, and may help in optimization speed by reducing interpreter
+ overhead from multiple function calls. This keyword is ignored if
+ ``workers != 1``.
+ This option will override the `updating` keyword to
+ ``updating='deferred'``.
+ See the notes section for further discussion on when to use
+ ``'vectorized'``, and when to use ``'workers'``.
+
+ .. versionadded:: 1.9.0
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully,
+ ``message`` which describes the cause of the termination,
+ ``population`` the solution vectors present in the population, and
+ ``population_energies`` the value of the objective function for each
+ entry in ``population``.
+ See `OptimizeResult` for a description of other attributes. If `polish`
+ was employed, and a lower minimum was obtained by the polishing, then
+ OptimizeResult also contains the ``jac`` attribute.
+ If the eventual solution does not satisfy the applied constraints
+ ``success`` will be `False`.
+
+ Notes
+ -----
+ Differential evolution is a stochastic population based method that is
+ useful for global optimization problems. At each pass through the
+ population the algorithm mutates each candidate solution by mixing with
+ other candidate solutions to create a trial candidate. There are several
+ strategies [3]_ for creating trial candidates, which suit some problems
+ more than others. The 'best1bin' strategy is a good starting point for
+ many systems. In this strategy two members of the population are randomly
+ chosen. Their difference is used to mutate the best member (the 'best' in
+ 'best1bin'), :math:`x_0`, so far:
+
+ .. math::
+
+ b' = x_0 + F \cdot (x_{r_0} - x_{r_1})
+
+ where :math:`F` is the `mutation` parameter.
+ A trial vector is then constructed. Starting with a randomly chosen ith
+ parameter the trial is sequentially filled (in modulo) with parameters
+ from ``b'`` or the original candidate. The choice of whether to use ``b'``
+ or the original candidate is made with a binomial distribution (the 'bin'
+ in 'best1bin') - a random number in [0, 1) is generated. If this number is
+ less than the `recombination` constant then the parameter is loaded from
+ ``b'``, otherwise it is loaded from the original candidate. A randomly
+ selected parameter is always loaded from ``b'``. For binomial crossover,
+ this is a single random parameter. For exponential crossover, this is the
+ starting point of a consecutive sequence of parameters from ``b'``. Once
+ the trial candidate is built its fitness is assessed. If the trial is
+ better than the original candidate then it takes its place. If it is
+ also better than the best overall candidate it also replaces that.
+
+ The other strategies available are outlined in Qiang and
+ Mitchell (2014) [3]_.
+
+
+ - ``rand1`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} - x_{r_2})`
+ - ``rand2`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} + x_{r_2} - x_{r_3} - x_{r_4})`
+ - ``best1`` : :math:`b' = x_0 + F \cdot (x_{r_0} - x_{r_1})`
+ - ``best2`` : :math:`b' = x_0 + F \cdot (x_{r_0} + x_{r_1} - x_{r_2} - x_{r_3})`
+ - ``currenttobest1`` : :math:`b' = x_i + F \cdot (x_0 - x_i + x_{r_0} - x_{r_1})`
+ - ``randtobest1`` : :math:`b' = x_{r_0} + F \cdot (x_0 - x_{r_0} + x_{r_1} - x_{r_2})`
+
+ where the integers :math:`r_0, r_1, r_2, r_3, r_4` are chosen randomly
+ from the interval [0, NP) with `NP` being the total population size and
+ the original candidate having index `i`. The user can fully customize the
+ generation of the trial candidates by supplying a callable to ``strategy``.
+
+ To improve your chances of finding a global minimum use higher `popsize`
+ values, with higher `mutation` and (dithering), but lower `recombination`
+ values. This has the effect of widening the search radius, but slowing
+ convergence.
+
+ By default the best solution vector is updated continuously within a single
+ iteration (``updating='immediate'``). This is a modification [4]_ of the
+ original differential evolution algorithm which can lead to faster
+ convergence as trial vectors can immediately benefit from improved
+ solutions. To use the original Storn and Price behaviour, updating the best
+ solution once per iteration, set ``updating='deferred'``.
+ The ``'deferred'`` approach is compatible with both parallelization and
+ vectorization (``'workers'`` and ``'vectorized'`` keywords). These may
+ improve minimization speed by using computer resources more efficiently.
+ The ``'workers'`` distribute calculations over multiple processors. By
+ default the Python `multiprocessing` module is used, but other approaches
+ are also possible, such as the Message Passing Interface (MPI) used on
+ clusters [6]_ [7]_. The overhead from these approaches (creating new
+ Processes, etc) may be significant, meaning that computational speed
+ doesn't necessarily scale with the number of processors used.
+ Parallelization is best suited to computationally expensive objective
+ functions. If the objective function is less expensive, then
+ ``'vectorized'`` may aid by only calling the objective function once per
+ iteration, rather than multiple times for all the population members; the
+ interpreter overhead is reduced.
+
+ .. versionadded:: 0.15.0
+
+ References
+ ----------
+ .. [1] Differential evolution, Wikipedia,
+ http://en.wikipedia.org/wiki/Differential_evolution
+ .. [2] Storn, R and Price, K, Differential Evolution - a Simple and
+ Efficient Heuristic for Global Optimization over Continuous Spaces,
+ Journal of Global Optimization, 1997, 11, 341 - 359.
+ .. [3] Qiang, J., Mitchell, C., A Unified Differential Evolution Algorithm
+ for Global Optimization, 2014, https://www.osti.gov/servlets/purl/1163659
+ .. [4] Wormington, M., Panaccione, C., Matney, K. M., Bowen, D. K., -
+ Characterization of structures from X-ray scattering data using
+ genetic algorithms, Phil. Trans. R. Soc. Lond. A, 1999, 357,
+ 2827-2848
+ .. [5] Lampinen, J., A constraint handling approach for the differential
+ evolution algorithm. Proceedings of the 2002 Congress on
+ Evolutionary Computation. CEC'02 (Cat. No. 02TH8600). Vol. 2. IEEE,
+ 2002.
+ .. [6] https://mpi4py.readthedocs.io/en/stable/
+ .. [7] https://schwimmbad.readthedocs.io/en/latest/
+
+
+ Examples
+ --------
+ Let us consider the problem of minimizing the Rosenbrock function. This
+ function is implemented in `rosen` in `scipy.optimize`.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen, differential_evolution
+ >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
+ >>> result = differential_evolution(rosen, bounds)
+ >>> result.x, result.fun
+ (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)
+
+ Now repeat, but with parallelization.
+
+ >>> result = differential_evolution(rosen, bounds, updating='deferred',
+ ... workers=2)
+ >>> result.x, result.fun
+ (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)
+
+ Let's do a constrained minimization.
+
+ >>> from scipy.optimize import LinearConstraint, Bounds
+
+ We add the constraint that the sum of ``x[0]`` and ``x[1]`` must be less
+ than or equal to 1.9. This is a linear constraint, which may be written
+ ``A @ x <= 1.9``, where ``A = array([[1, 1]])``. This can be encoded as
+ a `LinearConstraint` instance:
+
+ >>> lc = LinearConstraint([[1, 1]], -np.inf, 1.9)
+
+ Specify limits using a `Bounds` object.
+
+ >>> bounds = Bounds([0., 0.], [2., 2.])
+ >>> result = differential_evolution(rosen, bounds, constraints=lc,
+ ... rng=1)
+ >>> result.x, result.fun
+ (array([0.96632622, 0.93367155]), 0.0011352416852625719)
+
+ Next find the minimum of the Ackley function
+ (https://en.wikipedia.org/wiki/Test_functions_for_optimization).
+
+ >>> def ackley(x):
+ ... arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))
+ ... arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1]))
+ ... return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e
+ >>> bounds = [(-5, 5), (-5, 5)]
+ >>> result = differential_evolution(ackley, bounds, rng=1)
+ >>> result.x, result.fun
+ (array([0., 0.]), 4.440892098500626e-16)
+
+ The Ackley function is written in a vectorized manner, so the
+ ``'vectorized'`` keyword can be employed. Note the reduced number of
+ function evaluations.
+
+ >>> result = differential_evolution(
+ ... ackley, bounds, vectorized=True, updating='deferred', rng=1
+ ... )
+ >>> result.x, result.fun
+ (array([0., 0.]), 4.440892098500626e-16)
+
+ The final polishing step can be customised by providing a callable that
+ mimics the `minimize` interface. The user is responsible for ensuring that
+ the minimizer obeys any bounds and constraints.
+
+ >>> from functools import partial
+ >>> from scipy.optimize import minimize
+ >>> # supply extra parameters to the polishing function using partial
+ >>> polish_func = partial(minimize, method="SLSQP")
+ >>> result = differential_evolution(
+ ... ackley, bounds, vectorized=True, updating='deferred', rng=1,
+ ... polish=polish_func
+ ... )
+ >>> result.x, result.fun
+ (array([0., 0.]), 4.440892098500626e-16)
+
+ The following custom strategy function mimics 'best1bin':
+
+ >>> def custom_strategy_fn(candidate, population, rng=None):
+ ... parameter_count = population.shape[-1]
+ ... mutation, recombination = 0.7, 0.9
+ ... trial = np.copy(population[candidate])
+ ... fill_point = rng.choice(parameter_count)
+ ...
+ ... pool = np.arange(len(population))
+ ... rng.shuffle(pool)
+ ...
+ ... # two unique random numbers that aren't the same, and
+ ... # aren't equal to candidate.
+ ... idxs = []
+ ... while len(idxs) < 2 and len(pool) > 0:
+ ... idx = pool[0]
+ ... pool = pool[1:]
+ ... if idx != candidate:
+ ... idxs.append(idx)
+ ...
+ ... r0, r1 = idxs[:2]
+ ...
+ ... bprime = (population[0] + mutation *
+ ... (population[r0] - population[r1]))
+ ...
+ ... crossovers = rng.uniform(size=parameter_count)
+ ... crossovers = crossovers < recombination
+ ... crossovers[fill_point] = True
+ ... trial = np.where(crossovers, bprime, trial)
+ ... return trial
+
+ """# noqa: E501
+
+ # using a context manager means that any created Pool objects are
+ # cleared up.
+ with DifferentialEvolutionSolver(func, bounds, args=args,
+ strategy=strategy,
+ maxiter=maxiter,
+ popsize=popsize, tol=tol,
+ mutation=mutation,
+ recombination=recombination,
+ rng=rng, polish=polish,
+ callback=callback,
+ disp=disp, init=init, atol=atol,
+ updating=updating,
+ workers=workers,
+ constraints=constraints,
+ x0=x0,
+ integrality=integrality,
+ vectorized=vectorized) as solver:
+ ret = solver.solve()
+
+ return ret
+
+
+class DifferentialEvolutionSolver:
+
+ """This class implements the differential evolution solver
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the form
+ ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+ and ``args`` is a tuple of any additional fixed parameters needed to
+ completely specify the function. The number of parameters, N, is equal
+ to ``len(x)``.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. ``(min, max)`` pairs for each element in ``x``, defining the
+ finite lower and upper bounds for the optimizing argument of
+ `func`.
+
+ The total number of bounds is used to determine the number of
+ parameters, N. If there are parameters whose bounds are equal the total
+ number of free parameters is ``N - N_equal``.
+ args : tuple, optional
+ Any additional fixed parameters needed to
+ completely specify the objective function.
+ strategy : {str, callable}, optional
+ The differential evolution strategy to use. Should be one of:
+
+ - 'best1bin'
+ - 'best1exp'
+ - 'rand1bin'
+ - 'rand1exp'
+ - 'rand2bin'
+ - 'rand2exp'
+ - 'randtobest1bin'
+ - 'randtobest1exp'
+ - 'currenttobest1bin'
+ - 'currenttobest1exp'
+ - 'best2exp'
+ - 'best2bin'
+
+ The default is 'best1bin'. Strategies that may be
+ implemented are outlined in 'Notes'.
+
+ Alternatively the differential evolution strategy can be customized
+ by providing a callable that constructs a trial vector. The callable
+ must have the form
+ ``strategy(candidate: int, population: np.ndarray, rng=None)``,
+ where ``candidate`` is an integer specifying which entry of the
+ population is being evolved, ``population`` is an array of shape
+ ``(S, N)`` containing all the population members (where S is the
+ total population size), and ``rng`` is the random number generator
+ being used within the solver.
+ ``candidate`` will be in the range ``[0, S)``.
+ ``strategy`` must return a trial vector with shape ``(N,)``. The
+ fitness of this trial vector is compared against the fitness of
+ ``population[candidate]``.
+ maxiter : int, optional
+ The maximum number of generations over which the entire population is
+ evolved. The maximum number of function evaluations (with no polishing)
+ is: ``(maxiter + 1) * popsize * (N - N_equal)``
+ popsize : int, optional
+ A multiplier for setting the total population size. The population has
+ ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
+ an initial population is supplied via the `init` keyword. When using
+ ``init='sobol'`` the population size is calculated as the next power
+ of 2 after ``popsize * (N - N_equal)``.
+ tol : float, optional
+ Relative tolerance for convergence, the solving stops when
+ ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+ where and `atol` and `tol` are the absolute and relative tolerance
+ respectively.
+ mutation : float or tuple(float, float), optional
+ The mutation constant. In the literature this is also known as
+ differential weight, being denoted by F.
+ If specified as a float it should be in the range [0, 2].
+ If specified as a tuple ``(min, max)`` dithering is employed. Dithering
+ randomly changes the mutation constant on a generation by generation
+ basis. The mutation constant for that generation is taken from
+ U[min, max). Dithering can help speed convergence significantly.
+ Increasing the mutation constant increases the search radius, but will
+ slow down convergence.
+ recombination : float, optional
+ The recombination constant, should be in the range [0, 1]. In the
+ literature this is also known as the crossover probability, being
+ denoted by CR. Increasing this value allows a larger number of mutants
+ to progress into the next generation, but at the risk of population
+ stability.
+
+ rng : {None, int, `numpy.random.Generator`}, optional
+
+ ..versionchanged:: 1.15.0
+ As part of the `SPEC-007 `_
+ transition from use of `numpy.random.RandomState` to
+ `numpy.random.Generator` this keyword was changed from `seed` to `rng`.
+ For an interim period both keywords will continue to work (only specify
+ one of them). After the interim period using the `seed` keyword will emit
+ warnings. The behavior of the `seed` and `rng` keywords is outlined below.
+
+ If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a `Generator`.
+ If `rng` is already a `Generator` instance, then the provided instance is
+ used.
+
+ If this argument is passed by position or `seed` is passed by keyword, the
+ behavior is:
+
+ - If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+ singleton is used.
+ - If `seed` is an int, a new `RandomState` instance is used,
+ seeded with `seed`.
+ - If `seed` is already a `Generator` or `RandomState` instance then
+ that instance is used.
+
+ Specify `seed`/`rng` for repeatable minimizations.
+ disp : bool, optional
+ Prints the evaluated `func` at every iteration.
+ callback : callable, optional
+ A callable called after each iteration. Has the signature:
+
+ ``callback(intermediate_result: OptimizeResult)``
+
+ where ``intermediate_result`` is a keyword parameter containing an
+ `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
+ found so far and the objective function. Note that the name
+ of the parameter must be ``intermediate_result`` for the callback
+ to be passed an `OptimizeResult`.
+
+ The callback also supports a signature like:
+
+ ``callback(x, convergence: float=val)``
+
+ ``val`` represents the fractional value of the population convergence.
+ When ``val`` is greater than ``1.0``, the function halts.
+
+ Introspection is used to determine which of the signatures is invoked.
+
+ Global minimization will halt if the callback raises ``StopIteration``
+ or returns ``True``; any polishing is still carried out.
+
+ .. versionchanged:: 1.12.0
+ callback accepts the ``intermediate_result`` keyword.
+
+ polish : {bool, callable}, optional
+ If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
+ method is used to polish the best population member at the end, which
+ can improve the minimization slightly. If a constrained problem is
+ being studied then the `trust-constr` method is used instead. For large
+ problems with many constraints, polishing can take a long time due to
+ the Jacobian computations.
+ Alternatively supply a callable that has a `minimize`-like signature,
+ ``polish_func(func, x0, **kwds)`` and returns an `OptimizeResult`. This
+ allows the user to have fine control over how the polishing occurs.
+ `bounds` and `constraints` will be present in ``kwds``. Extra keywords
+ could be supplied to `polish_func` using `functools.partial`. It is the
+ user's responsibility to ensure that the polishing function obeys
+ bounds, any constraints (including integrality constraints), and that
+ appropriate attributes are set in the `OptimizeResult`, such as ``fun``,
+ ``x``, ``nfev``, ``jac``.
+ maxfun : int, optional
+ Set the maximum number of function evaluations. However, it probably
+ makes more sense to set `maxiter` instead.
+ init : str or array-like, optional
+ Specify which type of population initialization is performed. Should be
+ one of:
+
+ - 'latinhypercube'
+ - 'sobol'
+ - 'halton'
+ - 'random'
+ - array specifying the initial population. The array should have
+ shape ``(S, N)``, where S is the total population size and
+ N is the number of parameters.
+ `init` is clipped to `bounds` before use.
+
+ The default is 'latinhypercube'. Latin Hypercube sampling tries to
+ maximize coverage of the available parameter space.
+
+ 'sobol' and 'halton' are superior alternatives and maximize even more
+ the parameter space. 'sobol' will enforce an initial population
+ size which is calculated as the next power of 2 after
+ ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
+ less efficient. See `scipy.stats.qmc` for more details.
+
+ 'random' initializes the population randomly - this has the drawback
+ that clustering can occur, preventing the whole of parameter space
+ being covered. Use of an array to specify a population could be used,
+ for example, to create a tight bunch of initial guesses in a location
+ where the solution is known to exist, thereby reducing time for
+ convergence.
+ atol : float, optional
+ Absolute tolerance for convergence, the solving stops when
+ ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,
+ where and `atol` and `tol` are the absolute and relative tolerance
+ respectively.
+ updating : {'immediate', 'deferred'}, optional
+ If ``'immediate'``, the best solution vector is continuously updated
+ within a single generation [4]_. This can lead to faster convergence as
+ trial vectors can take advantage of continuous improvements in the best
+ solution.
+ With ``'deferred'``, the best solution vector is updated once per
+ generation. Only ``'deferred'`` is compatible with parallelization or
+ vectorization, and the `workers` and `vectorized` keywords can
+ over-ride this option.
+ workers : int or map-like callable, optional
+ If `workers` is an int the population is subdivided into `workers`
+ sections and evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply `-1` to use all cores available to the Process.
+ Alternatively supply a map-like callable, such as
+ `multiprocessing.Pool.map` for evaluating the population in parallel.
+ This evaluation is carried out as ``workers(func, iterable)``.
+ This option will override the `updating` keyword to
+ `updating='deferred'` if `workers != 1`.
+ Requires that `func` be pickleable.
+ constraints : {NonLinearConstraint, LinearConstraint, Bounds}
+ Constraints on the solver, over and above those applied by the `bounds`
+ kwd. Uses the approach by Lampinen.
+ x0 : None or array-like, optional
+ Provides an initial guess to the minimization. Once the population has
+ been initialized this vector replaces the first (best) member. This
+ replacement is done even if `init` is given an initial population.
+ ``x0.shape == (N,)``.
+ integrality : 1-D array, optional
+ For each decision variable, a boolean value indicating whether the
+ decision variable is constrained to integer values. The array is
+ broadcast to ``(N,)``.
+ If any decision variables are constrained to be integral, they will not
+ be changed during polishing.
+ Only integer values lying between the lower and upper bounds are used.
+ If there are no integer values lying between the bounds then a
+ `ValueError` is raised.
+ vectorized : bool, optional
+ If ``vectorized is True``, `func` is sent an `x` array with
+ ``x.shape == (N, S)``, and is expected to return an array of shape
+ ``(S,)``, where `S` is the number of solution vectors to be calculated.
+ If constraints are applied, each of the functions used to construct
+ a `Constraint` object should accept an `x` array with
+ ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where
+ `M` is the number of constraint components.
+ This option is an alternative to the parallelization offered by
+ `workers`, and may help in optimization speed. This keyword is
+ ignored if ``workers != 1``.
+ This option will override the `updating` keyword to
+ ``updating='deferred'``.
+ """ # noqa: E501
+
+ # Dispatch of mutation strategy method (binomial or exponential).
+ _binomial = {'best1bin': '_best1',
+ 'randtobest1bin': '_randtobest1',
+ 'currenttobest1bin': '_currenttobest1',
+ 'best2bin': '_best2',
+ 'rand2bin': '_rand2',
+ 'rand1bin': '_rand1'}
+ _exponential = {'best1exp': '_best1',
+ 'rand1exp': '_rand1',
+ 'randtobest1exp': '_randtobest1',
+ 'currenttobest1exp': '_currenttobest1',
+ 'best2exp': '_best2',
+ 'rand2exp': '_rand2'}
+ __combined = _binomial | _exponential
+
+ __init_error_msg = ("The population initialization method must be one of "
+ "'latinhypercube' or 'random', or an array of shape "
+ "(S, N) where N is the number of parameters and S>5")
+
+ def __init__(self, func, bounds, args=(),
+ strategy='best1bin', maxiter=1000, popsize=15,
+ tol=0.01, mutation=(0.5, 1), recombination=0.7, rng=None,
+ maxfun=np.inf, callback=None, disp=False, polish=True,
+ init='latinhypercube', atol=0, updating='immediate',
+ workers=1, constraints=(), x0=None, *, integrality=None,
+ vectorized=False):
+
+ if callable(strategy):
+ # a callable strategy is going to be stored in self.strategy anyway
+ pass
+ elif strategy not in self.__combined:
+ raise ValueError("Please select a valid mutation strategy")
+ self.strategy = strategy
+
+ self.callback = _wrap_callback(callback, "differential_evolution")
+ self.polish = polish
+
+ # set the updating / parallelisation options
+ if updating in ['immediate', 'deferred']:
+ self._updating = updating
+
+ self.vectorized = vectorized
+
+ # want to use parallelisation, but updating is immediate
+ if workers != 1 and updating == 'immediate':
+ warnings.warn("differential_evolution: the 'workers' keyword has"
+ " overridden updating='immediate' to"
+ " updating='deferred'", UserWarning, stacklevel=2)
+ self._updating = 'deferred'
+
+ if vectorized and workers != 1:
+ warnings.warn("differential_evolution: the 'workers' keyword"
+ " overrides the 'vectorized' keyword", stacklevel=2)
+ self.vectorized = vectorized = False
+
+ if vectorized and updating == 'immediate':
+ warnings.warn("differential_evolution: the 'vectorized' keyword"
+ " has overridden updating='immediate' to updating"
+ "='deferred'", UserWarning, stacklevel=2)
+ self._updating = 'deferred'
+
+ # an object with a map method.
+ if vectorized:
+ def maplike_for_vectorized_func(func, x):
+ # send an array (N, S) to the user func,
+ # expect to receive (S,). Transposition is required because
+ # internally the population is held as (S, N)
+ return np.atleast_1d(func(x.T))
+ workers = maplike_for_vectorized_func
+
+ self._mapwrapper = MapWrapper(workers)
+
+ # relative and absolute tolerances for convergence
+ self.tol, self.atol = tol, atol
+
+ # Mutation constant should be in [0, 2). If specified as a sequence
+ # then dithering is performed.
+ self.scale = mutation
+ if (not np.all(np.isfinite(mutation)) or
+ np.any(np.array(mutation) >= 2) or
+ np.any(np.array(mutation) < 0)):
+ raise ValueError('The mutation constant must be a float in '
+ 'U[0, 2), or specified as a tuple(min, max)'
+ ' where min < max and min, max are in U[0, 2).')
+
+ self.dither = None
+ if hasattr(mutation, '__iter__') and len(mutation) > 1:
+ self.dither = [mutation[0], mutation[1]]
+ self.dither.sort()
+
+ self.cross_over_probability = recombination
+
+ # we create a wrapped function to allow the use of map (and Pool.map
+ # in the future)
+ self.original_func = func
+ self.func = _FunctionWrapper(func, args)
+ self.args = args
+
+ # convert tuple of lower and upper bounds to limits
+ # [(low_0, high_0), ..., (low_n, high_n]
+ # -> [[low_0, ..., low_n], [high_0, ..., high_n]]
+ if isinstance(bounds, Bounds):
+ self.limits = np.array(new_bounds_to_old(bounds.lb,
+ bounds.ub,
+ len(bounds.lb)),
+ dtype=float).T
+ else:
+ self.limits = np.array(bounds, dtype='float').T
+
+ if (np.size(self.limits, 0) != 2 or not
+ np.all(np.isfinite(self.limits))):
+ raise ValueError('bounds should be a sequence containing finite '
+ 'real valued (min, max) pairs for each value'
+ ' in x')
+
+ if maxiter is None: # the default used to be None
+ maxiter = 1000
+ self.maxiter = maxiter
+ if maxfun is None: # the default used to be None
+ maxfun = np.inf
+ self.maxfun = maxfun
+
+ # population is scaled to between [0, 1].
+ # We have to scale between parameter <-> population
+ # save these arguments for _scale_parameter and
+ # _unscale_parameter. This is an optimization
+ self.__scale_arg1 = 0.5 * (self.limits[0] + self.limits[1])
+ self.__scale_arg2 = np.fabs(self.limits[0] - self.limits[1])
+ with np.errstate(divide='ignore'):
+ # if lb == ub then the following line will be 1/0, which is why
+ # we ignore the divide by zero warning. The result from 1/0 is
+ # inf, so replace those values by 0.
+ self.__recip_scale_arg2 = 1 / self.__scale_arg2
+ self.__recip_scale_arg2[~np.isfinite(self.__recip_scale_arg2)] = 0
+
+ self.parameter_count = np.size(self.limits, 1)
+
+ self.random_number_generator = check_random_state(rng)
+
+ # Which parameters are going to be integers?
+ if np.any(integrality):
+ # # user has provided a truth value for integer constraints
+ integrality = np.broadcast_to(
+ integrality,
+ self.parameter_count
+ )
+ integrality = np.asarray(integrality, bool)
+ # For integrality parameters change the limits to only allow
+ # integer values lying between the limits.
+ lb, ub = np.copy(self.limits)
+
+ lb = np.ceil(lb)
+ ub = np.floor(ub)
+ if not (lb[integrality] <= ub[integrality]).all():
+ # there's a parameter that doesn't have an integer value
+ # lying between the limits
+ raise ValueError("One of the integrality constraints does not"
+ " have any possible integer values between"
+ " the lower/upper bounds.")
+ nlb = np.nextafter(lb[integrality] - 0.5, np.inf)
+ nub = np.nextafter(ub[integrality] + 0.5, -np.inf)
+
+ self.integrality = integrality
+ self.limits[0, self.integrality] = nlb
+ self.limits[1, self.integrality] = nub
+ else:
+ self.integrality = False
+
+ # check for equal bounds
+ eb = self.limits[0] == self.limits[1]
+ eb_count = np.count_nonzero(eb)
+
+ # default population initialization is a latin hypercube design, but
+ # there are other population initializations possible.
+ # the minimum is 5 because 'best2bin' requires a population that's at
+ # least 5 long
+ # 202301 - reduced population size to account for parameters with
+ # equal bounds. If there are no varying parameters set N to at least 1
+ self.num_population_members = max(
+ 5,
+ popsize * max(1, self.parameter_count - eb_count)
+ )
+ self.population_shape = (self.num_population_members,
+ self.parameter_count)
+
+ self._nfev = 0
+ # check first str otherwise will fail to compare str with array
+ if isinstance(init, str):
+ if init == 'latinhypercube':
+ self.init_population_lhs()
+ elif init == 'sobol':
+ # must be Ns = 2**m for Sobol'
+ n_s = int(2 ** np.ceil(np.log2(self.num_population_members)))
+ self.num_population_members = n_s
+ self.population_shape = (self.num_population_members,
+ self.parameter_count)
+ self.init_population_qmc(qmc_engine='sobol')
+ elif init == 'halton':
+ self.init_population_qmc(qmc_engine='halton')
+ elif init == 'random':
+ self.init_population_random()
+ else:
+ raise ValueError(self.__init_error_msg)
+ else:
+ self.init_population_array(init)
+
+ if x0 is not None:
+ # scale to within unit interval and
+ # ensure parameters are within bounds.
+ x0_scaled = self._unscale_parameters(np.asarray(x0))
+ if ((x0_scaled > 1.0) | (x0_scaled < 0.0)).any():
+ raise ValueError(
+ "Some entries in x0 lay outside the specified bounds"
+ )
+ self.population[0] = x0_scaled
+
+ # infrastructure for constraints
+ self.constraints = constraints
+ self._wrapped_constraints = []
+
+ if hasattr(constraints, '__len__'):
+ # sequence of constraints, this will also deal with default
+ # keyword parameter
+ for c in constraints:
+ self._wrapped_constraints.append(
+ _ConstraintWrapper(c, self.x)
+ )
+ else:
+ self._wrapped_constraints = [
+ _ConstraintWrapper(constraints, self.x)
+ ]
+ self.total_constraints = np.sum(
+ [c.num_constr for c in self._wrapped_constraints]
+ )
+ self.constraint_violation = np.zeros((self.num_population_members, 1))
+ self.feasible = np.ones(self.num_population_members, bool)
+
+ # an array to shuffle when selecting candidates. Create it here
+ # rather than repeatedly creating it in _select_samples.
+ self._random_population_index = np.arange(self.num_population_members)
+ self.disp = disp
+
+ @property
+ def mutation_func(self):
+ return getattr(self, self.__combined[self.strategy])
+
+ def init_population_lhs(self):
+ """
+ Initializes the population with Latin Hypercube Sampling.
+ Latin Hypercube Sampling ensures that each parameter is uniformly
+ sampled over its range.
+ """
+ rng = self.random_number_generator
+
+ # Each parameter range needs to be sampled uniformly. The scaled
+ # parameter range ([0, 1)) needs to be split into
+ # `self.num_population_members` segments, each of which has the following
+ # size:
+ segsize = 1.0 / self.num_population_members
+
+ # Within each segment we sample from a uniform random distribution.
+ # We need to do this sampling for each parameter.
+ samples = (segsize * rng.uniform(size=self.population_shape)
+
+ # Offset each segment to cover the entire parameter range [0, 1)
+ + np.linspace(0., 1., self.num_population_members,
+ endpoint=False)[:, np.newaxis])
+
+ # Create an array for population of candidate solutions.
+ self.population = np.zeros_like(samples)
+
+ # Initialize population of candidate solutions by permutation of the
+ # random samples.
+ for j in range(self.parameter_count):
+ order = rng.permutation(range(self.num_population_members))
+ self.population[:, j] = samples[order, j]
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ def init_population_qmc(self, qmc_engine):
+ """Initializes the population with a QMC method.
+
+ QMC methods ensures that each parameter is uniformly
+ sampled over its range.
+
+ Parameters
+ ----------
+ qmc_engine : str
+ The QMC method to use for initialization. Can be one of
+ ``latinhypercube``, ``sobol`` or ``halton``.
+
+ """
+ from scipy.stats import qmc
+
+ rng = self.random_number_generator
+
+ # Create an array for population of candidate solutions.
+ if qmc_engine == 'latinhypercube':
+ sampler = qmc.LatinHypercube(d=self.parameter_count, seed=rng)
+ elif qmc_engine == 'sobol':
+ sampler = qmc.Sobol(d=self.parameter_count, seed=rng)
+ elif qmc_engine == 'halton':
+ sampler = qmc.Halton(d=self.parameter_count, seed=rng)
+ else:
+ raise ValueError(self.__init_error_msg)
+
+ self.population = sampler.random(n=self.num_population_members)
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ def init_population_random(self):
+ """
+ Initializes the population at random. This type of initialization
+ can possess clustering, Latin Hypercube sampling is generally better.
+ """
+ rng = self.random_number_generator
+ self.population = rng.uniform(size=self.population_shape)
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ def init_population_array(self, init):
+ """
+ Initializes the population with a user specified population.
+
+ Parameters
+ ----------
+ init : np.ndarray
+ Array specifying subset of the initial population. The array should
+ have shape (S, N), where N is the number of parameters.
+ The population is clipped to the lower and upper bounds.
+ """
+ # make sure you're using a float array
+ popn = np.asarray(init, dtype=np.float64)
+
+ if (np.size(popn, 0) < 5 or
+ popn.shape[1] != self.parameter_count or
+ len(popn.shape) != 2):
+ raise ValueError("The population supplied needs to have shape"
+ " (S, len(x)), where S > 4.")
+
+ # scale values and clip to bounds, assigning to population
+ self.population = np.clip(self._unscale_parameters(popn), 0, 1)
+
+ self.num_population_members = np.size(self.population, 0)
+
+ self.population_shape = (self.num_population_members,
+ self.parameter_count)
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ @property
+ def x(self):
+ """
+ The best solution from the solver
+ """
+ return self._scale_parameters(self.population[0])
+
+ @property
+ def convergence(self):
+ """
+ The standard deviation of the population energies divided by their
+ mean.
+ """
+ if np.any(np.isinf(self.population_energies)):
+ return np.inf
+ return (np.std(self.population_energies) /
+ (np.abs(np.mean(self.population_energies)) + _MACHEPS))
+
+ def converged(self):
+ """
+ Return True if the solver has converged.
+ """
+ if np.any(np.isinf(self.population_energies)):
+ return False
+
+ return (np.std(self.population_energies) <=
+ self.atol +
+ self.tol * np.abs(np.mean(self.population_energies)))
+
+ def solve(self):
+ """
+ Runs the DifferentialEvolutionSolver.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully,
+ ``message`` which describes the cause of the termination,
+ ``population`` the solution vectors present in the population, and
+ ``population_energies`` the value of the objective function for
+ each entry in ``population``.
+ See `OptimizeResult` for a description of other attributes. If
+ `polish` was employed, and a lower minimum was obtained by the
+ polishing, then OptimizeResult also contains the ``jac`` attribute.
+ If the eventual solution does not satisfy the applied constraints
+ ``success`` will be `False`.
+ """
+ nit, warning_flag = 0, False
+ status_message = _status_message['success']
+
+ # The population may have just been initialized (all entries are
+ # np.inf). If it has you have to calculate the initial energies.
+ # Although this is also done in the evolve generator it's possible
+ # that someone can set maxiter=0, at which point we still want the
+ # initial energies to be calculated (the following loop isn't run).
+ if np.all(np.isinf(self.population_energies)):
+ self.feasible, self.constraint_violation = (
+ self._calculate_population_feasibilities(self.population))
+
+ # only work out population energies for feasible solutions
+ self.population_energies[self.feasible] = (
+ self._calculate_population_energies(
+ self.population[self.feasible]))
+
+ self._promote_lowest_energy()
+
+ # do the optimization.
+ for nit in range(1, self.maxiter + 1):
+ # evolve the population by a generation
+ try:
+ next(self)
+ except StopIteration:
+ warning_flag = True
+ if self._nfev > self.maxfun:
+ status_message = _status_message['maxfev']
+ elif self._nfev == self.maxfun:
+ status_message = ('Maximum number of function evaluations'
+ ' has been reached.')
+ break
+
+ if self.disp:
+ print(f"differential_evolution step {nit}: f(x)="
+ f" {self.population_energies[0]}"
+ )
+
+ if self.callback:
+ c = self.tol / (self.convergence + _MACHEPS)
+ res = self._result(nit=nit, message="in progress")
+ res.convergence = c
+ try:
+ warning_flag = bool(self.callback(res))
+ except StopIteration:
+ warning_flag = True
+
+ if warning_flag:
+ status_message = 'callback function requested stop early'
+
+ # should the solver terminate?
+ if warning_flag or self.converged():
+ break
+
+ else:
+ status_message = _status_message['maxiter']
+ warning_flag = True
+
+ DE_result = self._result(
+ nit=nit, message=status_message, warning_flag=warning_flag
+ )
+
+ if self.polish and not np.all(self.integrality):
+ # can't polish if all the parameters are integers
+ if np.any(self.integrality):
+ # set the lower/upper bounds equal so that any integrality
+ # constraints work.
+ limits, integrality = self.limits, self.integrality
+ limits[0, integrality] = DE_result.x[integrality]
+ limits[1, integrality] = DE_result.x[integrality]
+
+ polish_method = 'L-BFGS-B'
+
+ if self._wrapped_constraints:
+ polish_method = 'trust-constr'
+
+ constr_violation = self._constraint_violation_fn(DE_result.x)
+ if np.any(constr_violation > 0.):
+ warnings.warn("differential evolution didn't find a "
+ "solution satisfying the constraints, "
+ "attempting to polish from the least "
+ "infeasible solution",
+ UserWarning, stacklevel=2)
+
+ pf = self.polish
+ _f = self.original_func
+ if not callable(pf):
+ pf = partial(minimize, method=polish_method)
+ def _f(x):
+ return list(self._mapwrapper(self.func, np.atleast_2d(x)))[0]
+
+ if self.disp:
+ print(f"Polishing solution with '{polish_method}'")
+
+ result = pf(
+ _f,
+ np.copy(DE_result.x),
+ bounds=Bounds(lb=self.limits[0], ub=self.limits[1]),
+ constraints=self.constraints
+ )
+
+ if not isinstance(result, OptimizeResult):
+ raise ValueError(
+ "The result from a user defined polishing function "
+ "should return an OptimizeResult."
+ )
+
+ self._nfev += result.get("nfev", 0)
+ DE_result.nfev = self._nfev
+
+ # Polishing solution is only accepted if there is an improvement in
+ # cost function, the polishing was successful and the solution lies
+ # within the bounds.
+ if (result.fun < DE_result.fun and
+ result.success and
+ np.all(result.x <= self.limits[1]) and
+ np.all(self.limits[0] <= result.x)):
+ DE_result.fun = result.fun
+ DE_result.x = result.x
+ DE_result.jac = result.get("jac", None)
+ # to keep internal state consistent
+ self.population_energies[0] = result.fun
+ self.population[0] = self._unscale_parameters(result.x)
+
+ if self._wrapped_constraints:
+ DE_result.constr = [c.violation(DE_result.x) for
+ c in self._wrapped_constraints]
+ DE_result.constr_violation = np.max(
+ np.concatenate(DE_result.constr))
+ DE_result.maxcv = DE_result.constr_violation
+ if DE_result.maxcv > 0:
+ # if the result is infeasible then success must be False
+ DE_result.success = False
+ DE_result.message = ("The solution does not satisfy the "
+ f"constraints, MAXCV = {DE_result.maxcv}")
+
+ return DE_result
+
+ def _result(self, **kwds):
+ # form an intermediate OptimizeResult
+ nit = kwds.get('nit', None)
+ message = kwds.get('message', None)
+ warning_flag = kwds.get('warning_flag', False)
+ result = OptimizeResult(
+ x=self.x,
+ fun=self.population_energies[0],
+ nfev=self._nfev,
+ nit=nit,
+ message=message,
+ success=(warning_flag is not True),
+ population=self._scale_parameters(self.population),
+ population_energies=self.population_energies
+ )
+ if self._wrapped_constraints:
+ result.constr = [c.violation(result.x)
+ for c in self._wrapped_constraints]
+ result.constr_violation = np.max(np.concatenate(result.constr))
+ result.maxcv = result.constr_violation
+ if result.maxcv > 0:
+ result.success = False
+
+ return result
+
+ def _calculate_population_energies(self, population):
+ """
+ Calculate the energies of a population.
+
+ Parameters
+ ----------
+ population : ndarray
+ An array of parameter vectors normalised to [0, 1] using lower
+ and upper limits. Has shape ``(np.size(population, 0), N)``.
+
+ Returns
+ -------
+ energies : ndarray
+ An array of energies corresponding to each population member. If
+ maxfun will be exceeded during this call, then the number of
+ function evaluations will be reduced and energies will be
+ right-padded with np.inf. Has shape ``(np.size(population, 0),)``
+ """
+ num_members = np.size(population, 0)
+ # S is the number of function evals left to stay under the
+ # maxfun budget
+ S = min(num_members, self.maxfun - self._nfev)
+
+ energies = np.full(num_members, np.inf)
+
+ parameters_pop = self._scale_parameters(population)
+ try:
+ calc_energies = list(
+ self._mapwrapper(self.func, parameters_pop[0:S])
+ )
+ calc_energies = np.squeeze(calc_energies)
+ except (TypeError, ValueError) as e:
+ # wrong number of arguments for _mapwrapper
+ # or wrong length returned from the mapper
+ raise RuntimeError(
+ "The map-like callable must be of the form f(func, iterable), "
+ "returning a sequence of numbers the same length as 'iterable'"
+ ) from e
+
+ if calc_energies.size != S:
+ if self.vectorized:
+ raise RuntimeError("The vectorized function must return an"
+ " array of shape (S,) when given an array"
+ " of shape (len(x), S)")
+ raise RuntimeError("func(x, *args) must return a scalar value")
+
+ energies[0:S] = calc_energies
+
+ if self.vectorized:
+ self._nfev += 1
+ else:
+ self._nfev += S
+
+ return energies
+
+ def _promote_lowest_energy(self):
+ # swaps 'best solution' into first population entry
+
+ idx = np.arange(self.num_population_members)
+ feasible_solutions = idx[self.feasible]
+ if feasible_solutions.size:
+ # find the best feasible solution
+ idx_t = np.argmin(self.population_energies[feasible_solutions])
+ l = feasible_solutions[idx_t]
+ else:
+ # no solution was feasible, use 'best' infeasible solution, which
+ # will violate constraints the least
+ l = np.argmin(np.sum(self.constraint_violation, axis=1))
+
+ self.population_energies[[0, l]] = self.population_energies[[l, 0]]
+ self.population[[0, l], :] = self.population[[l, 0], :]
+ self.feasible[[0, l]] = self.feasible[[l, 0]]
+ self.constraint_violation[[0, l], :] = (
+ self.constraint_violation[[l, 0], :])
+
+ def _constraint_violation_fn(self, x):
+ """
+ Calculates total constraint violation for all the constraints, for a
+ set of solutions.
+
+ Parameters
+ ----------
+ x : ndarray
+ Solution vector(s). Has shape (S, N), or (N,), where S is the
+ number of solutions to investigate and N is the number of
+ parameters.
+
+ Returns
+ -------
+ cv : ndarray
+ Total violation of constraints. Has shape ``(S, M)``, where M is
+ the total number of constraint components (which is not necessarily
+ equal to len(self._wrapped_constraints)).
+ """
+ # how many solution vectors you're calculating constraint violations
+ # for
+ S = np.size(x) // self.parameter_count
+ _out = np.zeros((S, self.total_constraints))
+ offset = 0
+ for con in self._wrapped_constraints:
+ # the input/output of the (vectorized) constraint function is
+ # {(N, S), (N,)} --> (M, S)
+ # The input to _constraint_violation_fn is (S, N) or (N,), so
+ # transpose to pass it to the constraint. The output is transposed
+ # from (M, S) to (S, M) for further use.
+ c = con.violation(x.T).T
+
+ # The shape of c should be (M,), (1, M), or (S, M). Check for
+ # those shapes, as an incorrect shape indicates that the
+ # user constraint function didn't return the right thing, and
+ # the reshape operation will fail. Intercept the wrong shape
+ # to give a reasonable error message. I'm not sure what failure
+ # modes an inventive user will come up with.
+ if c.shape[-1] != con.num_constr or (S > 1 and c.shape[0] != S):
+ raise RuntimeError("An array returned from a Constraint has"
+ " the wrong shape. If `vectorized is False`"
+ " the Constraint should return an array of"
+ " shape (M,). If `vectorized is True` then"
+ " the Constraint must return an array of"
+ " shape (M, S), where S is the number of"
+ " solution vectors and M is the number of"
+ " constraint components in a given"
+ " Constraint object.")
+
+ # the violation function may return a 1D array, but is it a
+ # sequence of constraints for one solution (S=1, M>=1), or the
+ # value of a single constraint for a sequence of solutions
+ # (S>=1, M=1)
+ c = np.reshape(c, (S, con.num_constr))
+ _out[:, offset:offset + con.num_constr] = c
+ offset += con.num_constr
+
+ return _out
+
+ def _calculate_population_feasibilities(self, population):
+ """
+ Calculate the feasibilities of a population.
+
+ Parameters
+ ----------
+ population : ndarray
+ An array of parameter vectors normalised to [0, 1] using lower
+ and upper limits. Has shape ``(np.size(population, 0), N)``.
+
+ Returns
+ -------
+ feasible, constraint_violation : ndarray, ndarray
+ Boolean array of feasibility for each population member, and an
+ array of the constraint violation for each population member.
+ constraint_violation has shape ``(np.size(population, 0), M)``,
+ where M is the number of constraints.
+ """
+ num_members = np.size(population, 0)
+ if not self._wrapped_constraints:
+ # shortcut for no constraints
+ return np.ones(num_members, bool), np.zeros((num_members, 1))
+
+ # (S, N)
+ parameters_pop = self._scale_parameters(population)
+
+ if self.vectorized:
+ # (S, M)
+ constraint_violation = np.array(
+ self._constraint_violation_fn(parameters_pop)
+ )
+ else:
+ # (S, 1, M)
+ constraint_violation = np.array([self._constraint_violation_fn(x)
+ for x in parameters_pop])
+ # if you use the list comprehension in the line above it will
+ # create an array of shape (S, 1, M), because each iteration
+ # generates an array of (1, M). In comparison the vectorized
+ # version returns (S, M). It's therefore necessary to remove axis 1
+ constraint_violation = constraint_violation[:, 0]
+
+ feasible = ~(np.sum(constraint_violation, axis=1) > 0)
+
+ return feasible, constraint_violation
+
+ def __iter__(self):
+ return self
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return self._mapwrapper.__exit__(*args)
+
+ def _accept_trial(self, energy_trial, feasible_trial, cv_trial,
+ energy_orig, feasible_orig, cv_orig):
+ """
+ Trial is accepted if:
+ * it satisfies all constraints and provides a lower or equal objective
+ function value, while both the compared solutions are feasible
+ - or -
+ * it is feasible while the original solution is infeasible,
+ - or -
+ * it is infeasible, but provides a lower or equal constraint violation
+ for all constraint functions.
+
+ This test corresponds to section III of Lampinen [1]_.
+
+ Parameters
+ ----------
+ energy_trial : float
+ Energy of the trial solution
+ feasible_trial : float
+ Feasibility of trial solution
+ cv_trial : array-like
+ Excess constraint violation for the trial solution
+ energy_orig : float
+ Energy of the original solution
+ feasible_orig : float
+ Feasibility of original solution
+ cv_orig : array-like
+ Excess constraint violation for the original solution
+
+ Returns
+ -------
+ accepted : bool
+
+ """
+ if feasible_orig and feasible_trial:
+ return energy_trial <= energy_orig
+ elif feasible_trial and not feasible_orig:
+ return True
+ elif not feasible_trial and (cv_trial <= cv_orig).all():
+ # cv_trial < cv_orig would imply that both trial and orig are not
+ # feasible
+ return True
+
+ return False
+
+ def __next__(self):
+ """
+ Evolve the population by a single generation
+
+ Returns
+ -------
+ x : ndarray
+ The best solution from the solver.
+ fun : float
+ Value of objective function obtained from the best solution.
+ """
+ # the population may have just been initialized (all entries are
+ # np.inf). If it has you have to calculate the initial energies
+ if np.all(np.isinf(self.population_energies)):
+ self.feasible, self.constraint_violation = (
+ self._calculate_population_feasibilities(self.population))
+
+ # only need to work out population energies for those that are
+ # feasible
+ self.population_energies[self.feasible] = (
+ self._calculate_population_energies(
+ self.population[self.feasible]))
+
+ self._promote_lowest_energy()
+
+ if self.dither is not None:
+ self.scale = self.random_number_generator.uniform(self.dither[0],
+ self.dither[1])
+
+ if self._updating == 'immediate':
+ # update best solution immediately
+ for candidate in range(self.num_population_members):
+ if self._nfev > self.maxfun:
+ raise StopIteration
+
+ # create a trial solution
+ trial = self._mutate(candidate)
+
+ # ensuring that it's in the range [0, 1)
+ self._ensure_constraint(trial)
+
+ # scale from [0, 1) to the actual parameter value
+ parameters = self._scale_parameters(trial)
+
+ # determine the energy of the objective function
+ if self._wrapped_constraints:
+ cv = self._constraint_violation_fn(parameters)
+ feasible = False
+ energy = np.inf
+ if not np.sum(cv) > 0:
+ # solution is feasible
+ feasible = True
+ energy = self.func(parameters)
+ self._nfev += 1
+ else:
+ feasible = True
+ cv = np.atleast_2d([0.])
+ energy = self.func(parameters)
+ self._nfev += 1
+
+ # compare trial and population member
+ if self._accept_trial(energy, feasible, cv,
+ self.population_energies[candidate],
+ self.feasible[candidate],
+ self.constraint_violation[candidate]):
+ self.population[candidate] = trial
+ self.population_energies[candidate] = np.squeeze(energy)
+ self.feasible[candidate] = feasible
+ self.constraint_violation[candidate] = cv
+
+ # if the trial candidate is also better than the best
+ # solution then promote it.
+ if self._accept_trial(energy, feasible, cv,
+ self.population_energies[0],
+ self.feasible[0],
+ self.constraint_violation[0]):
+ self._promote_lowest_energy()
+
+ elif self._updating == 'deferred':
+ # update best solution once per generation
+ if self._nfev >= self.maxfun:
+ raise StopIteration
+
+ # 'deferred' approach, vectorised form.
+ # create trial solutions
+ trial_pop = self._mutate_many(
+ np.arange(self.num_population_members)
+ )
+
+ # enforce bounds
+ self._ensure_constraint(trial_pop)
+
+ # determine the energies of the objective function, but only for
+ # feasible trials
+ feasible, cv = self._calculate_population_feasibilities(trial_pop)
+ trial_energies = np.full(self.num_population_members, np.inf)
+
+ # only calculate for feasible entries
+ trial_energies[feasible] = self._calculate_population_energies(
+ trial_pop[feasible])
+
+ # which solutions are 'improved'?
+ loc = [self._accept_trial(*val) for val in
+ zip(trial_energies, feasible, cv, self.population_energies,
+ self.feasible, self.constraint_violation)]
+ loc = np.array(loc)
+ self.population = np.where(loc[:, np.newaxis],
+ trial_pop,
+ self.population)
+ self.population_energies = np.where(loc,
+ trial_energies,
+ self.population_energies)
+ self.feasible = np.where(loc,
+ feasible,
+ self.feasible)
+ self.constraint_violation = np.where(loc[:, np.newaxis],
+ cv,
+ self.constraint_violation)
+
+ # make sure the best solution is updated if updating='deferred'.
+ # put the lowest energy into the best solution position.
+ self._promote_lowest_energy()
+
+ return self.x, self.population_energies[0]
+
+ def _scale_parameters(self, trial):
+ """Scale from a number between 0 and 1 to parameters."""
+ # trial either has shape (N, ) or (L, N), where L is the number of
+ # solutions being scaled
+ scaled = self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2
+ if np.count_nonzero(self.integrality):
+ i = np.broadcast_to(self.integrality, scaled.shape)
+ scaled[i] = np.round(scaled[i])
+ return scaled
+
+ def _unscale_parameters(self, parameters):
+ """Scale from parameters to a number between 0 and 1."""
+ return (parameters - self.__scale_arg1) * self.__recip_scale_arg2 + 0.5
+
+ def _ensure_constraint(self, trial):
+ """Make sure the parameters lie between the limits."""
+ mask = np.bitwise_or(trial > 1, trial < 0)
+ if oob := np.count_nonzero(mask):
+ trial[mask] = self.random_number_generator.uniform(size=oob)
+
+ def _mutate_custom(self, candidate):
+ rng = self.random_number_generator
+ msg = (
+ "strategy must have signature"
+ " f(candidate: int, population: np.ndarray, rng=None) returning an"
+ " array of shape (N,)"
+ )
+ _population = self._scale_parameters(self.population)
+ if not len(np.shape(candidate)):
+ # single entry in population
+ trial = self.strategy(candidate, _population, rng=rng)
+ if trial.shape != (self.parameter_count,):
+ raise RuntimeError(msg)
+ else:
+ S = candidate.shape[0]
+ trial = np.array(
+ [self.strategy(c, _population, rng=rng) for c in candidate],
+ dtype=float
+ )
+ if trial.shape != (S, self.parameter_count):
+ raise RuntimeError(msg)
+ return self._unscale_parameters(trial)
+
+ def _mutate_many(self, candidates):
+ """Create trial vectors based on a mutation strategy."""
+ rng = self.random_number_generator
+
+ S = len(candidates)
+ if callable(self.strategy):
+ return self._mutate_custom(candidates)
+
+ trial = np.copy(self.population[candidates])
+ samples = np.array([self._select_samples(c, 5) for c in candidates])
+
+ if self.strategy in ['currenttobest1exp', 'currenttobest1bin']:
+ bprime = self.mutation_func(candidates, samples)
+ else:
+ bprime = self.mutation_func(samples)
+
+ fill_point = rng_integers(rng, self.parameter_count, size=S)
+ crossovers = rng.uniform(size=(S, self.parameter_count))
+ crossovers = crossovers < self.cross_over_probability
+ if self.strategy in self._binomial:
+ # A randomly selected parameter is always from the bprime vector for
+ # binomial crossover. The fill_point ensures at least one parameter
+ # comes from bprime, preventing the possibility of no mutation
+ # influence in the trial vector.
+ i = np.arange(S)
+ crossovers[i, fill_point[i]] = True
+ trial = np.where(crossovers, bprime, trial)
+ return trial
+
+ elif self.strategy in self._exponential:
+ # For exponential crossover, fill_point determines the starting index
+ # for a consecutive sequence of parameters from bprime. The sequence
+ # continues until a crossover probability check fails. The starting
+ # index is always from the bprime vector ensuring at least one
+ # parameter comes from bprime.
+ crossovers[..., 0] = True
+ for j in range(S):
+ i = 0
+ init_fill = fill_point[j]
+ while (i < self.parameter_count and crossovers[j, i]):
+ trial[j, init_fill] = bprime[j, init_fill]
+ init_fill = (init_fill + 1) % self.parameter_count
+ i += 1
+
+ return trial
+
+ def _mutate(self, candidate):
+ """Create a trial vector based on a mutation strategy."""
+ rng = self.random_number_generator
+
+ if callable(self.strategy):
+ return self._mutate_custom(candidate)
+
+ fill_point = rng_integers(rng, self.parameter_count)
+ samples = self._select_samples(candidate, 5)
+
+ trial = np.copy(self.population[candidate])
+
+ if self.strategy in ['currenttobest1exp', 'currenttobest1bin']:
+ bprime = self.mutation_func(candidate, samples)
+ else:
+ bprime = self.mutation_func(samples)
+
+ crossovers = rng.uniform(size=self.parameter_count)
+ crossovers = crossovers < self.cross_over_probability
+ if self.strategy in self._binomial:
+ # A randomly selected parameter is always from the bprime vector for
+ # binomial crossover. The fill_point ensures at least one parameter
+ # comes from bprime, preventing the possibility of no mutation
+ # influence in the trial vector.
+ crossovers[fill_point] = True
+ trial = np.where(crossovers, bprime, trial)
+ return trial
+
+ elif self.strategy in self._exponential:
+ # For exponential crossover, fill_point determines the starting index
+ # for a consecutive sequence of parameters from bprime. The sequence
+ # continues until a crossover probability check fails. The starting
+ # index is always from the bprime vector ensuring at least one
+ # parameter comes from bprime.
+ i = 0
+ crossovers[0] = True
+ while i < self.parameter_count and crossovers[i]:
+ trial[fill_point] = bprime[fill_point]
+ fill_point = (fill_point + 1) % self.parameter_count
+ i += 1
+
+ return trial
+
+ def _best1(self, samples):
+ """best1bin, best1exp"""
+ # samples.shape == (S, 5)
+ # or
+ # samples.shape(5,)
+ r0, r1 = samples[..., :2].T
+ return (self.population[0] + self.scale *
+ (self.population[r0] - self.population[r1]))
+
+ def _rand1(self, samples):
+ """rand1bin, rand1exp"""
+ r0, r1, r2 = samples[..., :3].T
+ return (self.population[r0] + self.scale *
+ (self.population[r1] - self.population[r2]))
+
+ def _randtobest1(self, samples):
+ """randtobest1bin, randtobest1exp"""
+ r0, r1, r2 = samples[..., :3].T
+ bprime = np.copy(self.population[r0])
+ bprime += self.scale * (self.population[0] - bprime)
+ bprime += self.scale * (self.population[r1] -
+ self.population[r2])
+ return bprime
+
+ def _currenttobest1(self, candidate, samples):
+ """currenttobest1bin, currenttobest1exp"""
+ r0, r1 = samples[..., :2].T
+ bprime = (self.population[candidate] + self.scale *
+ (self.population[0] - self.population[candidate] +
+ self.population[r0] - self.population[r1]))
+ return bprime
+
+ def _best2(self, samples):
+ """best2bin, best2exp"""
+ r0, r1, r2, r3 = samples[..., :4].T
+ bprime = (self.population[0] + self.scale *
+ (self.population[r0] + self.population[r1] -
+ self.population[r2] - self.population[r3]))
+
+ return bprime
+
+ def _rand2(self, samples):
+ """rand2bin, rand2exp"""
+ r0, r1, r2, r3, r4 = samples[..., :5].T
+ bprime = (self.population[r0] + self.scale *
+ (self.population[r1] + self.population[r2] -
+ self.population[r3] - self.population[r4]))
+
+ return bprime
+
+ def _select_samples(self, candidate, number_samples):
+ """
+ obtain random integers from range(self.num_population_members),
+ without replacement. You can't have the original candidate either.
+ """
+ self.random_number_generator.shuffle(self._random_population_index)
+ idxs = self._random_population_index[:number_samples + 1]
+ return idxs[idxs != candidate][:number_samples]
+
+
+class _ConstraintWrapper:
+ """Object to wrap/evaluate user defined constraints.
+
+ Very similar in practice to `PreparedConstraint`, except that no evaluation
+ of jac/hess is performed (explicit or implicit).
+
+ If created successfully, it will contain the attributes listed below.
+
+ Parameters
+ ----------
+ constraint : {`NonlinearConstraint`, `LinearConstraint`, `Bounds`}
+ Constraint to check and prepare.
+ x0 : array_like
+ Initial vector of independent variables, shape (N,)
+
+ Attributes
+ ----------
+ fun : callable
+ Function defining the constraint wrapped by one of the convenience
+ classes.
+ bounds : 2-tuple
+ Contains lower and upper bounds for the constraints --- lb and ub.
+ These are converted to ndarray and have a size equal to the number of
+ the constraints.
+
+ Notes
+ -----
+ _ConstraintWrapper.fun and _ConstraintWrapper.violation can get sent
+ arrays of shape (N, S) or (N,), where S is the number of vectors of shape
+ (N,) to consider constraints for.
+ """
+ def __init__(self, constraint, x0):
+ self.constraint = constraint
+
+ if isinstance(constraint, NonlinearConstraint):
+ def fun(x):
+ x = np.asarray(x)
+ return np.atleast_1d(constraint.fun(x))
+ elif isinstance(constraint, LinearConstraint):
+ def fun(x):
+ if issparse(constraint.A):
+ A = constraint.A
+ else:
+ A = np.atleast_2d(constraint.A)
+
+ res = A.dot(x)
+ # x either has shape (N, S) or (N)
+ # (M, N) x (N, S) --> (M, S)
+ # (M, N) x (N,) --> (M,)
+ # However, if (M, N) is a matrix then:
+ # (M, N) * (N,) --> (M, 1), we need this to be (M,)
+ if x.ndim == 1 and res.ndim == 2:
+ # deal with case that constraint.A is an np.matrix
+ # see gh20041
+ res = np.asarray(res)[:, 0]
+
+ return res
+ elif isinstance(constraint, Bounds):
+ def fun(x):
+ return np.asarray(x)
+ else:
+ raise ValueError("`constraint` of an unknown type is passed.")
+
+ self.fun = fun
+
+ lb = np.asarray(constraint.lb, dtype=float)
+ ub = np.asarray(constraint.ub, dtype=float)
+
+ x0 = np.asarray(x0)
+
+ # find out the number of constraints
+ f0 = fun(x0)
+ self.num_constr = m = f0.size
+ self.parameter_count = x0.size
+
+ if lb.ndim == 0:
+ lb = np.resize(lb, m)
+ if ub.ndim == 0:
+ ub = np.resize(ub, m)
+
+ self.bounds = (lb, ub)
+
+ def __call__(self, x):
+ return np.atleast_1d(self.fun(x))
+
+ def violation(self, x):
+ """How much the constraint is exceeded by.
+
+ Parameters
+ ----------
+ x : array-like
+ Vector of independent variables, (N, S), where N is number of
+ parameters and S is the number of solutions to be investigated.
+
+ Returns
+ -------
+ excess : array-like
+ How much the constraint is exceeded by, for each of the
+ constraints specified by `_ConstraintWrapper.fun`.
+ Has shape (M, S) where M is the number of constraint components.
+ """
+ # expect ev to have shape (num_constr, S) or (num_constr,)
+ ev = self.fun(np.asarray(x))
+
+ try:
+ excess_lb = np.maximum(self.bounds[0] - ev.T, 0)
+ excess_ub = np.maximum(ev.T - self.bounds[1], 0)
+ except ValueError as e:
+ raise RuntimeError("An array returned from a Constraint has"
+ " the wrong shape. If `vectorized is False`"
+ " the Constraint should return an array of"
+ " shape (M,). If `vectorized is True` then"
+ " the Constraint must return an array of"
+ " shape (M, S), where S is the number of"
+ " solution vectors and M is the number of"
+ " constraint components in a given"
+ " Constraint object.") from e
+
+ v = (excess_lb + excess_ub).T
+ return v
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_direct.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_direct.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..bc592a8a2e91ff7b63d9e1f20ab0616dc1764d30
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/optimize/_direct.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_direct_py.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_direct_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e2d33ea607c7ec4e13fa37aee87bf7599777cce
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_direct_py.py
@@ -0,0 +1,280 @@
+from typing import ( # noqa: UP035
+ Any, Callable, Iterable
+)
+
+import numpy as np
+from scipy.optimize import OptimizeResult
+from ._constraints import old_bound_to_new, Bounds
+from ._direct import direct as _direct # type: ignore
+
+__all__ = ['direct']
+
+ERROR_MESSAGES = (
+ "Number of function evaluations done is larger than maxfun={}",
+ "Number of iterations is larger than maxiter={}",
+ "u[i] < l[i] for some i",
+ "maxfun is too large",
+ "Initialization failed",
+ "There was an error in the creation of the sample points",
+ "An error occurred while the function was sampled",
+ "Maximum number of levels has been reached.",
+ "Forced stop",
+ "Invalid arguments",
+ "Out of memory",
+)
+
+SUCCESS_MESSAGES = (
+ ("The best function value found is within a relative error={} "
+ "of the (known) global optimum f_min"),
+ ("The volume of the hyperrectangle containing the lowest function value "
+ "found is below vol_tol={}"),
+ ("The side length measure of the hyperrectangle containing the lowest "
+ "function value found is below len_tol={}"),
+)
+
+
+def direct(
+ func: Callable[
+ [np.ndarray[tuple[int], np.dtype[np.float64]]],
+ float | np.floating[Any] | np.integer[Any] | np.bool_,
+ ],
+ bounds: Iterable | Bounds,
+ *,
+ args: tuple = (),
+ eps: float = 1e-4,
+ maxfun: int | None = None,
+ maxiter: int = 1000,
+ locally_biased: bool = True,
+ f_min: float = -np.inf,
+ f_min_rtol: float = 1e-4,
+ vol_tol: float = 1e-16,
+ len_tol: float = 1e-6,
+ callback: Callable[
+ [np.ndarray[tuple[int], np.dtype[np.float64]]],
+ object,
+ ] | None = None,
+) -> OptimizeResult:
+ """
+ Finds the global minimum of a function using the
+ DIRECT algorithm.
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized.
+ ``func(x, *args) -> float``
+ where ``x`` is a 1-D array with shape (n,) and ``args`` is a tuple of
+ the fixed parameters needed to completely specify the function.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. ``(min, max)`` pairs for each element in ``x``.
+
+ args : tuple, optional
+ Any additional fixed parameters needed to
+ completely specify the objective function.
+ eps : float, optional
+ Minimal required difference of the objective function values
+ between the current best hyperrectangle and the next potentially
+ optimal hyperrectangle to be divided. In consequence, `eps` serves as a
+ tradeoff between local and global search: the smaller, the more local
+ the search becomes. Default is 1e-4.
+ maxfun : int or None, optional
+ Approximate upper bound on objective function evaluations.
+ If `None`, will be automatically set to ``1000 * N`` where ``N``
+ represents the number of dimensions. Will be capped if necessary to
+ limit DIRECT's RAM usage to app. 1GiB. This will only occur for very
+ high dimensional problems and excessive `max_fun`. Default is `None`.
+ maxiter : int, optional
+ Maximum number of iterations. Default is 1000.
+ locally_biased : bool, optional
+ If `True` (default), use the locally biased variant of the
+ algorithm known as DIRECT_L. If `False`, use the original unbiased
+ DIRECT algorithm. For hard problems with many local minima,
+ `False` is recommended.
+ f_min : float, optional
+ Function value of the global optimum. Set this value only if the
+ global optimum is known. Default is ``-np.inf``, so that this
+ termination criterion is deactivated.
+ f_min_rtol : float, optional
+ Terminate the optimization once the relative error between the
+ current best minimum `f` and the supplied global minimum `f_min`
+ is smaller than `f_min_rtol`. This parameter is only used if
+ `f_min` is also set. Must lie between 0 and 1. Default is 1e-4.
+ vol_tol : float, optional
+ Terminate the optimization once the volume of the hyperrectangle
+ containing the lowest function value is smaller than `vol_tol`
+ of the complete search space. Must lie between 0 and 1.
+ Default is 1e-16.
+ len_tol : float, optional
+ If ``locally_biased=True``, terminate the optimization once half of
+ the normalized maximal side length of the hyperrectangle containing
+ the lowest function value is smaller than `len_tol`.
+ If ``locally_biased=False``, terminate the optimization once half of
+ the normalized diagonal of the hyperrectangle containing the lowest
+ function value is smaller than `len_tol`. Must lie between 0 and 1.
+ Default is 1e-6.
+ callback : callable, optional
+ A callback function with signature ``callback(xk)`` where ``xk``
+ represents the best function value found so far.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ Notes
+ -----
+ DIviding RECTangles (DIRECT) is a deterministic global
+ optimization algorithm capable of minimizing a black box function with
+ its variables subject to lower and upper bound constraints by sampling
+ potential solutions in the search space [1]_. The algorithm starts by
+ normalising the search space to an n-dimensional unit hypercube.
+ It samples the function at the center of this hypercube and at 2n
+ (n is the number of variables) more points, 2 in each coordinate
+ direction. Using these function values, DIRECT then divides the
+ domain into hyperrectangles, each having exactly one of the sampling
+ points as its center. In each iteration, DIRECT chooses, using the `eps`
+ parameter which defaults to 1e-4, some of the existing hyperrectangles
+ to be further divided. This division process continues until either the
+ maximum number of iterations or maximum function evaluations allowed
+ are exceeded, or the hyperrectangle containing the minimal value found
+ so far becomes small enough. If `f_min` is specified, the optimization
+ will stop once this function value is reached within a relative tolerance.
+ The locally biased variant of DIRECT (originally called DIRECT_L) [2]_ is
+ used by default. It makes the search more locally biased and more
+ efficient for cases with only a few local minima.
+
+ A note about termination criteria: `vol_tol` refers to the volume of the
+ hyperrectangle containing the lowest function value found so far. This
+ volume decreases exponentially with increasing dimensionality of the
+ problem. Therefore `vol_tol` should be decreased to avoid premature
+ termination of the algorithm for higher dimensions. This does not hold
+ for `len_tol`: it refers either to half of the maximal side length
+ (for ``locally_biased=True``) or half of the diagonal of the
+ hyperrectangle (for ``locally_biased=False``).
+
+ This code is based on the DIRECT 2.0.4 Fortran code by Gablonsky et al. at
+ https://ctk.math.ncsu.edu/SOFTWARE/DIRECTv204.tar.gz .
+ This original version was initially converted via f2c and then cleaned up
+ and reorganized by Steven G. Johnson, August 2007, for the NLopt project.
+ The `direct` function wraps the C implementation.
+
+ .. versionadded:: 1.9.0
+
+ References
+ ----------
+ .. [1] Jones, D.R., Perttunen, C.D. & Stuckman, B.E. Lipschitzian
+ optimization without the Lipschitz constant. J Optim Theory Appl
+ 79, 157-181 (1993).
+ .. [2] Gablonsky, J., Kelley, C. A Locally-Biased form of the DIRECT
+ Algorithm. Journal of Global Optimization 21, 27-37 (2001).
+
+ Examples
+ --------
+ The following example is a 2-D problem with four local minima: minimizing
+ the Styblinski-Tang function
+ (https://en.wikipedia.org/wiki/Test_functions_for_optimization).
+
+ >>> from scipy.optimize import direct, Bounds
+ >>> def styblinski_tang(pos):
+ ... x, y = pos
+ ... return 0.5 * (x**4 - 16*x**2 + 5*x + y**4 - 16*y**2 + 5*y)
+ >>> bounds = Bounds([-4., -4.], [4., 4.])
+ >>> result = direct(styblinski_tang, bounds)
+ >>> result.x, result.fun, result.nfev
+ array([-2.90321597, -2.90321597]), -78.3323279095383, 2011
+
+ The correct global minimum was found but with a huge number of function
+ evaluations (2011). Loosening the termination tolerances `vol_tol` and
+ `len_tol` can be used to stop DIRECT earlier.
+
+ >>> result = direct(styblinski_tang, bounds, len_tol=1e-3)
+ >>> result.x, result.fun, result.nfev
+ array([-2.9044353, -2.9044353]), -78.33230330754142, 207
+
+ """
+ # convert bounds to new Bounds class if necessary
+ if not isinstance(bounds, Bounds):
+ if isinstance(bounds, list) or isinstance(bounds, tuple):
+ lb, ub = old_bound_to_new(bounds)
+ bounds = Bounds(lb, ub)
+ else:
+ message = ("bounds must be a sequence or "
+ "instance of Bounds class")
+ raise ValueError(message)
+
+ lb = np.ascontiguousarray(bounds.lb, dtype=np.float64)
+ ub = np.ascontiguousarray(bounds.ub, dtype=np.float64)
+
+ # validate bounds
+ # check that lower bounds are smaller than upper bounds
+ if not np.all(lb < ub):
+ raise ValueError('Bounds are not consistent min < max')
+ # check for infs
+ if (np.any(np.isinf(lb)) or np.any(np.isinf(ub))):
+ raise ValueError("Bounds must not be inf.")
+
+ # validate tolerances
+ if (vol_tol < 0 or vol_tol > 1):
+ raise ValueError("vol_tol must be between 0 and 1.")
+ if (len_tol < 0 or len_tol > 1):
+ raise ValueError("len_tol must be between 0 and 1.")
+ if (f_min_rtol < 0 or f_min_rtol > 1):
+ raise ValueError("f_min_rtol must be between 0 and 1.")
+
+ # validate maxfun and maxiter
+ if maxfun is None:
+ maxfun = 1000 * lb.shape[0]
+ if not isinstance(maxfun, int):
+ raise ValueError("maxfun must be of type int.")
+ if maxfun < 0:
+ raise ValueError("maxfun must be > 0.")
+ if not isinstance(maxiter, int):
+ raise ValueError("maxiter must be of type int.")
+ if maxiter < 0:
+ raise ValueError("maxiter must be > 0.")
+
+ # validate boolean parameters
+ if not isinstance(locally_biased, bool):
+ raise ValueError("locally_biased must be True or False.")
+
+ def _func_wrap(x, args=None):
+ x = np.asarray(x)
+ if args is None:
+ f = func(x)
+ else:
+ f = func(x, *args)
+ # always return a float
+ return np.asarray(f).item()
+
+ # TODO: fix disp argument
+ x, fun, ret_code, nfev, nit = _direct(
+ _func_wrap,
+ np.asarray(lb), np.asarray(ub),
+ args,
+ False, eps, maxfun, maxiter,
+ locally_biased,
+ f_min, f_min_rtol,
+ vol_tol, len_tol, callback
+ )
+
+ format_val = (maxfun, maxiter, f_min_rtol, vol_tol, len_tol)
+ if ret_code > 2:
+ message = SUCCESS_MESSAGES[ret_code - 3].format(
+ format_val[ret_code - 1])
+ elif 0 < ret_code <= 2:
+ message = ERROR_MESSAGES[ret_code - 1].format(format_val[ret_code - 1])
+ elif 0 > ret_code > -100:
+ message = ERROR_MESSAGES[abs(ret_code) + 1]
+ else:
+ message = ERROR_MESSAGES[ret_code + 99]
+
+ return OptimizeResult(x=np.asarray(x), fun=fun, status=ret_code,
+ success=ret_code > 2, message=message,
+ nfev=nfev, nit=nit)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_dual_annealing.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..028e0f8f6b6be59ae904b5418dfdf63080a5d4bc
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_dual_annealing.py
@@ -0,0 +1,735 @@
+# Dual Annealing implementation.
+# Copyright (c) 2018 Sylvain Gubian ,
+# Yang Xiang
+# Author: Sylvain Gubian, Yang Xiang, PMP S.A.
+
+"""
+A Dual Annealing global optimization algorithm
+"""
+
+import numpy as np
+from scipy.optimize import OptimizeResult
+from scipy.optimize import minimize, Bounds
+from scipy.special import gammaln
+from scipy._lib._util import check_random_state, _transition_to_rng
+from scipy.optimize._constraints import new_bounds_to_old
+
+__all__ = ['dual_annealing']
+
+
+class VisitingDistribution:
+ """
+ Class used to generate new coordinates based on the distorted
+ Cauchy-Lorentz distribution. Depending on the steps within the strategy
+ chain, the class implements the strategy for generating new location
+ changes.
+
+ Parameters
+ ----------
+ lb : array_like
+ A 1-D NumPy ndarray containing lower bounds of the generated
+ components. Neither NaN or inf are allowed.
+ ub : array_like
+ A 1-D NumPy ndarray containing upper bounds for the generated
+ components. Neither NaN or inf are allowed.
+ visiting_param : float
+ Parameter for visiting distribution. Default value is 2.62.
+ Higher values give the visiting distribution a heavier tail, this
+ makes the algorithm jump to a more distant region.
+ The value range is (1, 3]. Its value is fixed for the life of the
+ object.
+ rng_gen : {`~numpy.random.Generator`}
+ A `~numpy.random.Generator` object for generating new locations.
+ (can be a `~numpy.random.RandomState` object until SPEC007 transition
+ is fully complete).
+
+ """
+ TAIL_LIMIT = 1.e8
+ MIN_VISIT_BOUND = 1.e-10
+
+ def __init__(self, lb, ub, visiting_param, rng_gen):
+ # if you wish to make _visiting_param adjustable during the life of
+ # the object then _factor2, _factor3, _factor5, _d1, _factor6 will
+ # have to be dynamically calculated in `visit_fn`. They're factored
+ # out here so they don't need to be recalculated all the time.
+ self._visiting_param = visiting_param
+ self.rng_gen = rng_gen
+ self.lower = lb
+ self.upper = ub
+ self.bound_range = ub - lb
+
+ # these are invariant numbers unless visiting_param changes
+ self._factor2 = np.exp((4.0 - self._visiting_param) * np.log(
+ self._visiting_param - 1.0))
+ self._factor3 = np.exp((2.0 - self._visiting_param) * np.log(2.0)
+ / (self._visiting_param - 1.0))
+ self._factor4_p = np.sqrt(np.pi) * self._factor2 / (self._factor3 * (
+ 3.0 - self._visiting_param))
+
+ self._factor5 = 1.0 / (self._visiting_param - 1.0) - 0.5
+ self._d1 = 2.0 - self._factor5
+ self._factor6 = np.pi * (1.0 - self._factor5) / np.sin(
+ np.pi * (1.0 - self._factor5)) / np.exp(gammaln(self._d1))
+
+ def visiting(self, x, step, temperature):
+ """ Based on the step in the strategy chain, new coordinates are
+ generated by changing all components is the same time or only
+ one of them, the new values are computed with visit_fn method
+ """
+ dim = x.size
+ if step < dim:
+ # Changing all coordinates with a new visiting value
+ visits = self.visit_fn(temperature, dim)
+ upper_sample, lower_sample = self.rng_gen.uniform(size=2)
+ visits[visits > self.TAIL_LIMIT] = self.TAIL_LIMIT * upper_sample
+ visits[visits < -self.TAIL_LIMIT] = -self.TAIL_LIMIT * lower_sample
+ x_visit = visits + x
+ a = x_visit - self.lower
+ b = np.fmod(a, self.bound_range) + self.bound_range
+ x_visit = np.fmod(b, self.bound_range) + self.lower
+ x_visit[np.fabs(
+ x_visit - self.lower) < self.MIN_VISIT_BOUND] += 1.e-10
+ else:
+ # Changing only one coordinate at a time based on strategy
+ # chain step
+ x_visit = np.copy(x)
+ visit = self.visit_fn(temperature, 1)[0]
+ if visit > self.TAIL_LIMIT:
+ visit = self.TAIL_LIMIT * self.rng_gen.uniform()
+ elif visit < -self.TAIL_LIMIT:
+ visit = -self.TAIL_LIMIT * self.rng_gen.uniform()
+ index = step - dim
+ x_visit[index] = visit + x[index]
+ a = x_visit[index] - self.lower[index]
+ b = np.fmod(a, self.bound_range[index]) + self.bound_range[index]
+ x_visit[index] = np.fmod(b, self.bound_range[
+ index]) + self.lower[index]
+ if np.fabs(x_visit[index] - self.lower[
+ index]) < self.MIN_VISIT_BOUND:
+ x_visit[index] += self.MIN_VISIT_BOUND
+ return x_visit
+
+ def visit_fn(self, temperature, dim):
+ """ Formula Visita from p. 405 of reference [2] """
+ x, y = self.rng_gen.normal(size=(dim, 2)).T
+
+ factor1 = np.exp(np.log(temperature) / (self._visiting_param - 1.0))
+ factor4 = self._factor4_p * factor1
+
+ # sigmax
+ x *= np.exp(-(self._visiting_param - 1.0) * np.log(
+ self._factor6 / factor4) / (3.0 - self._visiting_param))
+
+ den = np.exp((self._visiting_param - 1.0) * np.log(np.fabs(y)) /
+ (3.0 - self._visiting_param))
+
+ return x / den
+
+
+class EnergyState:
+ """
+ Class used to record the energy state. At any time, it knows what is the
+ currently used coordinates and the most recent best location.
+
+ Parameters
+ ----------
+ lower : array_like
+ A 1-D NumPy ndarray containing lower bounds for generating an initial
+ random components in the `reset` method.
+ upper : array_like
+ A 1-D NumPy ndarray containing upper bounds for generating an initial
+ random components in the `reset` method
+ components. Neither NaN or inf are allowed.
+ callback : callable, ``callback(x, f, context)``, optional
+ A callback function which will be called for all minima found.
+ ``x`` and ``f`` are the coordinates and function value of the
+ latest minimum found, and `context` has value in [0, 1, 2]
+ """
+ # Maximum number of trials for generating a valid starting point
+ MAX_REINIT_COUNT = 1000
+
+ def __init__(self, lower, upper, callback=None):
+ self.ebest = None
+ self.current_energy = None
+ self.current_location = None
+ self.xbest = None
+ self.lower = lower
+ self.upper = upper
+ self.callback = callback
+
+ def reset(self, func_wrapper, rng_gen, x0=None):
+ """
+ Initialize current location is the search domain. If `x0` is not
+ provided, a random location within the bounds is generated.
+ """
+ if x0 is None:
+ self.current_location = rng_gen.uniform(self.lower, self.upper,
+ size=len(self.lower))
+ else:
+ self.current_location = np.copy(x0)
+ init_error = True
+ reinit_counter = 0
+ while init_error:
+ self.current_energy = func_wrapper.fun(self.current_location)
+ if self.current_energy is None:
+ raise ValueError('Objective function is returning None')
+ if not np.isfinite(self.current_energy):
+ if reinit_counter >= EnergyState.MAX_REINIT_COUNT:
+ init_error = False
+ message = (
+ 'Stopping algorithm because function '
+ 'create NaN or (+/-) infinity values even with '
+ 'trying new random parameters'
+ )
+ raise ValueError(message)
+ self.current_location = rng_gen.uniform(self.lower,
+ self.upper,
+ size=self.lower.size)
+ reinit_counter += 1
+ else:
+ init_error = False
+ # If first time reset, initialize ebest and xbest
+ if self.ebest is None and self.xbest is None:
+ self.ebest = self.current_energy
+ self.xbest = np.copy(self.current_location)
+ # Otherwise, we keep them in case of reannealing reset
+
+ def update_best(self, e, x, context):
+ self.ebest = e
+ self.xbest = np.copy(x)
+ if self.callback is not None:
+ val = self.callback(x, e, context)
+ if val is not None:
+ if val:
+ return ('Callback function requested to stop early by '
+ 'returning True')
+
+ def update_current(self, e, x):
+ self.current_energy = e
+ self.current_location = np.copy(x)
+
+
+class StrategyChain:
+ """
+ Class that implements within a Markov chain the strategy for location
+ acceptance and local search decision making.
+
+ Parameters
+ ----------
+ acceptance_param : float
+ Parameter for acceptance distribution. It is used to control the
+ probability of acceptance. The lower the acceptance parameter, the
+ smaller the probability of acceptance. Default value is -5.0 with
+ a range (-1e4, -5].
+ visit_dist : VisitingDistribution
+ Instance of `VisitingDistribution` class.
+ func_wrapper : ObjectiveFunWrapper
+ Instance of `ObjectiveFunWrapper` class.
+ minimizer_wrapper: LocalSearchWrapper
+ Instance of `LocalSearchWrapper` class.
+ rand_gen : {None, int, `numpy.random.Generator`,
+ `numpy.random.RandomState`}, optional
+
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+ singleton is used.
+ If `seed` is an int, a new ``RandomState`` instance is used,
+ seeded with `seed`.
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
+ that instance is used.
+ energy_state: EnergyState
+ Instance of `EnergyState` class.
+
+ """
+
+ def __init__(self, acceptance_param, visit_dist, func_wrapper,
+ minimizer_wrapper, rand_gen, energy_state):
+ # Local strategy chain minimum energy and location
+ self.emin = energy_state.current_energy
+ self.xmin = np.array(energy_state.current_location)
+ # Global optimizer state
+ self.energy_state = energy_state
+ # Acceptance parameter
+ self.acceptance_param = acceptance_param
+ # Visiting distribution instance
+ self.visit_dist = visit_dist
+ # Wrapper to objective function
+ self.func_wrapper = func_wrapper
+ # Wrapper to the local minimizer
+ self.minimizer_wrapper = minimizer_wrapper
+ self.not_improved_idx = 0
+ self.not_improved_max_idx = 1000
+ self._rand_gen = rand_gen
+ self.temperature_step = 0
+ self.K = 100 * len(energy_state.current_location)
+
+ def accept_reject(self, j, e, x_visit):
+ r = self._rand_gen.uniform()
+ pqv_temp = 1.0 - ((1.0 - self.acceptance_param) *
+ (e - self.energy_state.current_energy) / self.temperature_step)
+ if pqv_temp <= 0.:
+ pqv = 0.
+ else:
+ pqv = np.exp(np.log(pqv_temp) / (
+ 1. - self.acceptance_param))
+
+ if r <= pqv:
+ # We accept the new location and update state
+ self.energy_state.update_current(e, x_visit)
+ self.xmin = np.copy(self.energy_state.current_location)
+
+ # No improvement for a long time
+ if self.not_improved_idx >= self.not_improved_max_idx:
+ if j == 0 or self.energy_state.current_energy < self.emin:
+ self.emin = self.energy_state.current_energy
+ self.xmin = np.copy(self.energy_state.current_location)
+
+ def run(self, step, temperature):
+ self.temperature_step = temperature / float(step + 1)
+ self.not_improved_idx += 1
+ for j in range(self.energy_state.current_location.size * 2):
+ if j == 0:
+ if step == 0:
+ self.energy_state_improved = True
+ else:
+ self.energy_state_improved = False
+ x_visit = self.visit_dist.visiting(
+ self.energy_state.current_location, j, temperature)
+ # Calling the objective function
+ e = self.func_wrapper.fun(x_visit)
+ if e < self.energy_state.current_energy:
+ # We have got a better energy value
+ self.energy_state.update_current(e, x_visit)
+ if e < self.energy_state.ebest:
+ val = self.energy_state.update_best(e, x_visit, 0)
+ if val is not None:
+ if val:
+ return val
+ self.energy_state_improved = True
+ self.not_improved_idx = 0
+ else:
+ # We have not improved but do we accept the new location?
+ self.accept_reject(j, e, x_visit)
+ if self.func_wrapper.nfev >= self.func_wrapper.maxfun:
+ return ('Maximum number of function call reached '
+ 'during annealing')
+ # End of StrategyChain loop
+
+ def local_search(self):
+ # Decision making for performing a local search
+ # based on strategy chain results
+ # If energy has been improved or no improvement since too long,
+ # performing a local search with the best strategy chain location
+ if self.energy_state_improved:
+ # Global energy has improved, let's see if LS improves further
+ e, x = self.minimizer_wrapper.local_search(self.energy_state.xbest,
+ self.energy_state.ebest)
+ if e < self.energy_state.ebest:
+ self.not_improved_idx = 0
+ val = self.energy_state.update_best(e, x, 1)
+ if val is not None:
+ if val:
+ return val
+ self.energy_state.update_current(e, x)
+ if self.func_wrapper.nfev >= self.func_wrapper.maxfun:
+ return ('Maximum number of function call reached '
+ 'during local search')
+ # Check probability of a need to perform a LS even if no improvement
+ do_ls = False
+ if self.K < 90 * len(self.energy_state.current_location):
+ pls = np.exp(self.K * (
+ self.energy_state.ebest - self.energy_state.current_energy) /
+ self.temperature_step)
+ if pls >= self._rand_gen.uniform():
+ do_ls = True
+ # Global energy not improved, let's see what LS gives
+ # on the best strategy chain location
+ if self.not_improved_idx >= self.not_improved_max_idx:
+ do_ls = True
+ if do_ls:
+ e, x = self.minimizer_wrapper.local_search(self.xmin, self.emin)
+ self.xmin = np.copy(x)
+ self.emin = e
+ self.not_improved_idx = 0
+ self.not_improved_max_idx = self.energy_state.current_location.size
+ if e < self.energy_state.ebest:
+ val = self.energy_state.update_best(
+ self.emin, self.xmin, 2)
+ if val is not None:
+ if val:
+ return val
+ self.energy_state.update_current(e, x)
+ if self.func_wrapper.nfev >= self.func_wrapper.maxfun:
+ return ('Maximum number of function call reached '
+ 'during dual annealing')
+
+
+class ObjectiveFunWrapper:
+
+ def __init__(self, func, maxfun=1e7, *args):
+ self.func = func
+ self.args = args
+ # Number of objective function evaluations
+ self.nfev = 0
+ # Number of gradient function evaluation if used
+ self.ngev = 0
+ # Number of hessian of the objective function if used
+ self.nhev = 0
+ self.maxfun = maxfun
+
+ def fun(self, x):
+ self.nfev += 1
+ return self.func(x, *self.args)
+
+
+class LocalSearchWrapper:
+ """
+ Class used to wrap around the minimizer used for local search
+ Default local minimizer is SciPy minimizer L-BFGS-B
+ """
+
+ LS_MAXITER_RATIO = 6
+ LS_MAXITER_MIN = 100
+ LS_MAXITER_MAX = 1000
+
+ def __init__(self, search_bounds, func_wrapper, *args, **kwargs):
+ self.func_wrapper = func_wrapper
+ self.kwargs = kwargs
+ self.jac = self.kwargs.get('jac', None)
+ self.hess = self.kwargs.get('hess', None)
+ self.hessp = self.kwargs.get('hessp', None)
+ self.kwargs.pop("args", None)
+ self.minimizer = minimize
+ bounds_list = list(zip(*search_bounds))
+ self.lower = np.array(bounds_list[0])
+ self.upper = np.array(bounds_list[1])
+
+ # If no minimizer specified, use SciPy minimize with 'L-BFGS-B' method
+ if not self.kwargs:
+ n = len(self.lower)
+ ls_max_iter = min(max(n * self.LS_MAXITER_RATIO,
+ self.LS_MAXITER_MIN),
+ self.LS_MAXITER_MAX)
+ self.kwargs['method'] = 'L-BFGS-B'
+ self.kwargs['options'] = {
+ 'maxiter': ls_max_iter,
+ }
+ self.kwargs['bounds'] = list(zip(self.lower, self.upper))
+ else:
+ if callable(self.jac):
+ def wrapped_jac(x):
+ return self.jac(x, *args)
+ self.kwargs['jac'] = wrapped_jac
+ if callable(self.hess):
+ def wrapped_hess(x):
+ return self.hess(x, *args)
+ self.kwargs['hess'] = wrapped_hess
+ if callable(self.hessp):
+ def wrapped_hessp(x, p):
+ return self.hessp(x, p, *args)
+ self.kwargs['hessp'] = wrapped_hessp
+
+ def local_search(self, x, e):
+ # Run local search from the given x location where energy value is e
+ x_tmp = np.copy(x)
+ mres = self.minimizer(self.func_wrapper.fun, x, **self.kwargs)
+ if 'njev' in mres:
+ self.func_wrapper.ngev += mres.njev
+ if 'nhev' in mres:
+ self.func_wrapper.nhev += mres.nhev
+ # Check if is valid value
+ is_finite = np.all(np.isfinite(mres.x)) and np.isfinite(mres.fun)
+ in_bounds = np.all(mres.x >= self.lower) and np.all(
+ mres.x <= self.upper)
+ is_valid = is_finite and in_bounds
+
+ # Use the new point only if it is valid and return a better results
+ if is_valid and mres.fun < e:
+ return mres.fun, mres.x
+ else:
+ return e, x_tmp
+
+
+@_transition_to_rng("seed", position_num=10)
+def dual_annealing(func, bounds, args=(), maxiter=1000,
+ minimizer_kwargs=None, initial_temp=5230.,
+ restart_temp_ratio=2.e-5, visit=2.62, accept=-5.0,
+ maxfun=1e7, rng=None, no_local_search=False,
+ callback=None, x0=None):
+ """
+ Find the global minimum of a function using Dual Annealing.
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the form
+ ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+ and ``args`` is a tuple of any additional fixed parameters needed to
+ completely specify the function.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`.
+
+ args : tuple, optional
+ Any additional fixed parameters needed to completely specify the
+ objective function.
+ maxiter : int, optional
+ The maximum number of global search iterations. Default value is 1000.
+ minimizer_kwargs : dict, optional
+ Keyword arguments to be passed to the local minimizer
+ (`minimize`). An important option could be ``method`` for the minimizer
+ method to use.
+ If no keyword arguments are provided, the local minimizer defaults to
+ 'L-BFGS-B' and uses the already supplied bounds. If `minimizer_kwargs`
+ is specified, then the dict must contain all parameters required to
+ control the local minimization. `args` is ignored in this dict, as it is
+ passed automatically. `bounds` is not automatically passed on to the
+ local minimizer as the method may not support them.
+ initial_temp : float, optional
+ The initial temperature, use higher values to facilitates a wider
+ search of the energy landscape, allowing dual_annealing to escape
+ local minima that it is trapped in. Default value is 5230. Range is
+ (0.01, 5.e4].
+ restart_temp_ratio : float, optional
+ During the annealing process, temperature is decreasing, when it
+ reaches ``initial_temp * restart_temp_ratio``, the reannealing process
+ is triggered. Default value of the ratio is 2e-5. Range is (0, 1).
+ visit : float, optional
+ Parameter for visiting distribution. Default value is 2.62. Higher
+ values give the visiting distribution a heavier tail, this makes
+ the algorithm jump to a more distant region. The value range is (1, 3].
+ accept : float, optional
+ Parameter for acceptance distribution. It is used to control the
+ probability of acceptance. The lower the acceptance parameter, the
+ smaller the probability of acceptance. Default value is -5.0 with
+ a range (-1e4, -5].
+ maxfun : int, optional
+ Soft limit for the number of objective function calls. If the
+ algorithm is in the middle of a local search, this number will be
+ exceeded, the algorithm will stop just after the local search is
+ done. Default value is 1e7.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a `Generator`.
+
+ Specify `rng` for repeatable minimizations. The random numbers
+ generated only affect the visiting distribution function
+ and new coordinates generation.
+ no_local_search : bool, optional
+ If `no_local_search` is set to True, a traditional Generalized
+ Simulated Annealing will be performed with no local search
+ strategy applied.
+ callback : callable, optional
+ A callback function with signature ``callback(x, f, context)``,
+ which will be called for all minima found.
+ ``x`` and ``f`` are the coordinates and function value of the
+ latest minimum found, and ``context`` has one of the following
+ values:
+
+ - ``0``: minimum detected in the annealing process.
+ - ``1``: detection occurred in the local search process.
+ - ``2``: detection done in the dual annealing process.
+
+ If the callback implementation returns True, the algorithm will stop.
+ x0 : ndarray, shape(n,), optional
+ Coordinates of a single N-D starting point.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are: ``x`` the solution array, ``fun`` the value
+ of the function at the solution, and ``message`` which describes the
+ cause of the termination.
+ See `OptimizeResult` for a description of other attributes.
+
+ Notes
+ -----
+ This function implements the Dual Annealing optimization. This stochastic
+ approach derived from [3]_ combines the generalization of CSA (Classical
+ Simulated Annealing) and FSA (Fast Simulated Annealing) [1]_ [2]_ coupled
+ to a strategy for applying a local search on accepted locations [4]_.
+ An alternative implementation of this same algorithm is described in [5]_
+ and benchmarks are presented in [6]_. This approach introduces an advanced
+ method to refine the solution found by the generalized annealing
+ process. This algorithm uses a distorted Cauchy-Lorentz visiting
+ distribution, with its shape controlled by the parameter :math:`q_{v}`
+
+ .. math::
+
+ g_{q_{v}}(\\Delta x(t)) \\propto \\frac{ \\
+ \\left[T_{q_{v}}(t) \\right]^{-\\frac{D}{3-q_{v}}}}{ \\
+ \\left[{1+(q_{v}-1)\\frac{(\\Delta x(t))^{2}} { \\
+ \\left[T_{q_{v}}(t)\\right]^{\\frac{2}{3-q_{v}}}}}\\right]^{ \\
+ \\frac{1}{q_{v}-1}+\\frac{D-1}{2}}}
+
+ Where :math:`t` is the artificial time. This visiting distribution is used
+ to generate a trial jump distance :math:`\\Delta x(t)` of variable
+ :math:`x(t)` under artificial temperature :math:`T_{q_{v}}(t)`.
+
+ From the starting point, after calling the visiting distribution
+ function, the acceptance probability is computed as follows:
+
+ .. math::
+
+ p_{q_{a}} = \\min{\\{1,\\left[1-(1-q_{a}) \\beta \\Delta E \\right]^{ \\
+ \\frac{1}{1-q_{a}}}\\}}
+
+ Where :math:`q_{a}` is a acceptance parameter. For :math:`q_{a}<1`, zero
+ acceptance probability is assigned to the cases where
+
+ .. math::
+
+ [1-(1-q_{a}) \\beta \\Delta E] < 0
+
+ The artificial temperature :math:`T_{q_{v}}(t)` is decreased according to
+
+ .. math::
+
+ T_{q_{v}}(t) = T_{q_{v}}(1) \\frac{2^{q_{v}-1}-1}{\\left( \\
+ 1 + t\\right)^{q_{v}-1}-1}
+
+ Where :math:`q_{v}` is the visiting parameter.
+
+ The default values and accepted ranges for the parameters are based on
+ the recommendations from [1]_.
+
+ .. versionadded:: 1.2.0
+
+ References
+ ----------
+ .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs
+ statistics. Journal of Statistical Physics, 52, 479-487 (1988).
+ .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing.
+ Physica A, 233, 395-406 (1996).
+ .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated
+ Annealing Algorithm and Its Application to the Thomson Model.
+ Physics Letters A, 233, 216-220 (1997).
+ .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated
+ Annealing. Physical Review E, 62, 4473 (2000).
+ .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized
+ Simulated Annealing for Efficient Global Optimization: the GenSA
+ Package for R. The R Journal, Volume 5/1 (2013).
+ .. [6] Mullen, K. Continuous Global Optimization in R. Journal of
+ Statistical Software, 60(6), 1 - 45, (2014).
+ :doi:`10.18637/jss.v060.i06`
+
+ Examples
+ --------
+ The following example is a 10-D problem, with many local minima.
+ The function involved is called Rastrigin
+ (https://en.wikipedia.org/wiki/Rastrigin_function)
+
+ >>> import numpy as np
+ >>> from scipy.optimize import dual_annealing
+ >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x)
+ >>> lw = [-5.12] * 10
+ >>> up = [5.12] * 10
+ >>> ret = dual_annealing(func, bounds=list(zip(lw, up)))
+ >>> ret.x
+ array([-4.26437714e-09, -3.91699361e-09, -1.86149218e-09, -3.97165720e-09,
+ -6.29151648e-09, -6.53145322e-09, -3.93616815e-09, -6.55623025e-09,
+ -6.05775280e-09, -5.00668935e-09]) # random
+ >>> ret.fun
+ 0.000000
+
+ """
+
+ if isinstance(bounds, Bounds):
+ bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb))
+
+ if x0 is not None and not len(x0) == len(bounds):
+ raise ValueError('Bounds size does not match x0')
+
+ lu = list(zip(*bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ # Check that restart temperature ratio is correct
+ if restart_temp_ratio <= 0. or restart_temp_ratio >= 1.:
+ raise ValueError('Restart temperature ratio has to be in range (0, 1)')
+ # Checking bounds are valid
+ if (np.any(np.isinf(lower)) or np.any(np.isinf(upper)) or np.any(
+ np.isnan(lower)) or np.any(np.isnan(upper))):
+ raise ValueError('Some bounds values are inf values or nan values')
+ # Checking that bounds are consistent
+ if not np.all(lower < upper):
+ raise ValueError('Bounds are not consistent min < max')
+ # Checking that bounds are the same length
+ if not len(lower) == len(upper):
+ raise ValueError('Bounds do not have the same dimensions')
+
+ # Wrapper for the objective function
+ func_wrapper = ObjectiveFunWrapper(func, maxfun, *args)
+
+ # minimizer_kwargs has to be a dict, not None
+ minimizer_kwargs = minimizer_kwargs or {}
+
+ minimizer_wrapper = LocalSearchWrapper(
+ bounds, func_wrapper, *args, **minimizer_kwargs)
+
+ # Initialization of random Generator for reproducible runs if rng provided
+ rng_gen = check_random_state(rng)
+ # Initialization of the energy state
+ energy_state = EnergyState(lower, upper, callback)
+ energy_state.reset(func_wrapper, rng_gen, x0)
+ # Minimum value of annealing temperature reached to perform
+ # re-annealing
+ temperature_restart = initial_temp * restart_temp_ratio
+ # VisitingDistribution instance
+ visit_dist = VisitingDistribution(lower, upper, visit, rng_gen)
+ # Strategy chain instance
+ strategy_chain = StrategyChain(accept, visit_dist, func_wrapper,
+ minimizer_wrapper, rng_gen, energy_state)
+ need_to_stop = False
+ iteration = 0
+ message = []
+ # OptimizeResult object to be returned
+ optimize_res = OptimizeResult()
+ optimize_res.success = True
+ optimize_res.status = 0
+
+ t1 = np.exp((visit - 1) * np.log(2.0)) - 1.0
+ # Run the search loop
+ while not need_to_stop:
+ for i in range(maxiter):
+ # Compute temperature for this step
+ s = float(i) + 2.0
+ t2 = np.exp((visit - 1) * np.log(s)) - 1.0
+ temperature = initial_temp * t1 / t2
+ if iteration >= maxiter:
+ message.append("Maximum number of iteration reached")
+ need_to_stop = True
+ break
+ # Need a re-annealing process?
+ if temperature < temperature_restart:
+ energy_state.reset(func_wrapper, rng_gen)
+ break
+ # starting strategy chain
+ val = strategy_chain.run(i, temperature)
+ if val is not None:
+ message.append(val)
+ need_to_stop = True
+ optimize_res.success = False
+ break
+ # Possible local search at the end of the strategy chain
+ if not no_local_search:
+ val = strategy_chain.local_search()
+ if val is not None:
+ message.append(val)
+ need_to_stop = True
+ optimize_res.success = False
+ break
+ iteration += 1
+
+ # Setting the OptimizeResult values
+ optimize_res.x = energy_state.xbest
+ optimize_res.fun = energy_state.ebest
+ optimize_res.nit = iteration
+ optimize_res.nfev = func_wrapper.nfev
+ optimize_res.njev = func_wrapper.ngev
+ optimize_res.nhev = func_wrapper.nhev
+ optimize_res.message = message
+ return optimize_res
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_elementwise.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e756a3f9659961c71d6864b2ed6477c2f28e7a7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_elementwise.py
@@ -0,0 +1,826 @@
+from scipy.optimize._bracket import _bracket_root, _bracket_minimum
+from scipy.optimize._chandrupatla import _chandrupatla, _chandrupatla_minimize
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import xp_capabilities
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.')])
+def find_root(f, init, /, *, args=(), kwargs=None,
+ tolerances=None, maxiter=None, callback=None):
+ """Find the root of a monotonic, real-valued function of a real variable.
+
+ For each element of the output of `f`, `find_root` seeks the scalar
+ root that makes the element 0. This function currently uses Chandrupatla's
+ bracketing algorithm [1]_ and therefore requires argument `init` to
+ provide a bracket around the root: the function values at the two endpoints
+ must have opposite signs.
+
+ Provided a valid bracket, `find_root` is guaranteed to converge to a solution
+ that satisfies the provided `tolerances` if the function is continuous within
+ the bracket.
+
+ This function works elementwise when `init` and `args` contain (broadcastable)
+ arrays.
+
+ Parameters
+ ----------
+ f : callable
+ The function whose root is desired. The signature must be::
+
+ f(x: array, *args) -> array
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with ``x``.
+
+ `f` must be an elementwise function: each element ``f(x)[i]``
+ must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+ array ``x`` or the arrays in ``args``.
+
+ `find_root` seeks an array ``x`` such that ``f(x)`` is an array of zeros.
+ init : 2-tuple of float array_like
+ The lower and upper endpoints of a bracket surrounding the desired root.
+ A bracket is valid if arrays ``xl, xr = init`` satisfy ``xl < xr`` and
+ ``sign(f(xl)) == -sign(f(xr))`` elementwise. Arrays be broadcastable with
+ one another and `args`.
+ args : tuple of array_like, optional
+ Additional positional array arguments to be passed to `f`. Arrays
+ must be broadcastable with one another and the arrays of `init`.
+ If the callable for which the root is desired requires arguments that are
+ not broadcastable with `x`, wrap that callable with `f` such that `f`
+ accepts only `x` and broadcastable ``*args``.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `f`. See `args`.
+ tolerances : dictionary of floats, optional
+ Absolute and relative tolerances on the root and function value.
+ Valid keys of the dictionary are:
+
+ - ``xatol`` - absolute tolerance on the root
+ - ``xrtol`` - relative tolerance on the root
+ - ``fatol`` - absolute tolerance on the function value
+ - ``frtol`` - relative tolerance on the function value
+
+ See Notes for default values and explicit termination conditions.
+ maxiter : int, optional
+ The maximum number of iterations of the algorithm to perform.
+ The default is the maximum possible number of bisections within
+ the (normal) floating point numbers of the relevant dtype.
+ callback : callable, optional
+ An optional user-supplied function to be called before the first
+ iteration and after each iteration.
+ Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+ similar to that returned by `find_root` (but containing the current
+ iterate's values of all variables). If `callback` raises a
+ ``StopIteration``, the algorithm will terminate immediately and
+ `find_root` will return a result. `callback` must not mutate
+ `res` or its attributes.
+
+ Returns
+ -------
+ res : _RichResult
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+ following attributes. The descriptions are written as though the values will
+ be scalars; however, if `f` returns an array, the outputs will be
+ arrays of the same shape.
+
+ success : bool array
+ ``True`` where the algorithm terminated successfully (status ``0``);
+ ``False`` otherwise.
+ status : int array
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm converged to the specified tolerances.
+ - ``-1`` : The initial bracket was invalid.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : Iteration was terminated by `callback`.
+ - ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+ x : float array
+ The root of the function, if the algorithm terminated successfully.
+ f_x : float array
+ The value of `f` evaluated at `x`.
+ nfev : int array
+ The number of abscissae at which `f` was evaluated to find the root.
+ This is distinct from the number of times `f` is *called* because the
+ the function may evaluated at multiple points in a single call.
+ nit : int array
+ The number of iterations of the algorithm that were performed.
+ bracket : tuple of float arrays
+ The lower and upper endpoints of the final bracket.
+ f_bracket : tuple of float arrays
+ The value of `f` evaluated at the lower and upper endpoints of the
+ bracket.
+
+ Notes
+ -----
+ Implemented based on Chandrupatla's original paper [1]_.
+
+ Let:
+
+ - ``a, b = init`` be the left and right endpoints of the initial bracket,
+ - ``xl`` and ``xr`` be the left and right endpoints of the final bracket,
+ - ``xmin = xl if abs(f(xl)) <= abs(f(xr)) else xr`` be the final bracket
+ endpoint with the smaller function value, and
+ - ``fmin0 = min(f(a), f(b))`` be the minimum of the two values of the
+ function evaluated at the initial bracket endpoints.
+
+ Then the algorithm is considered to have converged when
+
+ - ``abs(xr - xl) < xatol + abs(xmin) * xrtol`` or
+ - ``fun(xmin) <= fatol + abs(fmin0) * frtol``.
+
+ This is equivalent to the termination condition described in [1]_ with
+ ``xrtol = 4e-10``, ``xatol = 1e-5``, and ``fatol = frtol = 0``.
+ However, the default values of the `tolerances` dictionary are
+ ``xatol = 4*tiny``, ``xrtol = 4*eps``, ``frtol = 0``, and ``fatol = tiny``,
+ where ``eps`` and ``tiny`` are the precision and smallest normal number
+ of the result ``dtype`` of function inputs and outputs.
+
+ References
+ ----------
+
+ .. [1] Chandrupatla, Tirupathi R.
+ "A new hybrid quadratic/bisection algorithm for finding the zero of a
+ nonlinear function without using derivatives".
+ Advances in Engineering Software, 28(3), 145-149.
+ :doi:`10.1016/s0965-9978(96)00051-8`.
+
+ See Also
+ --------
+ bracket_root
+
+ Examples
+ --------
+ Suppose we wish to find the root of the following function.
+
+ >>> def f(x, c=5):
+ ... return x**3 - 2*x - c
+
+ First, we must find a valid bracket. The function is not monotonic,
+ but `bracket_root` may be able to provide a bracket.
+
+ >>> from scipy.optimize import elementwise
+ >>> res_bracket = elementwise.bracket_root(f, 0)
+ >>> res_bracket.success
+ True
+ >>> res_bracket.bracket
+ (2.0, 4.0)
+
+ Indeed, the values of the function at the bracket endpoints have
+ opposite signs.
+
+ >>> res_bracket.f_bracket
+ (-1.0, 51.0)
+
+ Once we have a valid bracket, `find_root` can be used to provide
+ a precise root.
+
+ >>> res_root = elementwise.find_root(f, res_bracket.bracket)
+ >>> res_root.x
+ 2.0945514815423265
+
+ The final bracket is only a few ULPs wide, so the error between
+ this value and the true root cannot be much smaller within values
+ that are representable in double precision arithmetic.
+
+ >>> import numpy as np
+ >>> xl, xr = res_root.bracket
+ >>> (xr - xl) / np.spacing(xl)
+ 2.0
+ >>> res_root.f_bracket
+ (-8.881784197001252e-16, 9.769962616701378e-15)
+
+ `bracket_root` and `find_root` accept arrays for most arguments.
+ For instance, to find the root for a few values of the parameter ``c``
+ at once:
+
+ >>> c = np.asarray([3, 4, 5])
+ >>> res_bracket = elementwise.bracket_root(f, 0, args=(c,))
+ >>> res_bracket.bracket
+ (array([1., 1., 2.]), array([2., 2., 4.]))
+ >>> res_root = elementwise.find_root(f, res_bracket.bracket, args=(c,))
+ >>> res_root.x
+ array([1.8932892 , 2. , 2.09455148])
+
+ """
+
+ def reformat_result(res_in):
+ res_out = _RichResult()
+ res_out.status = res_in.status
+ res_out.success = res_in.success
+ res_out.x = res_in.x
+ res_out.f_x = res_in.fun
+ res_out.nfev = res_in.nfev
+ res_out.nit = res_in.nit
+ res_out.bracket = (res_in.xl, res_in.xr)
+ res_out.f_bracket = (res_in.fl, res_in.fr)
+ res_out._order_keys = ['success', 'status', 'x', 'f_x',
+ 'nfev', 'nit', 'bracket', 'f_bracket']
+ return res_out
+
+ xl, xr = init
+ default_tolerances = dict(xatol=None, xrtol=None, fatol=None, frtol=0)
+ tolerances = {} if tolerances is None else tolerances
+ default_tolerances.update(tolerances)
+ tolerances = default_tolerances
+
+ if callable(callback):
+ def _callback(res):
+ return callback(reformat_result(res))
+ else:
+ _callback = callback
+
+ res = _chandrupatla(f, xl, xr, args=args, kwargs=kwargs, **tolerances,
+ maxiter=maxiter, callback=_callback)
+ return reformat_result(res)
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.')])
+def find_minimum(f, init, /, *, args=(), kwargs=None,
+ tolerances=None, maxiter=100, callback=None):
+ """Find the minimum of a unimodal, real-valued function of a real variable.
+
+ For each element of the output of `f`, `find_minimum` seeks the scalar minimizer
+ that minimizes the element. This function currently uses Chandrupatla's
+ bracketing minimization algorithm [1]_ and therefore requires argument `init`
+ to provide a three-point minimization bracket: ``x1 < x2 < x3`` such that
+ ``func(x1) >= func(x2) <= func(x3)``, where one of the inequalities is strict.
+
+ Provided a valid bracket, `find_minimum` is guaranteed to converge to a local
+ minimum that satisfies the provided `tolerances` if the function is continuous
+ within the bracket.
+
+ This function works elementwise when `init` and `args` contain (broadcastable)
+ arrays.
+
+ Parameters
+ ----------
+ f : callable
+ The function whose minimizer is desired. The signature must be::
+
+ f(x: array, *args) -> array
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with ``x``.
+
+ `f` must be an elementwise function: each element ``f(x)[i]``
+ must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+ array ``x`` or the arrays in ``args``.
+
+ `find_minimum` seeks an array ``x`` such that ``f(x)`` is an array of
+ local minima.
+ init : 3-tuple of float array_like
+ The abscissae of a standard scalar minimization bracket. A bracket is
+ valid if arrays ``x1, x2, x3 = init`` satisfy ``x1 < x2 < x3`` and
+ ``func(x1) >= func(x2) <= func(x3)``, where one of the inequalities
+ is strict. Arrays must be broadcastable with one another and the arrays
+ of `args`.
+ args : tuple of array_like, optional
+ Additional positional array arguments to be passed to `f`. Arrays
+ must be broadcastable with one another and the arrays of `init`.
+ If the callable for which the root is desired requires arguments that are
+ not broadcastable with `x`, wrap that callable with `f` such that `f`
+ accepts only `x` and broadcastable ``*args``.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `f`. See `args`.
+ tolerances : dictionary of floats, optional
+ Absolute and relative tolerances on the root and function value.
+ Valid keys of the dictionary are:
+
+ - ``xatol`` - absolute tolerance on the root
+ - ``xrtol`` - relative tolerance on the root
+ - ``fatol`` - absolute tolerance on the function value
+ - ``frtol`` - relative tolerance on the function value
+
+ See Notes for default values and explicit termination conditions.
+ maxiter : int, default: 100
+ The maximum number of iterations of the algorithm to perform.
+ callback : callable, optional
+ An optional user-supplied function to be called before the first
+ iteration and after each iteration.
+ Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+ similar to that returned by `find_minimum` (but containing the current
+ iterate's values of all variables). If `callback` raises a
+ ``StopIteration``, the algorithm will terminate immediately and
+ `find_root` will return a result. `callback` must not mutate
+ `res` or its attributes.
+
+ Returns
+ -------
+ res : _RichResult
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+ following attributes. The descriptions are written as though the values will
+ be scalars; however, if `f` returns an array, the outputs will be
+ arrays of the same shape.
+
+ success : bool array
+ ``True`` where the algorithm terminated successfully (status ``0``);
+ ``False`` otherwise.
+ status : int array
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm converged to the specified tolerances.
+ - ``-1`` : The algorithm encountered an invalid bracket.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : Iteration was terminated by `callback`.
+ - ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+ x : float array
+ The minimizer of the function, if the algorithm terminated successfully.
+ f_x : float array
+ The value of `f` evaluated at `x`.
+ nfev : int array
+ The number of abscissae at which `f` was evaluated to find the root.
+ This is distinct from the number of times `f` is *called* because the
+ the function may evaluated at multiple points in a single call.
+ nit : int array
+ The number of iterations of the algorithm that were performed.
+ bracket : tuple of float arrays
+ The final three-point bracket.
+ f_bracket : tuple of float arrays
+ The value of `f` evaluated at the bracket points.
+
+ Notes
+ -----
+ Implemented based on Chandrupatla's original paper [1]_.
+
+ If ``xl < xm < xr`` are the points of the bracket and ``fl >= fm <= fr``
+ (where one of the inequalities is strict) are the values of `f` evaluated
+ at those points, then the algorithm is considered to have converged when:
+
+ - ``abs(xr - xm)/2 <= abs(xm)*xrtol + xatol`` or
+ - ``(fl - 2*fm + fr)/2 <= abs(fm)*frtol + fatol``.
+
+ The default value of `xrtol` is the square root of the precision of the
+ appropriate dtype, and ``xatol = fatol = frtol`` is the smallest normal
+ number of the appropriate dtype.
+
+ References
+ ----------
+
+ .. [1] Chandrupatla, Tirupathi R. (1998).
+ "An efficient quadratic fit-sectioning algorithm for minimization
+ without derivatives".
+ Computer Methods in Applied Mechanics and Engineering, 152 (1-2),
+ 211-217. :doi:`10.1016/S0045-7825(97)00190-4`.
+
+ See Also
+ --------
+ bracket_minimum
+
+ Examples
+ --------
+ Suppose we wish to minimize the following function.
+
+ >>> def f(x, c=1):
+ ... return (x - c)**2 + 2
+
+ First, we must find a valid bracket. The function is unimodal,
+ so `bracket_minium` will easily find a bracket.
+
+ >>> from scipy.optimize import elementwise
+ >>> res_bracket = elementwise.bracket_minimum(f, 0)
+ >>> res_bracket.success
+ True
+ >>> res_bracket.bracket
+ (0.0, 0.5, 1.5)
+
+ Indeed, the bracket points are ordered and the function value
+ at the middle bracket point is less than at the surrounding
+ points.
+
+ >>> xl, xm, xr = res_bracket.bracket
+ >>> fl, fm, fr = res_bracket.f_bracket
+ >>> (xl < xm < xr) and (fl > fm <= fr)
+ True
+
+ Once we have a valid bracket, `find_minimum` can be used to provide
+ an estimate of the minimizer.
+
+ >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket)
+ >>> res_minimum.x
+ 1.0000000149011612
+
+ The function value changes by only a few ULPs within the bracket, so
+ the minimizer cannot be determined much more precisely by evaluating
+ the function alone (i.e. we would need its derivative to do better).
+
+ >>> import numpy as np
+ >>> fl, fm, fr = res_minimum.f_bracket
+ >>> (fl - fm) / np.spacing(fm), (fr - fm) / np.spacing(fm)
+ (0.0, 2.0)
+
+ Therefore, a precise minimum of the function is given by:
+
+ >>> res_minimum.f_x
+ 2.0
+
+ `bracket_minimum` and `find_minimum` accept arrays for most arguments.
+ For instance, to find the minimizers and minima for a few values of the
+ parameter ``c`` at once:
+
+ >>> c = np.asarray([1, 1.5, 2])
+ >>> res_bracket = elementwise.bracket_minimum(f, 0, args=(c,))
+ >>> res_bracket.bracket
+ (array([0. , 0.5, 0.5]), array([0.5, 1.5, 1.5]), array([1.5, 2.5, 2.5]))
+ >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket, args=(c,))
+ >>> res_minimum.x
+ array([1.00000001, 1.5 , 2. ])
+ >>> res_minimum.f_x
+ array([2., 2., 2.])
+
+ """
+
+ def reformat_result(res_in):
+ res_out = _RichResult()
+ res_out.status = res_in.status
+ res_out.success = res_in.success
+ res_out.x = res_in.x
+ res_out.f_x = res_in.fun
+ res_out.nfev = res_in.nfev
+ res_out.nit = res_in.nit
+ res_out.bracket = (res_in.xl, res_in.xm, res_in.xr)
+ res_out.f_bracket = (res_in.fl, res_in.fm, res_in.fr)
+ res_out._order_keys = ['success', 'status', 'x', 'f_x',
+ 'nfev', 'nit', 'bracket', 'f_bracket']
+ return res_out
+
+ xl, xm, xr = init
+ default_tolerances = dict(xatol=None, xrtol=None, fatol=None, frtol=None)
+ tolerances = {} if tolerances is None else tolerances
+ default_tolerances.update(tolerances)
+ tolerances = default_tolerances
+
+ if callable(callback):
+ def _callback(res):
+ return callback(reformat_result(res))
+ else:
+ _callback = callback
+
+ res = _chandrupatla_minimize(f, xl, xm, xr, args=args, kwargs=kwargs, **tolerances,
+ maxiter=maxiter, callback=_callback)
+ return reformat_result(res)
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.')])
+def bracket_root(f, xl0, xr0=None, *, xmin=None, xmax=None, factor=None,
+ args=(), kwargs=None, maxiter=1000):
+ """Bracket the root of a monotonic, real-valued function of a real variable.
+
+ For each element of the output of `f`, `bracket_root` seeks the scalar
+ bracket endpoints ``xl`` and ``xr`` such that ``sign(f(xl)) == -sign(f(xr))``
+ elementwise.
+
+ The function is guaranteed to find a valid bracket if the function is monotonic,
+ but it may find a bracket under other conditions.
+
+ This function works elementwise when `xl0`, `xr0`, `xmin`, `xmax`, `factor`, and
+ the elements of `args` are (mutually broadcastable) arrays.
+
+ Parameters
+ ----------
+ f : callable
+ The function for which the root is to be bracketed. The signature must be::
+
+ f(x: array, *args) -> array
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with ``x``.
+
+ `f` must be an elementwise function: each element ``f(x)[i]``
+ must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+ array ``x`` or the arrays in ``args``.
+ xl0, xr0 : float array_like
+ Starting guess of bracket, which need not contain a root. If `xr0` is
+ not provided, ``xr0 = xl0 + 1``. Must be broadcastable with all other
+ array inputs.
+ xmin, xmax : float array_like, optional
+ Minimum and maximum allowable endpoints of the bracket, inclusive. Must
+ be broadcastable with all other array inputs.
+ factor : float array_like, default: 2
+ The factor used to grow the bracket. See Notes.
+ args : tuple of array_like, optional
+ Additional positional array arguments to be passed to `f`.
+ If the callable for which the root is desired requires arguments that are
+ not broadcastable with `x`, wrap that callable with `f` such that `f`
+ accepts only `x` and broadcastable ``*args``.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `f`. See `args`.
+ maxiter : int, default: 1000
+ The maximum number of iterations of the algorithm to perform.
+
+ Returns
+ -------
+ res : _RichResult
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+ following attributes. The descriptions are written as though the values will
+ be scalars; however, if `f` returns an array, the outputs will be
+ arrays of the same shape.
+
+ success : bool array
+ ``True`` where the algorithm terminated successfully (status ``0``);
+ ``False`` otherwise.
+ status : int array
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm produced a valid bracket.
+ - ``-1`` : The bracket expanded to the allowable limits without success.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : Iteration was terminated by `callback`.
+ - ``-5``: The initial bracket does not satisfy`xmin <= xl0 < xr0 < xmax`.
+
+ bracket : 2-tuple of float arrays
+ The lower and upper endpoints of the bracket, if the algorithm
+ terminated successfully.
+ f_bracket : 2-tuple of float arrays
+ The values of `f` evaluated at the endpoints of ``res.bracket``,
+ respectively.
+ nfev : int array
+ The number of abscissae at which `f` was evaluated to find the root.
+ This is distinct from the number of times `f` is *called* because the
+ the function may evaluated at multiple points in a single call.
+ nit : int array
+ The number of iterations of the algorithm that were performed.
+
+ Notes
+ -----
+ This function generalizes an algorithm found in pieces throughout the
+ `scipy.stats` codebase. The strategy is to iteratively grow the bracket `(l, r)`
+ until ``f(l) < 0 < f(r)`` or ``f(r) < 0 < f(l)``. The bracket grows to the left
+ as follows.
+
+ - If `xmin` is not provided, the distance between `xl0` and `l` is iteratively
+ increased by `factor`.
+ - If `xmin` is provided, the distance between `xmin` and `l` is iteratively
+ decreased by `factor`. Note that this also *increases* the bracket size.
+
+ Growth of the bracket to the right is analogous.
+
+ Growth of the bracket in one direction stops when the endpoint is no longer
+ finite, the function value at the endpoint is no longer finite, or the
+ endpoint reaches its limiting value (`xmin` or `xmax`). Iteration terminates
+ when the bracket stops growing in both directions, the bracket surrounds
+ the root, or a root is found (by chance).
+
+ If two brackets are found - that is, a bracket is found on both sides in
+ the same iteration, the smaller of the two is returned.
+
+ If roots of the function are found, both `xl` and `xr` are set to the
+ leftmost root.
+
+ See Also
+ --------
+ find_root
+
+ Examples
+ --------
+ Suppose we wish to find the root of the following function.
+
+ >>> def f(x, c=5):
+ ... return x**3 - 2*x - c
+
+ First, we must find a valid bracket. The function is not monotonic,
+ but `bracket_root` may be able to provide a bracket.
+
+ >>> from scipy.optimize import elementwise
+ >>> res_bracket = elementwise.bracket_root(f, 0)
+ >>> res_bracket.success
+ True
+ >>> res_bracket.bracket
+ (2.0, 4.0)
+
+ Indeed, the values of the function at the bracket endpoints have
+ opposite signs.
+
+ >>> res_bracket.f_bracket
+ (-1.0, 51.0)
+
+ Once we have a valid bracket, `find_root` can be used to provide
+ a precise root.
+
+ >>> res_root = elementwise.find_root(f, res_bracket.bracket)
+ >>> res_root.x
+ 2.0945514815423265
+
+ `bracket_root` and `find_root` accept arrays for most arguments.
+ For instance, to find the root for a few values of the parameter ``c``
+ at once:
+
+ >>> import numpy as np
+ >>> c = np.asarray([3, 4, 5])
+ >>> res_bracket = elementwise.bracket_root(f, 0, args=(c,))
+ >>> res_bracket.bracket
+ (array([1., 1., 2.]), array([2., 2., 4.]))
+ >>> res_root = elementwise.find_root(f, res_bracket.bracket, args=(c,))
+ >>> res_root.x
+ array([1.8932892 , 2. , 2.09455148])
+
+ """ # noqa: E501
+
+ res = _bracket_root(f, xl0, xr0=xr0, xmin=xmin, xmax=xmax, factor=factor,
+ args=args, kwargs=kwargs, maxiter=maxiter)
+ res.bracket = res.xl, res.xr
+ res.f_bracket = res.fl, res.fr
+ del res.xl
+ del res.xr
+ del res.fl
+ del res.fr
+ return res
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.'),
+ ('torch', 'data-apis/array-api-compat#271')])
+def bracket_minimum(f, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None,
+ factor=None, args=(), kwargs=None, maxiter=1000):
+ """Bracket the minimum of a unimodal, real-valued function of a real variable.
+
+ For each element of the output of `f`, `bracket_minimum` seeks the scalar
+ bracket points ``xl < xm < xr`` such that ``fl >= fm <= fr`` where one of the
+ inequalities is strict.
+
+ The function is guaranteed to find a valid bracket if the function is
+ strongly unimodal, but it may find a bracket under other conditions.
+
+ This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`, `factor`,
+ and the elements of `args` are (mutually broadcastable) arrays.
+
+ Parameters
+ ----------
+ f : callable
+ The function for which the root is to be bracketed. The signature must be::
+
+ f(x: array, *args) -> array
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with ``x``.
+
+ `f` must be an elementwise function: each element ``f(x)[i]``
+ must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+ array ``x`` or the arrays in ``args``.
+ xm0 : float array_like
+ Starting guess for middle point of bracket.
+ xl0, xr0 : float array_like, optional
+ Starting guesses for left and right endpoints of the bracket. Must
+ be broadcastable with all other array inputs.
+ xmin, xmax : float array_like, optional
+ Minimum and maximum allowable endpoints of the bracket, inclusive. Must
+ be broadcastable with all other array inputs.
+ factor : float array_like, default: 2
+ The factor used to grow the bracket. See Notes.
+ args : tuple of array_like, optional
+ Additional positional array arguments to be passed to `f`.
+ If the callable for which the root is desired requires arguments that are
+ not broadcastable with `x`, wrap that callable with `f` such that `f`
+ accepts only `x` and broadcastable ``*args``.
+ kwargs : dict of str:array_like, optional
+ Additional keyword arguments to be passed to `f`. See `args`.
+ maxiter : int, default: 1000
+ The maximum number of iterations of the algorithm to perform.
+
+ Returns
+ -------
+ res : _RichResult
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+ following attributes. The descriptions are written as though the values will
+ be scalars; however, if `f` returns an array, the outputs will be
+ arrays of the same shape.
+
+ success : bool array
+ ``True`` where the algorithm terminated successfully (status ``0``);
+ ``False`` otherwise.
+ status : int array
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm produced a valid bracket.
+ - ``-1`` : The bracket expanded to the allowable limits. Assuming
+ unimodality, this implies the endpoint at the limit is a minimizer.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : ``None`` shall pass.
+ - ``-5`` : The initial bracket does not satisfy
+ `xmin <= xl0 < xm0 < xr0 <= xmax`.
+
+ bracket : 3-tuple of float arrays
+ The left, middle, and right points of the bracket, if the algorithm
+ terminated successfully.
+ f_bracket : 3-tuple of float arrays
+ The function value at the left, middle, and right points of the bracket.
+ nfev : int array
+ The number of abscissae at which `f` was evaluated to find the root.
+ This is distinct from the number of times `f` is *called* because the
+ the function may evaluated at multiple points in a single call.
+ nit : int array
+ The number of iterations of the algorithm that were performed.
+
+ Notes
+ -----
+ Similar to `scipy.optimize.bracket`, this function seeks to find real
+ points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``,
+ where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`,
+ this function can operate in a vectorized manner on array input, so long as
+ the input arrays are broadcastable with each other. Also unlike
+ `scipy.optimize.bracket`, users may specify minimum and maximum endpoints
+ for the desired bracket.
+
+ Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``,
+ the algorithm checks if these points already give a valid bracket. If not,
+ a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new
+ opposite endpoint, and either `xl` or `xr` becomes the new middle point,
+ depending on which direction is downhill. The algorithm repeats from here.
+
+ The new endpoint `w` is chosen differently depending on whether or not a
+ boundary `xmin` or `xmax` has been set in the downhill direction. Without
+ loss of generality, suppose the downhill direction is to the right, so that
+ ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w`
+ is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by
+ the user (defaults to 2.0) so that step sizes increase in geometric proportion.
+ If there is a boundary, `xmax` in this case, then `w` is chosen to be
+ ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at
+ `xmax`. This cautious approach ensures that a minimum near but distinct from
+ the boundary isn't missed while also detecting whether or not the `xmax` is
+ a minimizer when `xmax` is reached after a finite number of steps.
+
+ See Also
+ --------
+ scipy.optimize.bracket
+ scipy.optimize.elementwise.find_minimum
+
+ Examples
+ --------
+ Suppose we wish to minimize the following function.
+
+ >>> def f(x, c=1):
+ ... return (x - c)**2 + 2
+
+ First, we must find a valid bracket. The function is unimodal,
+ so `bracket_minium` will easily find a bracket.
+
+ >>> from scipy.optimize import elementwise
+ >>> res_bracket = elementwise.bracket_minimum(f, 0)
+ >>> res_bracket.success
+ True
+ >>> res_bracket.bracket
+ (0.0, 0.5, 1.5)
+
+ Indeed, the bracket points are ordered and the function value
+ at the middle bracket point is less than at the surrounding
+ points.
+
+ >>> xl, xm, xr = res_bracket.bracket
+ >>> fl, fm, fr = res_bracket.f_bracket
+ >>> (xl < xm < xr) and (fl > fm <= fr)
+ True
+
+ Once we have a valid bracket, `find_minimum` can be used to provide
+ an estimate of the minimizer.
+
+ >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket)
+ >>> res_minimum.x
+ 1.0000000149011612
+
+ `bracket_minimum` and `find_minimum` accept arrays for most arguments.
+ For instance, to find the minimizers and minima for a few values of the
+ parameter ``c`` at once:
+
+ >>> import numpy as np
+ >>> c = np.asarray([1, 1.5, 2])
+ >>> res_bracket = elementwise.bracket_minimum(f, 0, args=(c,))
+ >>> res_bracket.bracket
+ (array([0. , 0.5, 0.5]), array([0.5, 1.5, 1.5]), array([1.5, 2.5, 2.5]))
+ >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket, args=(c,))
+ >>> res_minimum.x
+ array([1.00000001, 1.5 , 2. ])
+ >>> res_minimum.f_x
+ array([2., 2., 2.])
+
+ """ # noqa: E501
+
+ res = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax,
+ factor=factor, args=args, kwargs=kwargs, maxiter=maxiter)
+ res.bracket = res.xl, res.xm, res.xr
+ res.f_bracket = res.fl, res.fm, res.fr
+ del res.xl
+ del res.xm
+ del res.xr
+ del res.fl
+ del res.fm
+ del res.fr
+ return res
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_group_columns.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_group_columns.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..57ac7be21f3f66f1c3ad7f854ddd6ff6654ccfd5
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/optimize/_group_columns.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_hessian_update_strategy.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..15989969349025fd42fba9836b4f5d882c3f6791
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_hessian_update_strategy.py
@@ -0,0 +1,479 @@
+"""Hessian update strategies for quasi-Newton optimization methods."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.linalg import get_blas_funcs, issymmetric
+from warnings import warn
+
+
+__all__ = ['HessianUpdateStrategy', 'BFGS', 'SR1']
+
+
+class HessianUpdateStrategy:
+ """Interface for implementing Hessian update strategies.
+
+ Many optimization methods make use of Hessian (or inverse Hessian)
+ approximations, such as the quasi-Newton methods BFGS, SR1, L-BFGS.
+ Some of these approximations, however, do not actually need to store
+ the entire matrix or can compute the internal matrix product with a
+ given vector in a very efficiently manner. This class serves as an
+ abstract interface between the optimization algorithm and the
+ quasi-Newton update strategies, giving freedom of implementation
+ to store and update the internal matrix as efficiently as possible.
+ Different choices of initialization and update procedure will result
+ in different quasi-Newton strategies.
+
+ Four methods should be implemented in derived classes: ``initialize``,
+ ``update``, ``dot`` and ``get_matrix``. The matrix multiplication
+ operator ``@`` is also defined to call the ``dot`` method.
+
+ Notes
+ -----
+ Any instance of a class that implements this interface,
+ can be accepted by the method ``minimize`` and used by
+ the compatible solvers to approximate the Hessian (or
+ inverse Hessian) used by the optimization algorithms.
+ """
+
+ def initialize(self, n, approx_type):
+ """Initialize internal matrix.
+
+ Allocate internal memory for storing and updating
+ the Hessian or its inverse.
+
+ Parameters
+ ----------
+ n : int
+ Problem dimension.
+ approx_type : {'hess', 'inv_hess'}
+ Selects either the Hessian or the inverse Hessian.
+ When set to 'hess' the Hessian will be stored and updated.
+ When set to 'inv_hess' its inverse will be used instead.
+ """
+ raise NotImplementedError("The method ``initialize(n, approx_type)``"
+ " is not implemented.")
+
+ def update(self, delta_x, delta_grad):
+ """Update internal matrix.
+
+ Update Hessian matrix or its inverse (depending on how 'approx_type'
+ is defined) using information about the last evaluated points.
+
+ Parameters
+ ----------
+ delta_x : ndarray
+ The difference between two points the gradient
+ function have been evaluated at: ``delta_x = x2 - x1``.
+ delta_grad : ndarray
+ The difference between the gradients:
+ ``delta_grad = grad(x2) - grad(x1)``.
+ """
+ raise NotImplementedError("The method ``update(delta_x, delta_grad)``"
+ " is not implemented.")
+
+ def dot(self, p):
+ """Compute the product of the internal matrix with the given vector.
+
+ Parameters
+ ----------
+ p : array_like
+ 1-D array representing a vector.
+
+ Returns
+ -------
+ Hp : array
+ 1-D represents the result of multiplying the approximation matrix
+ by vector p.
+ """
+ raise NotImplementedError("The method ``dot(p)``"
+ " is not implemented.")
+
+ def get_matrix(self):
+ """Return current internal matrix.
+
+ Returns
+ -------
+ H : ndarray, shape (n, n)
+ Dense matrix containing either the Hessian
+ or its inverse (depending on how 'approx_type'
+ is defined).
+ """
+ raise NotImplementedError("The method ``get_matrix(p)``"
+ " is not implemented.")
+
+ def __matmul__(self, p):
+ return self.dot(p)
+
+
+class FullHessianUpdateStrategy(HessianUpdateStrategy):
+ """Hessian update strategy with full dimensional internal representation.
+ """
+ _syr = get_blas_funcs('syr', dtype='d') # Symmetric rank 1 update
+ _syr2 = get_blas_funcs('syr2', dtype='d') # Symmetric rank 2 update
+ # Symmetric matrix-vector product
+ _symv = get_blas_funcs('symv', dtype='d')
+
+ def __init__(self, init_scale='auto'):
+ self.init_scale = init_scale
+ # Until initialize is called we can't really use the class,
+ # so it makes sense to set everything to None.
+ self.first_iteration = None
+ self.approx_type = None
+ self.B = None
+ self.H = None
+
+ def initialize(self, n, approx_type):
+ """Initialize internal matrix.
+
+ Allocate internal memory for storing and updating
+ the Hessian or its inverse.
+
+ Parameters
+ ----------
+ n : int
+ Problem dimension.
+ approx_type : {'hess', 'inv_hess'}
+ Selects either the Hessian or the inverse Hessian.
+ When set to 'hess' the Hessian will be stored and updated.
+ When set to 'inv_hess' its inverse will be used instead.
+ """
+ self.first_iteration = True
+ self.n = n
+ self.approx_type = approx_type
+ if approx_type not in ('hess', 'inv_hess'):
+ raise ValueError("`approx_type` must be 'hess' or 'inv_hess'.")
+ # Create matrix
+ if self.approx_type == 'hess':
+ self.B = np.eye(n, dtype=float)
+ else:
+ self.H = np.eye(n, dtype=float)
+
+ def _auto_scale(self, delta_x, delta_grad):
+ # Heuristic to scale matrix at first iteration.
+ # Described in Nocedal and Wright "Numerical Optimization"
+ # p.143 formula (6.20).
+ s_norm2 = np.dot(delta_x, delta_x)
+ y_norm2 = np.dot(delta_grad, delta_grad)
+ ys = np.abs(np.dot(delta_grad, delta_x))
+ if ys == 0.0 or y_norm2 == 0 or s_norm2 == 0:
+ return 1
+ if self.approx_type == 'hess':
+ return y_norm2 / ys
+ else:
+ return ys / y_norm2
+
+ def _update_implementation(self, delta_x, delta_grad):
+ raise NotImplementedError("The method ``_update_implementation``"
+ " is not implemented.")
+
+ def update(self, delta_x, delta_grad):
+ """Update internal matrix.
+
+ Update Hessian matrix or its inverse (depending on how 'approx_type'
+ is defined) using information about the last evaluated points.
+
+ Parameters
+ ----------
+ delta_x : ndarray
+ The difference between two points the gradient
+ function have been evaluated at: ``delta_x = x2 - x1``.
+ delta_grad : ndarray
+ The difference between the gradients:
+ ``delta_grad = grad(x2) - grad(x1)``.
+ """
+ if np.all(delta_x == 0.0):
+ return
+ if np.all(delta_grad == 0.0):
+ warn('delta_grad == 0.0. Check if the approximated '
+ 'function is linear. If the function is linear '
+ 'better results can be obtained by defining the '
+ 'Hessian as zero instead of using quasi-Newton '
+ 'approximations.',
+ UserWarning, stacklevel=2)
+ return
+ if self.first_iteration:
+ # Get user specific scale
+ if isinstance(self.init_scale, str) and self.init_scale == "auto":
+ scale = self._auto_scale(delta_x, delta_grad)
+ else:
+ scale = self.init_scale
+
+ # Check for complex: numpy will silently cast a complex array to
+ # a real one but not so for scalar as it raises a TypeError.
+ # Checking here brings a consistent behavior.
+ replace = False
+ if np.size(scale) == 1:
+ # to account for the legacy behavior having the exact same cast
+ scale = float(scale)
+ elif np.iscomplexobj(scale):
+ raise TypeError("init_scale contains complex elements, "
+ "must be real.")
+ else: # test explicitly for allowed shapes and values
+ replace = True
+ if self.approx_type == 'hess':
+ shape = np.shape(self.B)
+ dtype = self.B.dtype
+ else:
+ shape = np.shape(self.H)
+ dtype = self.H.dtype
+ # copy, will replace the original
+ scale = np.array(scale, dtype=dtype, copy=True)
+
+ # it has to match the shape of the matrix for the multiplication,
+ # no implicit broadcasting is allowed
+ if shape != (init_shape := np.shape(scale)):
+ raise ValueError("If init_scale is an array, it must have the "
+ f"dimensions of the hess/inv_hess: {shape}."
+ f" Got {init_shape}.")
+ if not issymmetric(scale):
+ raise ValueError("If init_scale is an array, it must be"
+ " symmetric (passing scipy.linalg.issymmetric)"
+ " to be an approximation of a hess/inv_hess.")
+
+ # Scale initial matrix with ``scale * np.eye(n)`` or replace
+ # This is not ideal, we could assign the scale directly in
+ # initialize, but we would need to
+ if self.approx_type == 'hess':
+ if replace:
+ self.B = scale
+ else:
+ self.B *= scale
+ else:
+ if replace:
+ self.H = scale
+ else:
+ self.H *= scale
+ self.first_iteration = False
+ self._update_implementation(delta_x, delta_grad)
+
+ def dot(self, p):
+ """Compute the product of the internal matrix with the given vector.
+
+ Parameters
+ ----------
+ p : array_like
+ 1-D array representing a vector.
+
+ Returns
+ -------
+ Hp : array
+ 1-D represents the result of multiplying the approximation matrix
+ by vector p.
+ """
+ if self.approx_type == 'hess':
+ return self._symv(1, self.B, p)
+ else:
+ return self._symv(1, self.H, p)
+
+ def get_matrix(self):
+ """Return the current internal matrix.
+
+ Returns
+ -------
+ M : ndarray, shape (n, n)
+ Dense matrix containing either the Hessian or its inverse
+ (depending on how `approx_type` was defined).
+ """
+ if self.approx_type == 'hess':
+ M = np.copy(self.B)
+ else:
+ M = np.copy(self.H)
+ li = np.tril_indices_from(M, k=-1)
+ M[li] = M.T[li]
+ return M
+
+
+class BFGS(FullHessianUpdateStrategy):
+ """Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
+
+ Parameters
+ ----------
+ exception_strategy : {'skip_update', 'damp_update'}, optional
+ Define how to proceed when the curvature condition is violated.
+ Set it to 'skip_update' to just skip the update. Or, alternatively,
+ set it to 'damp_update' to interpolate between the actual BFGS
+ result and the unmodified matrix. Both exceptions strategies
+ are explained in [1]_, p.536-537.
+ min_curvature : float
+ This number, scaled by a normalization factor, defines the
+ minimum curvature ``dot(delta_grad, delta_x)`` allowed to go
+ unaffected by the exception strategy. By default is equal to
+ 1e-8 when ``exception_strategy = 'skip_update'`` and equal
+ to 0.2 when ``exception_strategy = 'damp_update'``.
+ init_scale : {float, np.array, 'auto'}
+ This parameter can be used to initialize the Hessian or its
+ inverse. When a float is given, the relevant array is initialized
+ to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
+ Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
+ this array will be used. Otherwise an error is generated.
+ Set it to 'auto' in order to use an automatic heuristic for choosing
+ the initial scale. The heuristic is described in [1]_, p.143.
+ The default is 'auto'.
+
+ Notes
+ -----
+ The update is based on the description in [1]_, p.140.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+
+ def __init__(self, exception_strategy='skip_update', min_curvature=None,
+ init_scale='auto'):
+ if exception_strategy == 'skip_update':
+ if min_curvature is not None:
+ self.min_curvature = min_curvature
+ else:
+ self.min_curvature = 1e-8
+ elif exception_strategy == 'damp_update':
+ if min_curvature is not None:
+ self.min_curvature = min_curvature
+ else:
+ self.min_curvature = 0.2
+ else:
+ raise ValueError("`exception_strategy` must be 'skip_update' "
+ "or 'damp_update'.")
+
+ super().__init__(init_scale)
+ self.exception_strategy = exception_strategy
+
+ def _update_inverse_hessian(self, ys, Hy, yHy, s):
+ """Update the inverse Hessian matrix.
+
+ BFGS update using the formula:
+
+ ``H <- H + ((H*y).T*y + s.T*y)/(s.T*y)^2 * (s*s.T)
+ - 1/(s.T*y) * ((H*y)*s.T + s*(H*y).T)``
+
+ where ``s = delta_x`` and ``y = delta_grad``. This formula is
+ equivalent to (6.17) in [1]_ written in a more efficient way
+ for implementation.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+ self.H = self._syr2(-1.0 / ys, s, Hy, a=self.H)
+ self.H = self._syr((ys + yHy) / ys ** 2, s, a=self.H)
+
+ def _update_hessian(self, ys, Bs, sBs, y):
+ """Update the Hessian matrix.
+
+ BFGS update using the formula:
+
+ ``B <- B - (B*s)*(B*s).T/s.T*(B*s) + y*y^T/s.T*y``
+
+ where ``s`` is short for ``delta_x`` and ``y`` is short
+ for ``delta_grad``. Formula (6.19) in [1]_.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+ self.B = self._syr(1.0 / ys, y, a=self.B)
+ self.B = self._syr(-1.0 / sBs, Bs, a=self.B)
+
+ def _update_implementation(self, delta_x, delta_grad):
+ # Auxiliary variables w and z
+ if self.approx_type == 'hess':
+ w = delta_x
+ z = delta_grad
+ else:
+ w = delta_grad
+ z = delta_x
+ # Do some common operations
+ wz = np.dot(w, z)
+ Mw = self @ w
+ wMw = Mw.dot(w)
+ # Guarantee that wMw > 0 by reinitializing matrix.
+ # While this is always true in exact arithmetic,
+ # indefinite matrix may appear due to roundoff errors.
+ if wMw <= 0.0:
+ scale = self._auto_scale(delta_x, delta_grad)
+ # Reinitialize matrix
+ if self.approx_type == 'hess':
+ self.B = scale * np.eye(self.n, dtype=float)
+ else:
+ self.H = scale * np.eye(self.n, dtype=float)
+ # Do common operations for new matrix
+ Mw = self @ w
+ wMw = Mw.dot(w)
+ # Check if curvature condition is violated
+ if wz <= self.min_curvature * wMw:
+ # If the option 'skip_update' is set
+ # we just skip the update when the condition
+ # is violated.
+ if self.exception_strategy == 'skip_update':
+ return
+ # If the option 'damp_update' is set we
+ # interpolate between the actual BFGS
+ # result and the unmodified matrix.
+ elif self.exception_strategy == 'damp_update':
+ update_factor = (1-self.min_curvature) / (1 - wz/wMw)
+ z = update_factor*z + (1-update_factor)*Mw
+ wz = np.dot(w, z)
+ # Update matrix
+ if self.approx_type == 'hess':
+ self._update_hessian(wz, Mw, wMw, z)
+ else:
+ self._update_inverse_hessian(wz, Mw, wMw, z)
+
+
+class SR1(FullHessianUpdateStrategy):
+ """Symmetric-rank-1 Hessian update strategy.
+
+ Parameters
+ ----------
+ min_denominator : float
+ This number, scaled by a normalization factor,
+ defines the minimum denominator magnitude allowed
+ in the update. When the condition is violated we skip
+ the update. By default uses ``1e-8``.
+ init_scale : {float, np.array, 'auto'}, optional
+ This parameter can be used to initialize the Hessian or its
+ inverse. When a float is given, the relevant array is initialized
+ to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
+ Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
+ this array will be used. Otherwise an error is generated.
+ Set it to 'auto' in order to use an automatic heuristic for choosing
+ the initial scale. The heuristic is described in [1]_, p.143.
+ The default is 'auto'.
+
+ Notes
+ -----
+ The update is based on the description in [1]_, p.144-146.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+
+ def __init__(self, min_denominator=1e-8, init_scale='auto'):
+ self.min_denominator = min_denominator
+ super().__init__(init_scale)
+
+ def _update_implementation(self, delta_x, delta_grad):
+ # Auxiliary variables w and z
+ if self.approx_type == 'hess':
+ w = delta_x
+ z = delta_grad
+ else:
+ w = delta_grad
+ z = delta_x
+ # Do some common operations
+ Mw = self @ w
+ z_minus_Mw = z - Mw
+ denominator = np.dot(w, z_minus_Mw)
+ # If the denominator is too small
+ # we just skip the update.
+ if np.abs(denominator) <= self.min_denominator*norm(w)*norm(z_minus_Mw):
+ return
+ # Update matrix
+ if self.approx_type == 'hess':
+ self.B = self._syr(1/denominator, z_minus_Mw, a=self.B)
+ else:
+ self.H = self._syr(1/denominator, z_minus_Mw, a=self.H)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..27f548b97964e5dc83bab0c0eaa766dd0aee1ed1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:33fb5a6a86b8fb914b26e69f8f046274b0b043d202511109365d3fde180c540d
+size 6755920
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee57ee4cab0e3bcbf4e611c3c1eeaf64df319609
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:116ed72be9accceafcdeb58d5d02308e5023b9bc98118303a79d3bc24fe171d6
+size 400104
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_wrapper.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..c88f0fb14c627b10584995fbde17f3a0e445b0cf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_wrapper.py
@@ -0,0 +1,338 @@
+from warnings import warn
+
+import numpy as np
+import scipy.optimize._highspy._core as _h # type: ignore[import-not-found]
+from scipy.optimize._highspy import _highs_options as hopt # type: ignore[attr-defined]
+from scipy.optimize import OptimizeWarning
+
+
+def _highs_wrapper(c, indptr, indices, data, lhs, rhs, lb, ub, integrality, options):
+ '''Solve linear programs using HiGHS [1]_.
+
+ Assume problems of the form:
+
+ MIN c.T @ x
+ s.t. lhs <= A @ x <= rhs
+ lb <= x <= ub
+
+ Parameters
+ ----------
+ c : 1-D array, (n,)
+ Array of objective value coefficients.
+ astart : 1-D array
+ CSC format index array.
+ aindex : 1-D array
+ CSC format index array.
+ avalue : 1-D array
+ Data array of the matrix.
+ lhs : 1-D array (or None), (m,)
+ Array of left hand side values of the inequality constraints.
+ If ``lhs=None``, then an array of ``-inf`` is assumed.
+ rhs : 1-D array, (m,)
+ Array of right hand side values of the inequality constraints.
+ lb : 1-D array (or None), (n,)
+ Lower bounds on solution variables x. If ``lb=None``, then an
+ array of all `0` is assumed.
+ ub : 1-D array (or None), (n,)
+ Upper bounds on solution variables x. If ``ub=None``, then an
+ array of ``inf`` is assumed.
+ options : dict
+ A dictionary of solver options
+
+ Returns
+ -------
+ res : dict
+
+ If model_status is one of kOptimal,
+ kObjectiveBound, kTimeLimit,
+ kIterationLimit:
+
+ - ``status`` : HighsModelStatus
+ Model status code.
+
+ - ``message`` : str
+ Message corresponding to model status code.
+
+ - ``x`` : list
+ Solution variables.
+
+ - ``slack`` : list
+ Slack variables.
+
+ - ``lambda`` : list
+ Lagrange multipliers associated with the constraints
+ Ax = b.
+
+ - ``s`` : list
+ Lagrange multipliers associated with the constraints
+ x >= 0.
+
+ - ``fun``
+ Final objective value.
+
+ - ``simplex_nit`` : int
+ Number of iterations accomplished by the simplex
+ solver.
+
+ - ``ipm_nit`` : int
+ Number of iterations accomplished by the interior-
+ point solver.
+
+ If model_status is not one of the above:
+
+ - ``status`` : HighsModelStatus
+ Model status code.
+
+ - ``message`` : str
+ Message corresponding to model status code.
+
+ Notes
+ -----
+ If ``options['write_solution_to_file']`` is ``True`` but
+ ``options['solution_file']`` is unset or ``''``, then the solution
+ will be printed to ``stdout``.
+
+ If any iteration limit is reached, no solution will be
+ available.
+
+ ``OptimizeWarning`` will be raised if any option value set by
+ the user is found to be incorrect.
+
+ References
+ ----------
+ .. [1] https://highs.dev/
+ .. [2] https://www.maths.ed.ac.uk/hall/HiGHS/HighsOptions.html
+ '''
+ numcol = c.size
+ numrow = rhs.size
+ isMip = integrality is not None and np.sum(integrality) > 0
+
+ # default "null" return values
+ res = {
+ "x": None,
+ "fun": None,
+ }
+
+ # Fill up a HighsLp object
+ lp = _h.HighsLp()
+ lp.num_col_ = numcol
+ lp.num_row_ = numrow
+ lp.a_matrix_.num_col_ = numcol
+ lp.a_matrix_.num_row_ = numrow
+ lp.a_matrix_.format_ = _h.MatrixFormat.kColwise
+ lp.col_cost_ = c
+ lp.col_lower_ = lb
+ lp.col_upper_ = ub
+ lp.row_lower_ = lhs
+ lp.row_upper_ = rhs
+ lp.a_matrix_.start_ = indptr
+ lp.a_matrix_.index_ = indices
+ lp.a_matrix_.value_ = data
+ if integrality.size > 0:
+ lp.integrality_ = [_h.HighsVarType(i) for i in integrality]
+
+ # Make a Highs object and pass it everything
+ highs = _h._Highs()
+ highs_options = _h.HighsOptions()
+ hoptmanager = hopt.HighsOptionsManager()
+ for key, val in options.items():
+ # handle filtering of unsupported and default options
+ if val is None or key in ("sense",):
+ continue
+
+ # ask for the option type
+ opt_type = hoptmanager.get_option_type(key)
+ if -1 == opt_type:
+ warn(
+ f"Unrecognized options detected: {dict({key: val})}",
+ OptimizeWarning,
+ stacklevel=2,
+ )
+ continue
+ else:
+ if key in ("presolve", "parallel"):
+ # handle fake bools (require bool -> str conversions)
+ if isinstance(val, bool):
+ val = "on" if val else "off"
+ else:
+ warn(
+ f'Option f"{key}" is "{val}", but only True or False is '
+ f"allowed. Using default.",
+ OptimizeWarning,
+ stacklevel=2,
+ )
+ continue
+ opt_type = _h.HighsOptionType(opt_type)
+ status, msg = check_option(highs, key, val)
+ if opt_type == _h.HighsOptionType.kBool:
+ if not isinstance(val, bool):
+ warn(
+ f'Option f"{key}" is "{val}", but only True or False is '
+ f"allowed. Using default.",
+ OptimizeWarning,
+ stacklevel=2,
+ )
+ continue
+
+ # warn or set option
+ if status != 0:
+ warn(msg, OptimizeWarning, stacklevel=2)
+ else:
+ setattr(highs_options, key, val)
+
+ opt_status = highs.passOptions(highs_options)
+ if opt_status == _h.HighsStatus.kError:
+ res.update(
+ {
+ "status": highs.getModelStatus(),
+ "message": highs.modelStatusToString(highs.getModelStatus()),
+ }
+ )
+ return res
+
+ init_status = highs.passModel(lp)
+ if init_status == _h.HighsStatus.kError:
+ # if model fails to load, highs.getModelStatus() will be NOT_SET
+ err_model_status = _h.HighsModelStatus.kModelError
+ res.update(
+ {
+ "status": err_model_status,
+ "message": highs.modelStatusToString(err_model_status),
+ }
+ )
+ return res
+
+ # Solve the LP
+ run_status = highs.run()
+ if run_status == _h.HighsStatus.kError:
+ res.update(
+ {
+ "status": highs.getModelStatus(),
+ "message": highs.modelStatusToString(highs.getModelStatus()),
+ }
+ )
+ return res
+
+ # Extract what we need from the solution
+ model_status = highs.getModelStatus()
+
+ # it should always be safe to get the info object
+ info = highs.getInfo()
+
+ # Failure modes:
+ # LP: if we have anything other than an Optimal status, it
+ # is unsafe (and unhelpful) to read any results
+ # MIP: has a non-Optimal status or has timed out/reached max iterations
+ # 1) If not Optimal/TimedOut/MaxIter status, there is no solution
+ # 2) If TimedOut/MaxIter status, there may be a feasible solution.
+ # if the objective function value is not Infinity, then the
+ # current solution is feasible and can be returned. Else, there
+ # is no solution.
+ mipFailCondition = model_status not in (
+ _h.HighsModelStatus.kOptimal,
+ _h.HighsModelStatus.kTimeLimit,
+ _h.HighsModelStatus.kIterationLimit,
+ _h.HighsModelStatus.kSolutionLimit,
+ ) or (
+ model_status
+ in {
+ _h.HighsModelStatus.kTimeLimit,
+ _h.HighsModelStatus.kIterationLimit,
+ _h.HighsModelStatus.kSolutionLimit,
+ }
+ and (info.objective_function_value == _h.kHighsInf)
+ )
+ lpFailCondition = model_status != _h.HighsModelStatus.kOptimal
+ if (isMip and mipFailCondition) or (not isMip and lpFailCondition):
+ res.update(
+ {
+ "status": model_status,
+ "message": "model_status is "
+ f"{highs.modelStatusToString(model_status)}; "
+ "primal_status is "
+ f"{highs.solutionStatusToString(info.primal_solution_status)}",
+ "simplex_nit": info.simplex_iteration_count,
+ "ipm_nit": info.ipm_iteration_count,
+ "crossover_nit": info.crossover_iteration_count,
+ }
+ )
+ return res
+
+ # Should be safe to read the solution:
+ solution = highs.getSolution()
+ basis = highs.getBasis()
+
+ # Lagrangians for bounds based on column statuses
+ marg_bnds = np.zeros((2, numcol))
+ basis_col_status = basis.col_status
+ solution_col_dual = solution.col_dual
+ for ii in range(numcol):
+ if basis_col_status[ii] == _h.HighsBasisStatus.kLower:
+ marg_bnds[0, ii] = solution_col_dual[ii]
+ elif basis_col_status[ii] == _h.HighsBasisStatus.kUpper:
+ marg_bnds[1, ii] = solution_col_dual[ii]
+
+ res.update(
+ {
+ "status": model_status,
+ "message": highs.modelStatusToString(model_status),
+ # Primal solution
+ "x": np.array(solution.col_value),
+ # Ax + s = b => Ax = b - s
+ # Note: this is for all constraints (A_ub and A_eq)
+ "slack": rhs - solution.row_value,
+ # lambda are the lagrange multipliers associated with Ax=b
+ "lambda": np.array(solution.row_dual),
+ "marg_bnds": marg_bnds,
+ "fun": info.objective_function_value,
+ "simplex_nit": info.simplex_iteration_count,
+ "ipm_nit": info.ipm_iteration_count,
+ "crossover_nit": info.crossover_iteration_count,
+ }
+ )
+
+ if isMip:
+ res.update(
+ {
+ "mip_node_count": info.mip_node_count,
+ "mip_dual_bound": info.mip_dual_bound,
+ "mip_gap": info.mip_gap,
+ }
+ )
+
+ return res
+
+
+def check_option(highs_inst, option, value):
+ status, option_type = highs_inst.getOptionType(option)
+ hoptmanager = hopt.HighsOptionsManager()
+
+ if status != _h.HighsStatus.kOk:
+ return -1, "Invalid option name."
+
+ valid_types = {
+ _h.HighsOptionType.kBool: bool,
+ _h.HighsOptionType.kInt: int,
+ _h.HighsOptionType.kDouble: float,
+ _h.HighsOptionType.kString: str,
+ }
+
+ expected_type = valid_types.get(option_type, None)
+
+ if expected_type is str:
+ if not hoptmanager.check_string_option(option, value):
+ return -1, "Invalid option value."
+ if expected_type is float:
+ if not hoptmanager.check_double_option(option, value):
+ return -1, "Invalid option value."
+ if expected_type is int:
+ if not hoptmanager.check_int_option(option, value):
+ return -1, "Invalid option value."
+
+ if expected_type is None:
+ return 3, "Unknown option type."
+
+ status, current_value = highs_inst.getOptionValue(option)
+ if status != _h.HighsStatus.kOk:
+ return 4, "Failed to validate option value."
+ return 0, "Check option succeeded."
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_isotonic.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_isotonic.py
new file mode 100644
index 0000000000000000000000000000000000000000..825576535402a9acf8bbff009a5f76282cb4f500
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_isotonic.py
@@ -0,0 +1,157 @@
+from typing import TYPE_CHECKING
+
+import numpy as np
+
+from ._optimize import OptimizeResult
+from ._pava_pybind import pava
+
+if TYPE_CHECKING:
+ import numpy.typing as npt
+
+
+__all__ = ["isotonic_regression"]
+
+
+def isotonic_regression(
+ y: "npt.ArrayLike",
+ *,
+ weights: "npt.ArrayLike | None" = None,
+ increasing: bool = True,
+) -> OptimizeResult:
+ r"""Nonparametric isotonic regression.
+
+ A (not strictly) monotonically increasing array `x` with the same length
+ as `y` is calculated by the pool adjacent violators algorithm (PAVA), see
+ [1]_. See the Notes section for more details.
+
+ Parameters
+ ----------
+ y : (N,) array_like
+ Response variable.
+ weights : (N,) array_like or None
+ Case weights.
+ increasing : bool
+ If True, fit monotonic increasing, i.e. isotonic, regression.
+ If False, fit a monotonic decreasing, i.e. antitonic, regression.
+ Default is True.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are:
+
+ - ``x``: The isotonic regression solution, i.e. an increasing (or
+ decreasing) array of the same length than y, with elements in the
+ range from min(y) to max(y).
+ - ``weights`` : Array with the sum of case weights for each block
+ (or pool) B.
+ - ``blocks``: Array of length B+1 with the indices of the start
+ positions of each block (or pool) B. The j-th block is given by
+ ``x[blocks[j]:blocks[j+1]]`` for which all values are the same.
+
+ Notes
+ -----
+ Given data :math:`y` and case weights :math:`w`, the isotonic regression
+ solves the following optimization problem:
+
+ .. math::
+
+ \operatorname{argmin}_{x_i} \sum_i w_i (y_i - x_i)^2 \quad
+ \text{subject to } x_i \leq x_j \text{ whenever } i \leq j \,.
+
+ For every input value :math:`y_i`, it generates a value :math:`x_i` such
+ that :math:`x` is increasing (but not strictly), i.e.
+ :math:`x_i \leq x_{i+1}`. This is accomplished by the PAVA.
+ The solution consists of pools or blocks, i.e. neighboring elements of
+ :math:`x`, e.g. :math:`x_i` and :math:`x_{i+1}`, that all have the same
+ value.
+
+ Most interestingly, the solution stays the same if the squared loss is
+ replaced by the wide class of Bregman functions which are the unique
+ class of strictly consistent scoring functions for the mean, see [2]_
+ and references therein.
+
+ The implemented version of PAVA according to [1]_ has a computational
+ complexity of O(N) with input size N.
+
+ References
+ ----------
+ .. [1] Busing, F. M. T. A. (2022).
+ Monotone Regression: A Simple and Fast O(n) PAVA Implementation.
+ Journal of Statistical Software, Code Snippets, 102(1), 1-25.
+ :doi:`10.18637/jss.v102.c01`
+ .. [2] Jordan, A.I., Mühlemann, A. & Ziegel, J.F.
+ Characterizing the optimal solutions to the isotonic regression
+ problem for identifiable functionals.
+ Ann Inst Stat Math 74, 489-514 (2022).
+ :doi:`10.1007/s10463-021-00808-0`
+
+ Examples
+ --------
+ This example demonstrates that ``isotonic_regression`` really solves a
+ constrained optimization problem.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import isotonic_regression, minimize
+ >>> y = [1.5, 1.0, 4.0, 6.0, 5.7, 5.0, 7.8, 9.0, 7.5, 9.5, 9.0]
+ >>> def objective(yhat, y):
+ ... return np.sum((yhat - y)**2)
+ >>> def constraint(yhat, y):
+ ... # This is for a monotonically increasing regression.
+ ... return np.diff(yhat)
+ >>> result = minimize(objective, x0=y, args=(y,),
+ ... constraints=[{'type': 'ineq',
+ ... 'fun': lambda x: constraint(x, y)}])
+ >>> result.x
+ array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667,
+ 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 ,
+ 9.25 ])
+ >>> result = isotonic_regression(y)
+ >>> result.x
+ array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667,
+ 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 ,
+ 9.25 ])
+
+ The big advantage of ``isotonic_regression`` compared to calling
+ ``minimize`` is that it is more user friendly, i.e. one does not need to
+ define objective and constraint functions, and that it is orders of
+ magnitudes faster. On commodity hardware (in 2023), for normal distributed
+ input y of length 1000, the minimizer takes about 4 seconds, while
+ ``isotonic_regression`` takes about 200 microseconds.
+ """
+ yarr = np.atleast_1d(y) # Check yarr.ndim == 1 is implicit (pybind11) in pava.
+ order = slice(None) if increasing else slice(None, None, -1)
+ x = np.array(yarr[order], order="C", dtype=np.float64, copy=True)
+ if weights is None:
+ wx = np.ones_like(yarr, dtype=np.float64)
+ else:
+ warr = np.atleast_1d(weights)
+
+ if not (yarr.ndim == warr.ndim == 1 and yarr.shape[0] == warr.shape[0]):
+ raise ValueError(
+ "Input arrays y and w must have one dimension of equal length."
+ )
+ if np.any(warr <= 0):
+ raise ValueError("Weights w must be strictly positive.")
+
+ wx = np.array(warr[order], order="C", dtype=np.float64, copy=True)
+ n = x.shape[0]
+ r = np.full(shape=n + 1, fill_value=-1, dtype=np.intp)
+ x, wx, r, b = pava(x, wx, r)
+ # Now that we know the number of blocks b, we only keep the relevant part
+ # of r and wx.
+ # As information: Due to the pava implementation, after the last block
+ # index, there might be smaller numbers appended to r, e.g.
+ # r = [0, 10, 8, 7] which in the end should be r = [0, 10].
+ r = r[:b + 1] # type: ignore[assignment]
+ wx = wx[:b]
+ if not increasing:
+ x = x[::-1]
+ wx = wx[::-1]
+ r = r[-1] - r[::-1]
+ return OptimizeResult(
+ x=x,
+ weights=wx,
+ blocks=r,
+ )
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..a91005468b2b45a5a456e961a6a9d01fbbc723fe
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lbfgsb_py.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lbfgsb_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1cee42d67398e93539abe8265b6cc6b6945ce2e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lbfgsb_py.py
@@ -0,0 +1,585 @@
+"""
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ fmin_l_bfgs_b
+
+"""
+
+## License for the Python wrapper
+## ==============================
+
+## Copyright (c) 2004 David M. Cooke
+
+## Permission is hereby granted, free of charge, to any person obtaining a
+## copy of this software and associated documentation files (the "Software"),
+## to deal in the Software without restriction, including without limitation
+## the rights to use, copy, modify, merge, publish, distribute, sublicense,
+## and/or sell copies of the Software, and to permit persons to whom the
+## Software is furnished to do so, subject to the following conditions:
+
+## The above copyright notice and this permission notice shall be included in
+## all copies or substantial portions of the Software.
+
+## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+## DEALINGS IN THE SOFTWARE.
+
+## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy
+
+import numpy as np
+from numpy import asarray, array, zeros # noqa: F401
+from . import _lbfgsb
+from ._optimize import (MemoizeJac, OptimizeResult, _call_callback_maybe_halt,
+ _wrap_callback, _check_unknown_options,
+ _prepare_scalar_function)
+from ._constraints import old_bound_to_new
+from scipy.linalg.lapack import HAS_ILP64
+
+from scipy.sparse.linalg import LinearOperator
+
+__all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct']
+
+
+status_messages = {
+ 0 : "START",
+ 1 : "NEW_X",
+ 2 : "RESTART",
+ 3 : "FG",
+ 4 : "CONVERGENCE",
+ 5 : "STOP",
+ 6 : "WARNING",
+ 7 : "ERROR",
+ 8 : "ABNORMAL"
+}
+
+
+task_messages = {
+ 0 : "",
+ 301 : "",
+ 302 : "",
+ 401 : "NORM OF PROJECTED GRADIENT <= PGTOL",
+ 402 : "RELATIVE REDUCTION OF F <= FACTR*EPSMCH",
+ 501 : "CPU EXCEEDING THE TIME LIMIT",
+ 502 : "TOTAL NO. OF F,G EVALUATIONS EXCEEDS LIMIT",
+ 503 : "PROJECTED GRADIENT IS SUFFICIENTLY SMALL",
+ 504 : "TOTAL NO. OF ITERATIONS REACHED LIMIT",
+ 505 : "CALLBACK REQUESTED HALT",
+ 601 : "ROUNDING ERRORS PREVENT PROGRESS",
+ 602 : "STP = STPMAX",
+ 603 : "STP = STPMIN",
+ 604 : "XTOL TEST SATISFIED",
+ 701 : "NO FEASIBLE SOLUTION",
+ 702 : "FACTR < 0",
+ 703 : "FTOL < 0",
+ 704 : "GTOL < 0",
+ 705 : "XTOL < 0",
+ 706 : "STP < STPMIN",
+ 707 : "STP > STPMAX",
+ 708 : "STPMIN < 0",
+ 709 : "STPMAX < STPMIN",
+ 710 : "INITIAL G >= 0",
+ 711 : "M <= 0",
+ 712 : "N <= 0",
+ 713 : "INVALID NBD",
+}
+
+def fmin_l_bfgs_b(func, x0, fprime=None, args=(), approx_grad=0, bounds=None, m=10,
+ factr=1e7, pgtol=1e-5, epsilon=1e-8, maxfun=15000, maxiter=15000,
+ callback=None, maxls=20):
+ """
+ Minimize a function func using the L-BFGS-B algorithm.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Function to minimize.
+ x0 : ndarray
+ Initial guess.
+ fprime : callable fprime(x,*args), optional
+ The gradient of `func`. If None, then `func` returns the function
+ value and the gradient (``f, g = func(x, *args)``), unless
+ `approx_grad` is True in which case `func` returns only ``f``.
+ args : sequence, optional
+ Arguments to pass to `func` and `fprime`.
+ approx_grad : bool, optional
+ Whether to approximate the gradient numerically (in which case
+ `func` returns only the function value).
+ bounds : list, optional
+ ``(min, max)`` pairs for each element in ``x``, defining
+ the bounds on that parameter. Use None or +-inf for one of ``min`` or
+ ``max`` when there is no bound in that direction.
+ m : int, optional
+ The maximum number of variable metric corrections
+ used to define the limited memory matrix. (The limited memory BFGS
+ method does not store the full hessian but uses this many terms in an
+ approximation to it.)
+ factr : float, optional
+ The iteration stops when
+ ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
+ where ``eps`` is the machine precision, which is automatically
+ generated by the code. Typical values for `factr` are: 1e12 for
+ low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
+ high accuracy. See Notes for relationship to `ftol`, which is exposed
+ (instead of `factr`) by the `scipy.optimize.minimize` interface to
+ L-BFGS-B.
+ pgtol : float, optional
+ The iteration will stop when
+ ``max{|proj g_i | i = 1, ..., n} <= pgtol``
+ where ``proj g_i`` is the i-th component of the projected gradient.
+ epsilon : float, optional
+ Step size used when `approx_grad` is True, for numerically
+ calculating the gradient
+ maxfun : int, optional
+ Maximum number of function evaluations. Note that this function
+ may violate the limit because of evaluating gradients by numerical
+ differentiation.
+ maxiter : int, optional
+ Maximum number of iterations.
+ callback : callable, optional
+ Called after each iteration, as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ maxls : int, optional
+ Maximum number of line search steps (per iteration). Default is 20.
+
+ Returns
+ -------
+ x : array_like
+ Estimated position of the minimum.
+ f : float
+ Value of `func` at the minimum.
+ d : dict
+ Information dictionary.
+
+ * d['warnflag'] is
+
+ - 0 if converged,
+ - 1 if too many function evaluations or too many iterations,
+ - 2 if stopped for another reason, given in d['task']
+
+ * d['grad'] is the gradient at the minimum (should be 0 ish)
+ * d['funcalls'] is the number of function calls made.
+ * d['nit'] is the number of iterations.
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'L-BFGS-B' `method` in particular. Note that the
+ `ftol` option is made available via that interface, while `factr` is
+ provided via this interface, where `factr` is the factor multiplying
+ the default machine floating-point precision to arrive at `ftol`:
+ ``ftol = factr * numpy.finfo(float).eps``.
+
+ Notes
+ -----
+ SciPy uses a C-translated and modified version of the Fortran code,
+ L-BFGS-B v3.0 (released April 25, 2011, BSD-3 licensed). Original Fortran
+ version was written by Ciyou Zhu, Richard Byrd, Jorge Nocedal and,
+ Jose Luis Morales.
+
+ References
+ ----------
+ * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
+ Constrained Optimization, (1995), SIAM Journal on Scientific and
+ Statistical Computing, 16, 5, pp. 1190-1208.
+ * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
+ FORTRAN routines for large scale bound constrained optimization (1997),
+ ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
+ * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
+ FORTRAN routines for large scale bound constrained optimization (2011),
+ ACM Transactions on Mathematical Software, 38, 1.
+
+ Examples
+ --------
+ Solve a linear regression problem via `fmin_l_bfgs_b`. To do this, first we
+ define an objective function ``f(m, b) = (y - y_model)**2``, where `y`
+ describes the observations and `y_model` the prediction of the linear model
+ as ``y_model = m*x + b``. The bounds for the parameters, ``m`` and ``b``,
+ are arbitrarily chosen as ``(0,5)`` and ``(5,10)`` for this example.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import fmin_l_bfgs_b
+ >>> X = np.arange(0, 10, 1)
+ >>> M = 2
+ >>> B = 3
+ >>> Y = M * X + B
+ >>> def func(parameters, *args):
+ ... x = args[0]
+ ... y = args[1]
+ ... m, b = parameters
+ ... y_model = m*x + b
+ ... error = sum(np.power((y - y_model), 2))
+ ... return error
+
+ >>> initial_values = np.array([0.0, 1.0])
+
+ >>> x_opt, f_opt, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
+ ... approx_grad=True)
+ >>> x_opt, f_opt
+ array([1.99999999, 3.00000006]), 1.7746231151323805e-14 # may vary
+
+ The optimized parameters in ``x_opt`` agree with the ground truth parameters
+ ``m`` and ``b``. Next, let us perform a bound constrained optimization using
+ the `bounds` parameter.
+
+ >>> bounds = [(0, 5), (5, 10)]
+ >>> x_opt, f_op, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y),
+ ... approx_grad=True, bounds=bounds)
+ >>> x_opt, f_opt
+ array([1.65990508, 5.31649385]), 15.721334516453945 # may vary
+ """
+ # handle fprime/approx_grad
+ if approx_grad:
+ fun = func
+ jac = None
+ elif fprime is None:
+ fun = MemoizeJac(func)
+ jac = fun.derivative
+ else:
+ fun = func
+ jac = fprime
+
+ # build options
+ callback = _wrap_callback(callback)
+ opts = {'maxcor': m,
+ 'ftol': factr * np.finfo(float).eps,
+ 'gtol': pgtol,
+ 'eps': epsilon,
+ 'maxfun': maxfun,
+ 'maxiter': maxiter,
+ 'callback': callback,
+ 'maxls': maxls}
+
+ res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,
+ **opts)
+ d = {'grad': res['jac'],
+ 'task': res['message'],
+ 'funcalls': res['nfev'],
+ 'nit': res['nit'],
+ 'warnflag': res['status']}
+ f = res['fun']
+ x = res['x']
+
+ return x, f, d
+
+
+def _minimize_lbfgsb(fun, x0, args=(), jac=None, bounds=None, maxcor=10,
+ ftol=2.2204460492503131e-09, gtol=1e-5, eps=1e-8, maxfun=15000,
+ maxiter=15000, callback=None, maxls=20, finite_diff_rel_step=None,
+ workers=None, **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using the L-BFGS-B
+ algorithm.
+
+ Options
+ -------
+ maxcor : int
+ The maximum number of variable metric corrections used to
+ define the limited memory matrix. (The limited memory BFGS
+ method does not store the full hessian but uses this many terms
+ in an approximation to it.)
+ ftol : float
+ The iteration stops when ``(f^k -
+ f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.
+ gtol : float
+ The iteration will stop when ``max{|proj g_i | i = 1, ..., n}
+ <= gtol`` where ``proj g_i`` is the i-th component of the
+ projected gradient.
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ maxfun : int
+ Maximum number of function evaluations before minimization terminates.
+ Note that this function may violate the limit if the gradients
+ are evaluated by numerical differentiation.
+ maxiter : int
+ Maximum number of algorithm iterations.
+ maxls : int, optional
+ Maximum number of line search steps (per iteration). Default is 20.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
+ but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
+ relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
+ I.e., `factr` multiplies the default machine floating-point precision to
+ arrive at `ftol`.
+ If the minimization is slow to converge the optimizer may halt if the
+ total number of function evaluations exceeds `maxfun`, or the number of
+ algorithm iterations has reached `maxiter` (whichever comes first). If
+ this is the case then ``result.success=False``, and an appropriate
+ error message is contained in ``result.message``.
+
+ """
+ _check_unknown_options(unknown_options)
+ m = maxcor
+ pgtol = gtol
+ factr = ftol / np.finfo(float).eps
+
+ x0 = np.asarray(x0).ravel()
+ n, = x0.shape
+
+ # historically old-style bounds were/are expected by lbfgsb.
+ # That's still the case but we'll deal with new-style from here on,
+ # it's easier
+ if bounds is None:
+ pass
+ elif len(bounds) != n:
+ raise ValueError('length of x0 != length of bounds')
+ else:
+ bounds = np.array(old_bound_to_new(bounds))
+
+ # check bounds
+ if (bounds[0] > bounds[1]).any():
+ raise ValueError(
+ "LBFGSB - one of the lower bounds is greater than an upper bound."
+ )
+
+ # initial vector must lie within the bounds. Otherwise ScalarFunction and
+ # approx_derivative will cause problems
+ x0 = np.clip(x0, bounds[0], bounds[1])
+
+ # _prepare_scalar_function can use bounds=None to represent no bounds
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+ bounds=bounds,
+ finite_diff_rel_step=finite_diff_rel_step,
+ workers=workers)
+
+ func_and_grad = sf.fun_and_grad
+
+ int_dtype = np.int64 if HAS_ILP64 else np.int32
+
+ nbd = np.zeros(n, dtype=int_dtype)
+ low_bnd = np.zeros(n, dtype=np.float64)
+ upper_bnd = np.zeros(n, dtype=np.float64)
+ bounds_map = {(-np.inf, np.inf): 0,
+ (1, np.inf): 1,
+ (1, 1): 2,
+ (-np.inf, 1): 3}
+
+ if bounds is not None:
+ for i in range(0, n):
+ L, U = bounds[0, i], bounds[1, i]
+ if not np.isinf(L):
+ low_bnd[i] = L
+ L = 1
+ if not np.isinf(U):
+ upper_bnd[i] = U
+ U = 1
+ nbd[i] = bounds_map[L, U]
+
+ if not maxls > 0:
+ raise ValueError('maxls must be positive.')
+
+ x = np.array(x0, dtype=np.float64)
+ f = np.array(0.0, dtype=np.float64)
+ g = np.zeros((n,), dtype=np.float64)
+ wa = np.zeros(2*m*n + 5*n + 11*m*m + 8*m, np.float64)
+ iwa = np.zeros(3*n, dtype=int_dtype)
+ task = np.zeros(2, dtype=int_dtype)
+ ln_task = np.zeros(2, dtype=int_dtype)
+ lsave = np.zeros(4, dtype=int_dtype)
+ isave = np.zeros(44, dtype=int_dtype)
+ dsave = np.zeros(29, dtype=np.float64)
+
+ n_iterations = 0
+
+ while True:
+ # g may become float32 if a user provides a function that calculates
+ # the Jacobian in float32 (see gh-18730). The underlying code expects
+ # float64, so upcast it
+ g = g.astype(np.float64)
+ # x, f, g, wa, iwa, task, csave, lsave, isave, dsave = \
+ _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa,
+ iwa, task, lsave, isave, dsave, maxls, ln_task)
+
+ if task[0] == 3:
+ # The minimization routine wants f and g at the current x.
+ # Note that interruptions due to maxfun are postponed
+ # until the completion of the current minimization iteration.
+ # Overwrite f and g:
+ f, g = func_and_grad(x)
+ elif task[0] == 1:
+ # new iteration
+ n_iterations += 1
+
+ intermediate_result = OptimizeResult(x=x, fun=f)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ task[0] = 5
+ task[1] = 505
+ if n_iterations >= maxiter:
+ task[0] = 5
+ task[1] = 504
+ elif sf.nfev > maxfun:
+ task[0] = 5
+ task[1] = 502
+ else:
+ break
+
+ if task[0] == 4:
+ warnflag = 0
+ elif sf.nfev > maxfun or n_iterations >= maxiter:
+ warnflag = 1
+ else:
+ warnflag = 2
+
+ # These two portions of the workspace are described in the mainlb
+ # function docstring in "__lbfgsb.c", ws and wy arguments.
+ s = wa[0: m*n].reshape(m, n)
+ y = wa[m*n: 2*m*n].reshape(m, n)
+
+ # isave(31) = the total number of BFGS updates prior the current iteration.
+ n_bfgs_updates = isave[30]
+
+ n_corrs = min(n_bfgs_updates, maxcor)
+ hess_inv = LbfgsInvHessProduct(s[:n_corrs], y[:n_corrs])
+
+ msg = status_messages[task[0]] + ": " + task_messages[task[1]]
+
+ return OptimizeResult(fun=f, jac=g, nfev=sf.nfev,
+ njev=sf.ngev,
+ nit=n_iterations, status=warnflag, message=msg,
+ x=x, success=(warnflag == 0), hess_inv=hess_inv)
+
+
+class LbfgsInvHessProduct(LinearOperator):
+ """Linear operator for the L-BFGS approximate inverse Hessian.
+
+ This operator computes the product of a vector with the approximate inverse
+ of the Hessian of the objective function, using the L-BFGS limited
+ memory approximation to the inverse Hessian, accumulated during the
+ optimization.
+
+ Objects of this class implement the ``scipy.sparse.linalg.LinearOperator``
+ interface.
+
+ Parameters
+ ----------
+ sk : array_like, shape=(n_corr, n)
+ Array of `n_corr` most recent updates to the solution vector.
+ (See [1]).
+ yk : array_like, shape=(n_corr, n)
+ Array of `n_corr` most recent updates to the gradient. (See [1]).
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited
+ storage." Mathematics of computation 35.151 (1980): 773-782.
+
+ """
+
+ def __init__(self, sk, yk):
+ """Construct the operator."""
+ if sk.shape != yk.shape or sk.ndim != 2:
+ raise ValueError('sk and yk must have matching shape, (n_corrs, n)')
+ n_corrs, n = sk.shape
+
+ super().__init__(dtype=np.float64, shape=(n, n))
+
+ self.sk = sk
+ self.yk = yk
+ self.n_corrs = n_corrs
+ self.rho = 1 / np.einsum('ij,ij->i', sk, yk)
+
+ def _matvec(self, x):
+ """Efficient matrix-vector multiply with the BFGS matrices.
+
+ This calculation is described in Section (4) of [1].
+
+ Parameters
+ ----------
+ x : ndarray
+ An array with shape (n,) or (n,1).
+
+ Returns
+ -------
+ y : ndarray
+ The matrix-vector product
+
+ """
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+ q = np.array(x, dtype=self.dtype, copy=True)
+ if q.ndim == 2 and q.shape[1] == 1:
+ q = q.reshape(-1)
+
+ alpha = np.empty(n_corrs)
+
+ for i in range(n_corrs-1, -1, -1):
+ alpha[i] = rho[i] * np.dot(s[i], q)
+ q = q - alpha[i]*y[i]
+
+ r = q
+ for i in range(n_corrs):
+ beta = rho[i] * np.dot(y[i], r)
+ r = r + s[i] * (alpha[i] - beta)
+
+ return r
+
+ def _matmat(self, X):
+ """Efficient matrix-matrix multiply with the BFGS matrices.
+
+ This calculation is described in Section (4) of [1].
+
+ Parameters
+ ----------
+ X : ndarray
+ An array with shape (n,m)
+
+ Returns
+ -------
+ Y : ndarray
+ The matrix-matrix product
+
+ Notes
+ -----
+ This implementation is written starting from _matvec and broadcasting
+ all expressions along the second axis of X.
+
+ """
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+ Q = np.array(X, dtype=self.dtype, copy=True)
+
+ alpha = np.empty((n_corrs, Q.shape[1]))
+
+ for i in range(n_corrs-1, -1, -1):
+ alpha[i] = rho[i] * np.dot(s[i], Q)
+ Q -= alpha[i]*y[i][:, np.newaxis]
+
+ R = Q
+ for i in range(n_corrs):
+ beta = rho[i] * np.dot(y[i], R)
+ R += s[i][:, np.newaxis] * (alpha[i] - beta)
+
+ return R
+
+ def todense(self):
+ """Return a dense array representation of this operator.
+
+ Returns
+ -------
+ arr : ndarray, shape=(n, n)
+ An array with the same shape and containing
+ the same data represented by this `LinearOperator`.
+
+ """
+ I_arr = np.eye(*self.shape, dtype=self.dtype)
+ return self._matmat(I_arr)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linesearch.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..9366b359cd5786d7612af1e164ee0f29cfb0ed36
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linesearch.py
@@ -0,0 +1,910 @@
+"""
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ line_search_armijo
+ line_search_wolfe1
+ line_search_wolfe2
+ scalar_search_wolfe1
+ scalar_search_wolfe2
+
+"""
+from warnings import warn
+
+from ._dcsrch import DCSRCH
+import numpy as np
+
+__all__ = ['LineSearchWarning', 'line_search_wolfe1', 'line_search_wolfe2',
+ 'scalar_search_wolfe1', 'scalar_search_wolfe2',
+ 'line_search_armijo']
+
+class LineSearchWarning(RuntimeWarning):
+ pass
+
+
+def _check_c1_c2(c1, c2):
+ if not (0 < c1 < c2 < 1):
+ raise ValueError("'c1' and 'c2' do not satisfy"
+ "'0 < c1 < c2 < 1'.")
+
+
+#------------------------------------------------------------------------------
+# Minpack's Wolfe line and scalar searches
+#------------------------------------------------------------------------------
+
+def line_search_wolfe1(f, fprime, xk, pk, gfk=None,
+ old_fval=None, old_old_fval=None,
+ args=(), c1=1e-4, c2=0.9, amax=50, amin=1e-8,
+ xtol=1e-14):
+ """
+ As `scalar_search_wolfe1` but do a line search to direction `pk`.
+
+ This implements the DCSRCH function of MINPACK.
+
+ Parameters
+ ----------
+ f : callable
+ Function `f(x)`
+ fprime : callable
+ Gradient of `f`
+ xk : array_like
+ Current point
+ pk : array_like
+ Search direction
+ gfk : array_like, optional
+ Gradient of `f` at point `xk`
+ old_fval : float, optional
+ Value of `f` at point `xk`
+ old_old_fval : float, optional
+ Value of `f` at point preceding `xk`
+
+ The rest of the parameters are the same as for `scalar_search_wolfe1`.
+
+ Returns
+ -------
+ stp, f_count, g_count, fval, old_fval
+ As in `line_search_wolfe1`
+ gval : array
+ Gradient of `f` at the final point
+
+ Notes
+ -----
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ References
+ ----------
+ .. [1] Jorge J. Moré and David J. Thuente. 1994. "Line search algorithms with
+ guaranteed sufficient decrease". ACM Trans. Math. Softw. 20, 3 (Sept. 1994),
+ 286-307. doi:`10.1145/192115.192132`
+
+ """
+ if gfk is None:
+ gfk = fprime(xk, *args)
+
+ gval = [gfk]
+ gc = [0]
+ fc = [0]
+
+ def phi(s):
+ fc[0] += 1
+ return f(xk + s*pk, *args)
+
+ def derphi(s):
+ gval[0] = fprime(xk + s*pk, *args)
+ gc[0] += 1
+ return np.dot(gval[0], pk)
+
+ derphi0 = np.dot(gfk, pk)
+
+ stp, fval, old_fval = scalar_search_wolfe1(
+ phi, derphi, old_fval, old_old_fval, derphi0,
+ c1=c1, c2=c2, amax=amax, amin=amin, xtol=xtol)
+
+ return stp, fc[0], gc[0], fval, old_fval, gval[0]
+
+
+def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None,
+ c1=1e-4, c2=0.9,
+ amax=50, amin=1e-8, xtol=1e-14):
+ """
+ Scalar function search for alpha that satisfies strong Wolfe conditions
+
+ alpha > 0 is assumed to be a descent direction.
+
+ Parameters
+ ----------
+ phi : callable phi(alpha)
+ Function at point `alpha`
+ derphi : callable phi'(alpha)
+ Objective function derivative. Returns a scalar.
+ phi0 : float, optional
+ Value of phi at 0
+ old_phi0 : float, optional
+ Value of phi at previous point
+ derphi0 : float, optional
+ Value derphi at 0
+ c1 : float, optional
+ Parameter for Armijo condition rule.
+ c2 : float, optional
+ Parameter for curvature condition rule.
+ amax, amin : float, optional
+ Maximum and minimum step size
+ xtol : float, optional
+ Relative tolerance for an acceptable step.
+
+ Returns
+ -------
+ alpha : float
+ Step size, or None if no suitable step was found
+ phi : float
+ Value of `phi` at the new point `alpha`
+ phi0 : float
+ Value of `phi` at `alpha=0`
+
+ Notes
+ -----
+ Uses routine DCSRCH from MINPACK.
+
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1`` as described in [1]_.
+
+ References
+ ----------
+ .. [1] J. Nocedal and S. J. Wright. "Numerical Optimization". Springer Ser.
+ Oper. Res. Financ. Eng. Springer, New York, NY, USA, second edition,
+ 2006. :doi:`10.1007/978-0-387-40065-5`
+
+ """
+ _check_c1_c2(c1, c2)
+
+ if phi0 is None:
+ phi0 = phi(0.)
+ if derphi0 is None:
+ derphi0 = derphi(0.)
+
+ if old_phi0 is not None and derphi0 != 0:
+ alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0)
+ if alpha1 < 0:
+ alpha1 = 1.0
+ else:
+ alpha1 = 1.0
+
+ maxiter = 100
+
+ dcsrch = DCSRCH(phi, derphi, c1, c2, xtol, amin, amax)
+ stp, phi1, phi0, task = dcsrch(
+ alpha1, phi0=phi0, derphi0=derphi0, maxiter=maxiter
+ )
+
+ return stp, phi1, phi0
+
+
+line_search = line_search_wolfe1
+
+
+#------------------------------------------------------------------------------
+# Pure-Python Wolfe line and scalar searches
+#------------------------------------------------------------------------------
+
+# Note: `line_search_wolfe2` is the public `scipy.optimize.line_search`
+
+def line_search_wolfe2(f, myfprime, xk, pk, gfk=None, old_fval=None,
+ old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=None,
+ extra_condition=None, maxiter=10):
+ """Find alpha that satisfies strong Wolfe conditions.
+
+ Parameters
+ ----------
+ f : callable f(x,*args)
+ Objective function.
+ myfprime : callable f'(x,*args)
+ Objective function gradient.
+ xk : ndarray
+ Starting point.
+ pk : ndarray
+ Search direction. The search direction must be a descent direction
+ for the algorithm to converge.
+ gfk : ndarray, optional
+ Gradient value for x=xk (xk being the current parameter
+ estimate). Will be recomputed if omitted.
+ old_fval : float, optional
+ Function value for x=xk. Will be recomputed if omitted.
+ old_old_fval : float, optional
+ Function value for the point preceding x=xk.
+ args : tuple, optional
+ Additional arguments passed to objective function.
+ c1 : float, optional
+ Parameter for Armijo condition rule.
+ c2 : float, optional
+ Parameter for curvature condition rule.
+ amax : float, optional
+ Maximum step size
+ extra_condition : callable, optional
+ A callable of the form ``extra_condition(alpha, x, f, g)``
+ returning a boolean. Arguments are the proposed step ``alpha``
+ and the corresponding ``x``, ``f`` and ``g`` values. The line search
+ accepts the value of ``alpha`` only if this
+ callable returns ``True``. If the callable returns ``False``
+ for the step length, the algorithm will continue with
+ new iterates. The callable is only called for iterates
+ satisfying the strong Wolfe conditions.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+
+ Returns
+ -------
+ alpha : float or None
+ Alpha for which ``x_new = x0 + alpha * pk``,
+ or None if the line search algorithm did not converge.
+ fc : int
+ Number of function evaluations made.
+ gc : int
+ Number of gradient evaluations made.
+ new_fval : float or None
+ New function value ``f(x_new)=f(x0+alpha*pk)``,
+ or None if the line search algorithm did not converge.
+ old_fval : float
+ Old function value ``f(x0)``.
+ new_slope : float or None
+ The local slope along the search direction at the
+ new value ````,
+ or None if the line search algorithm did not converge.
+
+
+ Notes
+ -----
+ Uses the line search algorithm to enforce strong Wolfe conditions. See algorithms
+ 3.5 and 3.6 on pp. 60-61 in [1]_ (first edition, algorithms 3.2 and 3.3 on
+ pp. 59-61), see also [2]_.
+
+ The search direction `pk` must be a descent direction (e.g.
+ ``-myfprime(xk)``) to find a step length that satisfies the strong Wolfe
+ conditions. If the search direction is not a descent direction (e.g.
+ ``myfprime(xk)``), then `alpha`, `new_fval`, and `new_slope` will be None.
+
+ References
+ ----------
+ .. [1] J. Nocedal and S. J. Wright. "Numerical Optimization". Springer Ser.
+ Oper. Res. Financ. Eng. Springer, New York, NY, USA, second edition,
+ 2006. doi:`10.1007/978-0-387-40065-5`
+ .. [2] R. Fletcher, "Practical Methods of Optimization." Wiley, May 23, 2000.
+ doi:`10.1002/9781118723203`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import line_search
+
+ An objective function and its gradient are defined.
+
+ >>> def obj_func(x):
+ ... return (x[0])**2+(x[1])**2
+ >>> def obj_grad(x):
+ ... return [2*x[0], 2*x[1]]
+
+ We can find alpha that satisfies strong Wolfe conditions.
+
+ >>> start_point = np.array([1.8, 1.7])
+ >>> search_gradient = np.array([-1.0, -1.0])
+ >>> line_search(obj_func, obj_grad, start_point, search_gradient)
+ (1.0, 2, 1, 1.1300000000000001, 6.13, [1.6, 1.4])
+
+ """
+ fc = [0]
+ gc = [0]
+ gval = [None]
+ gval_alpha = [None]
+
+ def phi(alpha):
+ fc[0] += 1
+ return f(xk + alpha * pk, *args)
+
+ fprime = myfprime
+
+ def derphi(alpha):
+ gc[0] += 1
+ gval[0] = fprime(xk + alpha * pk, *args) # store for later use
+ gval_alpha[0] = alpha
+ return np.dot(gval[0], pk)
+
+ if gfk is None:
+ gfk = fprime(xk, *args)
+ derphi0 = np.dot(gfk, pk)
+
+ if extra_condition is not None:
+ # Add the current gradient as argument, to avoid needless
+ # re-evaluation
+ def extra_condition2(alpha, phi):
+ if gval_alpha[0] != alpha:
+ derphi(alpha)
+ x = xk + alpha * pk
+ return extra_condition(alpha, x, phi, gval[0])
+ else:
+ extra_condition2 = None
+
+ alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2(
+ phi, derphi, old_fval, old_old_fval, derphi0, c1, c2, amax,
+ extra_condition2, maxiter=maxiter)
+
+ if derphi_star is None:
+ warn('The line search algorithm did not converge',
+ LineSearchWarning, stacklevel=2)
+ else:
+ # derphi_star is a number (derphi) -- so use the most recently
+ # calculated gradient used in computing it derphi = gfk*pk
+ # this is the gradient at the next step no need to compute it
+ # again in the outer loop.
+ derphi_star = gval[0]
+
+ return alpha_star, fc[0], gc[0], phi_star, old_fval, derphi_star
+
+
+def scalar_search_wolfe2(phi, derphi, phi0=None,
+ old_phi0=None, derphi0=None,
+ c1=1e-4, c2=0.9, amax=None,
+ extra_condition=None, maxiter=10):
+ """Find alpha that satisfies strong Wolfe conditions.
+
+ alpha > 0 is assumed to be a descent direction.
+
+ Parameters
+ ----------
+ phi : callable phi(alpha)
+ Objective scalar function.
+ derphi : callable phi'(alpha)
+ Objective function derivative. Returns a scalar.
+ phi0 : float, optional
+ Value of phi at 0.
+ old_phi0 : float, optional
+ Value of phi at previous point.
+ derphi0 : float, optional
+ Value of derphi at 0
+ c1 : float, optional
+ Parameter for Armijo condition rule.
+ c2 : float, optional
+ Parameter for curvature condition rule.
+ amax : float, optional
+ Maximum step size.
+ extra_condition : callable, optional
+ A callable of the form ``extra_condition(alpha, phi_value)``
+ returning a boolean. The line search accepts the value
+ of ``alpha`` only if this callable returns ``True``.
+ If the callable returns ``False`` for the step length,
+ the algorithm will continue with new iterates.
+ The callable is only called for iterates satisfying
+ the strong Wolfe conditions.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+
+ Returns
+ -------
+ alpha_star : float or None
+ Best alpha, or None if the line search algorithm did not converge.
+ phi_star : float
+ phi at alpha_star.
+ phi0 : float
+ phi at 0.
+ derphi_star : float or None
+ derphi at alpha_star, or None if the line search algorithm
+ did not converge.
+
+ Notes
+ -----
+ Uses the line search algorithm to enforce strong Wolfe
+ conditions. See Wright and Nocedal, 'Numerical Optimization',
+ 1999, pp. 59-61.
+
+ """
+ _check_c1_c2(c1, c2)
+
+ if phi0 is None:
+ phi0 = phi(0.)
+
+ if derphi0 is None:
+ derphi0 = derphi(0.)
+
+ alpha0 = 0
+ if old_phi0 is not None and derphi0 != 0:
+ alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0)
+ else:
+ alpha1 = 1.0
+
+ if alpha1 < 0:
+ alpha1 = 1.0
+
+ if amax is not None:
+ alpha1 = min(alpha1, amax)
+
+ phi_a1 = phi(alpha1)
+ #derphi_a1 = derphi(alpha1) evaluated below
+
+ phi_a0 = phi0
+ derphi_a0 = derphi0
+
+ if extra_condition is None:
+ def extra_condition(alpha, phi):
+ return True
+
+ for i in range(maxiter):
+ if alpha1 == 0 or (amax is not None and alpha0 > amax):
+ # alpha1 == 0: This shouldn't happen. Perhaps the increment has
+ # slipped below machine precision?
+ alpha_star = None
+ phi_star = phi0
+ phi0 = old_phi0
+ derphi_star = None
+
+ if alpha1 == 0:
+ msg = 'Rounding errors prevent the line search from converging'
+ else:
+ msg = "The line search algorithm could not find a solution " + \
+ f"less than or equal to amax: {amax}"
+
+ warn(msg, LineSearchWarning, stacklevel=2)
+ break
+
+ not_first_iteration = i > 0
+ if (phi_a1 > phi0 + c1 * alpha1 * derphi0) or \
+ ((phi_a1 >= phi_a0) and not_first_iteration):
+ alpha_star, phi_star, derphi_star = \
+ _zoom(alpha0, alpha1, phi_a0,
+ phi_a1, derphi_a0, phi, derphi,
+ phi0, derphi0, c1, c2, extra_condition)
+ break
+
+ derphi_a1 = derphi(alpha1)
+ if (abs(derphi_a1) <= -c2*derphi0):
+ if extra_condition(alpha1, phi_a1):
+ alpha_star = alpha1
+ phi_star = phi_a1
+ derphi_star = derphi_a1
+ break
+
+ if (derphi_a1 >= 0):
+ alpha_star, phi_star, derphi_star = \
+ _zoom(alpha1, alpha0, phi_a1,
+ phi_a0, derphi_a1, phi, derphi,
+ phi0, derphi0, c1, c2, extra_condition)
+ break
+
+ alpha2 = 2 * alpha1 # increase by factor of two on each iteration
+ if amax is not None:
+ alpha2 = min(alpha2, amax)
+ alpha0 = alpha1
+ alpha1 = alpha2
+ phi_a0 = phi_a1
+ phi_a1 = phi(alpha1)
+ derphi_a0 = derphi_a1
+
+ else:
+ # stopping test maxiter reached
+ alpha_star = alpha1
+ phi_star = phi_a1
+ derphi_star = None
+ warn('The line search algorithm did not converge',
+ LineSearchWarning, stacklevel=2)
+
+ return alpha_star, phi_star, phi0, derphi_star
+
+
+def _cubicmin(a, fa, fpa, b, fb, c, fc):
+ """
+ Finds the minimizer for a cubic polynomial that goes through the
+ points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa.
+
+ If no minimizer can be found, return None.
+
+ """
+ # f(x) = A *(x-a)^3 + B*(x-a)^2 + C*(x-a) + D
+
+ with np.errstate(divide='raise', over='raise', invalid='raise'):
+ try:
+ C = fpa
+ db = b - a
+ dc = c - a
+ denom = (db * dc) ** 2 * (db - dc)
+ d1 = np.empty((2, 2))
+ d1[0, 0] = dc ** 2
+ d1[0, 1] = -db ** 2
+ d1[1, 0] = -dc ** 3
+ d1[1, 1] = db ** 3
+ [A, B] = np.dot(d1, np.asarray([fb - fa - C * db,
+ fc - fa - C * dc]).flatten())
+ A /= denom
+ B /= denom
+ radical = B * B - 3 * A * C
+ xmin = a + (-B + np.sqrt(radical)) / (3 * A)
+ except ArithmeticError:
+ return None
+ if not np.isfinite(xmin):
+ return None
+ return xmin
+
+
+def _quadmin(a, fa, fpa, b, fb):
+ """
+ Finds the minimizer for a quadratic polynomial that goes through
+ the points (a,fa), (b,fb) with derivative at a of fpa.
+
+ """
+ # f(x) = B*(x-a)^2 + C*(x-a) + D
+ with np.errstate(divide='raise', over='raise', invalid='raise'):
+ try:
+ D = fa
+ C = fpa
+ db = b - a * 1.0
+ B = (fb - D - C * db) / (db * db)
+ xmin = a - C / (2.0 * B)
+ except ArithmeticError:
+ return None
+ if not np.isfinite(xmin):
+ return None
+ return xmin
+
+
+def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo,
+ phi, derphi, phi0, derphi0, c1, c2, extra_condition):
+ """Zoom stage of approximate linesearch satisfying strong Wolfe conditions.
+
+ Part of the optimization algorithm in `scalar_search_wolfe2`.
+
+ Notes
+ -----
+ Implements Algorithm 3.6 (zoom) in Wright and Nocedal,
+ 'Numerical Optimization', 1999, pp. 61.
+
+ """
+
+ maxiter = 10
+ i = 0
+ delta1 = 0.2 # cubic interpolant check
+ delta2 = 0.1 # quadratic interpolant check
+ phi_rec = phi0
+ a_rec = 0
+ while True:
+ # interpolate to find a trial step length between a_lo and
+ # a_hi Need to choose interpolation here. Use cubic
+ # interpolation and then if the result is within delta *
+ # dalpha or outside of the interval bounded by a_lo or a_hi
+ # then use quadratic interpolation, if the result is still too
+ # close, then use bisection
+
+ dalpha = a_hi - a_lo
+ if dalpha < 0:
+ a, b = a_hi, a_lo
+ else:
+ a, b = a_lo, a_hi
+
+ # minimizer of cubic interpolant
+ # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi)
+ #
+ # if the result is too close to the end points (or out of the
+ # interval), then use quadratic interpolation with phi_lo,
+ # derphi_lo and phi_hi if the result is still too close to the
+ # end points (or out of the interval) then use bisection
+
+ if (i > 0):
+ cchk = delta1 * dalpha
+ a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi,
+ a_rec, phi_rec)
+ if (i == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk):
+ qchk = delta2 * dalpha
+ a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi)
+ if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk):
+ a_j = a_lo + 0.5*dalpha
+
+ # Check new value of a_j
+
+ phi_aj = phi(a_j)
+ if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo):
+ phi_rec = phi_hi
+ a_rec = a_hi
+ a_hi = a_j
+ phi_hi = phi_aj
+ else:
+ derphi_aj = derphi(a_j)
+ if abs(derphi_aj) <= -c2*derphi0 and extra_condition(a_j, phi_aj):
+ a_star = a_j
+ val_star = phi_aj
+ valprime_star = derphi_aj
+ break
+ if derphi_aj*(a_hi - a_lo) >= 0:
+ phi_rec = phi_hi
+ a_rec = a_hi
+ a_hi = a_lo
+ phi_hi = phi_lo
+ else:
+ phi_rec = phi_lo
+ a_rec = a_lo
+ a_lo = a_j
+ phi_lo = phi_aj
+ derphi_lo = derphi_aj
+ i += 1
+ if (i > maxiter):
+ # Failed to find a conforming step size
+ a_star = None
+ val_star = None
+ valprime_star = None
+ break
+ return a_star, val_star, valprime_star
+
+
+#------------------------------------------------------------------------------
+# Armijo line and scalar searches
+#------------------------------------------------------------------------------
+
+def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1):
+ """Minimize over alpha, the function ``f(xk+alpha pk)``.
+
+ Parameters
+ ----------
+ f : callable
+ Function to be minimized.
+ xk : array_like
+ Current point.
+ pk : array_like
+ Search direction.
+ gfk : array_like
+ Gradient of `f` at point `xk`.
+ old_fval : float
+ Value of `f` at point `xk`.
+ args : tuple, optional
+ Optional arguments.
+ c1 : float, optional
+ Value to control stopping criterion.
+ alpha0 : scalar, optional
+ Value of `alpha` at start of the optimization.
+
+ Returns
+ -------
+ alpha
+ f_count
+ f_val_at_alpha
+
+ Notes
+ -----
+ Uses the interpolation algorithm (Armijo backtracking) as suggested by
+ Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57
+
+ """
+ xk = np.atleast_1d(xk)
+ fc = [0]
+
+ def phi(alpha1):
+ fc[0] += 1
+ return f(xk + alpha1*pk, *args)
+
+ if old_fval is None:
+ phi0 = phi(0.)
+ else:
+ phi0 = old_fval # compute f(xk) -- done in past loop
+
+ derphi0 = np.dot(gfk, pk)
+ alpha, phi1 = scalar_search_armijo(phi, phi0, derphi0, c1=c1,
+ alpha0=alpha0)
+ return alpha, fc[0], phi1
+
+
+def line_search_BFGS(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1):
+ """
+ Compatibility wrapper for `line_search_armijo`
+ """
+ r = line_search_armijo(f, xk, pk, gfk, old_fval, args=args, c1=c1,
+ alpha0=alpha0)
+ return r[0], r[1], 0, r[2]
+
+
+def scalar_search_armijo(phi, phi0, derphi0, c1=1e-4, alpha0=1, amin=0):
+ """Minimize over alpha, the function ``phi(alpha)``.
+
+ Uses the interpolation algorithm (Armijo backtracking) as suggested by
+ Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57
+
+ alpha > 0 is assumed to be a descent direction.
+
+ Returns
+ -------
+ alpha
+ phi1
+
+ """
+ phi_a0 = phi(alpha0)
+ if phi_a0 <= phi0 + c1*alpha0*derphi0:
+ return alpha0, phi_a0
+
+ # Otherwise, compute the minimizer of a quadratic interpolant:
+
+ alpha1 = -(derphi0) * alpha0**2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0)
+ phi_a1 = phi(alpha1)
+
+ if (phi_a1 <= phi0 + c1*alpha1*derphi0):
+ return alpha1, phi_a1
+
+ # Otherwise, loop with cubic interpolation until we find an alpha which
+ # satisfies the first Wolfe condition (since we are backtracking, we will
+ # assume that the value of alpha is not too small and satisfies the second
+ # condition.
+
+ while alpha1 > amin: # we are assuming alpha>0 is a descent direction
+ factor = alpha0**2 * alpha1**2 * (alpha1-alpha0)
+ a = alpha0**2 * (phi_a1 - phi0 - derphi0*alpha1) - \
+ alpha1**2 * (phi_a0 - phi0 - derphi0*alpha0)
+ a = a / factor
+ b = -alpha0**3 * (phi_a1 - phi0 - derphi0*alpha1) + \
+ alpha1**3 * (phi_a0 - phi0 - derphi0*alpha0)
+ b = b / factor
+
+ alpha2 = (-b + np.sqrt(abs(b**2 - 3 * a * derphi0))) / (3.0*a)
+ phi_a2 = phi(alpha2)
+
+ if (phi_a2 <= phi0 + c1*alpha2*derphi0):
+ return alpha2, phi_a2
+
+ if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2/alpha1) < 0.96:
+ alpha2 = alpha1 / 2.0
+
+ alpha0 = alpha1
+ alpha1 = alpha2
+ phi_a0 = phi_a1
+ phi_a1 = phi_a2
+
+ # Failed to find a suitable step length
+ return None, phi_a1
+
+
+#------------------------------------------------------------------------------
+# Non-monotone line search for DF-SANE
+#------------------------------------------------------------------------------
+
+def _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta,
+ gamma=1e-4, tau_min=0.1, tau_max=0.5):
+ """
+ Nonmonotone backtracking line search as described in [1]_
+
+ Parameters
+ ----------
+ f : callable
+ Function returning a tuple ``(f, F)`` where ``f`` is the value
+ of a merit function and ``F`` the residual.
+ x_k : ndarray
+ Initial position.
+ d : ndarray
+ Search direction.
+ prev_fs : float
+ List of previous merit function values. Should have ``len(prev_fs) <= M``
+ where ``M`` is the nonmonotonicity window parameter.
+ eta : float
+ Allowed merit function increase, see [1]_
+ gamma, tau_min, tau_max : float, optional
+ Search parameters, see [1]_
+
+ Returns
+ -------
+ alpha : float
+ Step length
+ xp : ndarray
+ Next position
+ fp : float
+ Merit function value at next position
+ Fp : ndarray
+ Residual at next position
+
+ References
+ ----------
+ [1] "Spectral residual method without gradient information for solving
+ large-scale nonlinear systems of equations." W. La Cruz,
+ J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006).
+
+ """
+ f_k = prev_fs[-1]
+ f_bar = max(prev_fs)
+
+ alpha_p = 1
+ alpha_m = 1
+ alpha = 1
+
+ while True:
+ xp = x_k + alpha_p * d
+ fp, Fp = f(xp)
+
+ if fp <= f_bar + eta - gamma * alpha_p**2 * f_k:
+ alpha = alpha_p
+ break
+
+ alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k)
+
+ xp = x_k - alpha_m * d
+ fp, Fp = f(xp)
+
+ if fp <= f_bar + eta - gamma * alpha_m**2 * f_k:
+ alpha = -alpha_m
+ break
+
+ alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k)
+
+ alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p)
+ alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m)
+
+ return alpha, xp, fp, Fp
+
+
+def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta,
+ gamma=1e-4, tau_min=0.1, tau_max=0.5,
+ nu=0.85):
+ """
+ Nonmonotone line search from [1]
+
+ Parameters
+ ----------
+ f : callable
+ Function returning a tuple ``(f, F)`` where ``f`` is the value
+ of a merit function and ``F`` the residual.
+ x_k : ndarray
+ Initial position.
+ d : ndarray
+ Search direction.
+ f_k : float
+ Initial merit function value.
+ C, Q : float
+ Control parameters. On the first iteration, give values
+ Q=1.0, C=f_k
+ eta : float
+ Allowed merit function increase, see [1]_
+ nu, gamma, tau_min, tau_max : float, optional
+ Search parameters, see [1]_
+
+ Returns
+ -------
+ alpha : float
+ Step length
+ xp : ndarray
+ Next position
+ fp : float
+ Merit function value at next position
+ Fp : ndarray
+ Residual at next position
+ C : float
+ New value for the control parameter C
+ Q : float
+ New value for the control parameter Q
+
+ References
+ ----------
+ .. [1] W. Cheng & D.-H. Li, ''A derivative-free nonmonotone line
+ search and its application to the spectral residual
+ method'', IMA J. Numer. Anal. 29, 814 (2009).
+
+ """
+ alpha_p = 1
+ alpha_m = 1
+ alpha = 1
+
+ while True:
+ xp = x_k + alpha_p * d
+ fp, Fp = f(xp)
+
+ if fp <= C + eta - gamma * alpha_p**2 * f_k:
+ alpha = alpha_p
+ break
+
+ alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k)
+
+ xp = x_k - alpha_m * d
+ fp, Fp = f(xp)
+
+ if fp <= C + eta - gamma * alpha_m**2 * f_k:
+ alpha = -alpha_m
+ break
+
+ alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k)
+
+ alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p)
+ alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m)
+
+ # Update C and Q
+ Q_next = nu * Q + 1
+ C = (nu * Q * (C + eta) + fp) / Q_next
+ Q = Q_next
+
+ return alpha, xp, fp, Fp, C, Q
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog.py
new file mode 100644
index 0000000000000000000000000000000000000000..48e875bb401eac66227662514699b8362f53e52e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog.py
@@ -0,0 +1,733 @@
+"""
+A top-level linear programming interface.
+
+.. versionadded:: 0.15.0
+
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ linprog
+ linprog_verbose_callback
+ linprog_terse_callback
+
+"""
+
+import numpy as np
+
+from ._optimize import OptimizeResult, OptimizeWarning
+from warnings import warn
+from ._linprog_highs import _linprog_highs
+from ._linprog_ip import _linprog_ip
+from ._linprog_simplex import _linprog_simplex
+from ._linprog_rs import _linprog_rs
+from ._linprog_doc import (_linprog_highs_doc, _linprog_ip_doc, # noqa: F401
+ _linprog_rs_doc, _linprog_simplex_doc,
+ _linprog_highs_ipm_doc, _linprog_highs_ds_doc)
+from ._linprog_util import (
+ _parse_linprog, _presolve, _get_Abc, _LPProblem, _autoscale,
+ _postsolve, _check_result, _display_summary)
+from copy import deepcopy
+
+__all__ = ['linprog', 'linprog_verbose_callback', 'linprog_terse_callback']
+
+__docformat__ = "restructuredtext en"
+
+LINPROG_METHODS = [
+ 'simplex', 'revised simplex', 'interior-point', 'highs', 'highs-ds', 'highs-ipm'
+]
+
+
+def linprog_verbose_callback(res):
+ """
+ A sample callback function demonstrating the linprog callback interface.
+ This callback produces detailed output to sys.stdout before each iteration
+ and after the final iteration of the simplex algorithm.
+
+ Parameters
+ ----------
+ res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ The independent variable vector which optimizes the linear
+ programming problem.
+ fun : float
+ Value of the objective function.
+ success : bool
+ True if the algorithm succeeded in finding an optimal solution.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable corresponds
+ to an inequality constraint. If the slack is zero, then the
+ corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ status : int
+ An integer representing the exit status of the optimization:
+
+ ``0`` : Optimization terminated successfully
+
+ ``1`` : Iteration limit reached
+
+ ``2`` : Problem appears to be infeasible
+
+ ``3`` : Problem appears to be unbounded
+
+ ``4`` : Serious numerical difficulties encountered
+
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ """
+ x = res['x']
+ fun = res['fun']
+ phase = res['phase']
+ status = res['status']
+ nit = res['nit']
+ message = res['message']
+ complete = res['complete']
+
+ saved_printoptions = np.get_printoptions()
+ np.set_printoptions(linewidth=500,
+ formatter={'float': lambda x: f"{x: 12.4f}"})
+ if status:
+ print('--------- Simplex Early Exit -------\n')
+ print(f'The simplex method exited early with status {status:d}')
+ print(message)
+ elif complete:
+ print('--------- Simplex Complete --------\n')
+ print(f'Iterations required: {nit}')
+ else:
+ print(f'--------- Iteration {nit:d} ---------\n')
+
+ if nit > 0:
+ if phase == 1:
+ print('Current Pseudo-Objective Value:')
+ else:
+ print('Current Objective Value:')
+ print('f = ', fun)
+ print()
+ print('Current Solution Vector:')
+ print('x = ', x)
+ print()
+
+ np.set_printoptions(**saved_printoptions)
+
+
+def linprog_terse_callback(res):
+ """
+ A sample callback function demonstrating the linprog callback interface.
+ This callback produces brief output to sys.stdout before each iteration
+ and after the final iteration of the simplex algorithm.
+
+ Parameters
+ ----------
+ res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ The independent variable vector which optimizes the linear
+ programming problem.
+ fun : float
+ Value of the objective function.
+ success : bool
+ True if the algorithm succeeded in finding an optimal solution.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable corresponds
+ to an inequality constraint. If the slack is zero, then the
+ corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``.
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ status : int
+ An integer representing the exit status of the optimization:
+
+ ``0`` : Optimization terminated successfully
+
+ ``1`` : Iteration limit reached
+
+ ``2`` : Problem appears to be infeasible
+
+ ``3`` : Problem appears to be unbounded
+
+ ``4`` : Serious numerical difficulties encountered
+
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ """
+ nit = res['nit']
+ x = res['x']
+
+ if nit == 0:
+ print("Iter: X:")
+ print(f"{nit: <5d} ", end="")
+ print(x)
+
+
+def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=(0, None), method='highs', callback=None,
+ options=None, x0=None, integrality=None):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ - minimize ::
+
+ c @ x
+
+ - such that ::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None``. Other bounds can be
+ specified with ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable.
+ If a single tuple ``(min, max)`` is provided, then ``min`` and ``max``
+ will serve as bounds for all decision variables.
+ Use ``None`` to indicate that there is no bound. For instance, the
+ default bound ``(0, None)`` means that all decision variables are
+ non-negative, and the pair ``(None, None)`` means no bounds at all,
+ i.e. all variables are allowed to be any real.
+ method : str, optional
+ The algorithm used to solve the standard form problem.
+ The following are supported.
+
+ - :ref:`'highs' ` (default)
+ - :ref:`'highs-ds' `
+ - :ref:`'highs-ipm' `
+ - :ref:`'interior-point' ` (legacy)
+ - :ref:`'revised simplex' ` (legacy)
+ - :ref:`'simplex' ` (legacy)
+
+ The legacy methods are deprecated and will be removed in SciPy 1.11.0.
+ callback : callable, optional
+ If a callback function is provided, it will be called at least once per
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ The current solution vector.
+ fun : float
+ The current value of the objective function ``c @ x``.
+ success : bool
+ ``True`` when the algorithm has completed successfully.
+ slack : 1-D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ phase : int
+ The phase of the algorithm being executed.
+ status : int
+ An integer representing the status of the algorithm.
+
+ ``0`` : Optimization proceeding nominally.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ nit : int
+ The current iteration number.
+ message : str
+ A string descriptor of the algorithm status.
+
+ Callback functions are not currently supported by the HiGHS methods.
+
+ options : dict, optional
+ A dictionary of solver options. All methods accept the following
+ options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ Default: see method-specific documentation.
+ disp : bool
+ Set to ``True`` to print convergence messages.
+ Default: ``False``.
+ presolve : bool
+ Set to ``False`` to disable automatic presolve.
+ Default: ``True``.
+
+ All methods except the HiGHS solvers also accept:
+
+ tol : float
+ A tolerance which determines when a residual is "close enough" to
+ zero to be considered exactly zero.
+ autoscale : bool
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ Default: ``False``.
+ rr : bool
+ Set to ``False`` to disable automatic redundancy removal.
+ Default: ``True``.
+ rr_method : str
+ Method used to identify and remove redundant rows from the
+ equality constraint matrix after presolve. For problems with
+ dense input, the available methods for redundancy removal are:
+
+ ``SVD``:
+ Repeatedly performs singular value decomposition on
+ the matrix, detecting redundant rows based on nonzeros
+ in the left singular vectors that correspond with
+ zero singular values. May be fast when the matrix is
+ nearly full rank.
+ ``pivot``:
+ Uses the algorithm presented in [5]_ to identify
+ redundant rows.
+ ``ID``:
+ Uses a randomized interpolative decomposition.
+ Identifies columns of the matrix transpose not used in
+ a full-rank interpolative decomposition of the matrix.
+ ``None``:
+ Uses ``svd`` if the matrix is nearly full rank, that is,
+ the difference between the matrix rank and the number
+ of rows is less than five. If not, uses ``pivot``. The
+ behavior of this default is subject to change without
+ prior notice.
+
+ Default: None.
+ For problems with sparse input, this option is ignored, and the
+ pivot-based algorithm presented in [5]_ is used.
+
+ For method-specific options, see
+ :func:`show_options('linprog') `.
+
+ x0 : 1-D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ :ref:`'revised simplex' ` method,
+ and can only be used if `x0` represents a basic feasible solution.
+
+ integrality : 1-D array or int, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or ``0``.
+
+ By default, all variables are continuous.
+
+ For mixed integrality constraints, supply an array of shape ``c.shape``.
+ To infer a constraint on each decision variable from shorter inputs,
+ the argument will be broadcast to ``c.shape`` using `numpy.broadcast_to`.
+
+ This argument is currently used only by the
+ :ref:`'highs' ` method and is ignored otherwise.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields
+ below. Note that the return types of the fields may depend on whether
+ the optimization was successful, therefore it is recommended to check
+ `OptimizeResult.status` before relying on the other fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ nit : int
+ The total number of iterations performed in all phases.
+ message : str
+ A string descriptor of the exit status of the algorithm.
+
+ See Also
+ --------
+ show_options : Additional options accepted by the solvers.
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter.
+
+ :ref:`'highs-ds' `, and
+ :ref:`'highs-ipm' ` are interfaces to the
+ HiGHS simplex and interior-point method solvers [13]_, respectively.
+ :ref:`'highs' ` (default) chooses between
+ the two automatically. These are the fastest linear
+ programming solvers in SciPy, especially for large, sparse problems;
+ which of these two is faster is problem-dependent.
+ The other solvers are legacy methods and will be removed when `callback` is
+ supported by the HiGHS methods.
+
+ Method :ref:`'highs-ds' `, is a wrapper of the C++ high
+ performance dual revised simplex implementation (HSOL) [13]_, [14]_.
+ Method :ref:`'highs-ipm' ` is a wrapper of a C++
+ implementation of an **i**\ nterior-\ **p**\ oint **m**\ ethod [13]_; it
+ features a crossover routine, so it is as accurate as a simplex solver.
+ Method :ref:`'highs' ` chooses between the two
+ automatically.
+ For new code involving `linprog`, we recommend explicitly choosing one of
+ these three method values.
+
+ .. versionadded:: 1.6.0
+
+ Method :ref:`'interior-point' `
+ uses the primal-dual path following algorithm
+ as outlined in [4]_. This algorithm supports sparse constraint matrices and
+ is typically faster than the simplex methods, especially for large, sparse
+ problems. Note, however, that the solution returned may be slightly less
+ accurate than those of the simplex methods and will not, in general,
+ correspond with a vertex of the polytope defined by the constraints.
+
+ .. versionadded:: 1.0.0
+
+ Method :ref:`'revised simplex' `
+ uses the revised simplex method as described in
+ [9]_, except that a factorization [11]_ of the basis matrix, rather than
+ its inverse, is efficiently maintained and used to solve the linear systems
+ at each iteration of the algorithm.
+
+ .. versionadded:: 1.3.0
+
+ Method :ref:`'simplex' ` uses a traditional,
+ full-tableau implementation of
+ Dantzig's simplex algorithm [1]_, [2]_ (*not* the
+ Nelder-Mead simplex). This algorithm is included for backwards
+ compatibility and educational purposes.
+
+ .. versionadded:: 0.15.0
+
+ Before applying :ref:`'interior-point' `,
+ :ref:`'revised simplex' `, or
+ :ref:`'simplex' `,
+ a presolve procedure based on [8]_ attempts
+ to identify trivial infeasibilities, trivial unboundedness, and potential
+ problem simplifications. Specifically, it checks for:
+
+ - rows of zeros in ``A_eq`` or ``A_ub``, representing trivial constraints;
+ - columns of zeros in ``A_eq`` `and` ``A_ub``, representing unconstrained
+ variables;
+ - column singletons in ``A_eq``, representing fixed variables; and
+ - column singletons in ``A_ub``, representing simple bounds.
+
+ If presolve reveals that the problem is unbounded (e.g. an unconstrained
+ and unbounded variable has negative cost) or infeasible (e.g., a row of
+ zeros in ``A_eq`` corresponds with a nonzero in ``b_eq``), the solver
+ terminates with the appropriate status code. Note that presolve terminates
+ as soon as any sign of unboundedness is detected; consequently, a problem
+ may be reported as unbounded when in reality the problem is infeasible
+ (but infeasibility has not been detected yet). Therefore, if it is
+ important to know whether the problem is actually infeasible, solve the
+ problem again with option ``presolve=False``.
+
+ If neither infeasibility nor unboundedness are detected in a single pass
+ of the presolve, bounds are tightened where possible and fixed
+ variables are removed from the problem. Then, linearly dependent rows
+ of the ``A_eq`` matrix are removed, (unless they represent an
+ infeasibility) to avoid numerical difficulties in the primary solve
+ routine. Note that rows that are nearly linearly dependent (within a
+ prescribed tolerance) may also be removed, which can change the optimal
+ solution in rare cases. If this is a concern, eliminate redundancy from
+ your problem formulation and run with option ``rr=False`` or
+ ``presolve=False``.
+
+ Several potential improvements can be made here: additional presolve
+ checks outlined in [8]_ should be implemented, the presolve routine should
+ be run multiple times (until no further simplifications can be made), and
+ more of the efficiency improvements from [5]_ should be implemented in the
+ redundancy removal routines.
+
+ After presolve, the problem is transformed to standard form by converting
+ the (tightened) simple bounds to upper bound constraints, introducing
+ non-negative slack variables for inequality constraints, and expressing
+ unbounded variables as the difference between two non-negative variables.
+ Optionally, the problem is automatically scaled via equilibration [12]_.
+ The selected algorithm solves the standard form problem, and a
+ postprocessing routine converts the result to a solution to the original
+ problem.
+
+ References
+ ----------
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [5] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+ .. [7] Fourer, Robert. "Solving Linear Programs by Interior-Point Methods."
+ Unpublished Course Notes, August 26, 2005. Available 2/25/2017 at
+ http://www.4er.org/CourseNotes/Book%20B/B-III.pdf
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [10] Andersen, Erling D., et al. Implementation of interior point
+ methods for large scale linear programming. HEC/Universite de
+ Geneve, 1996.
+ .. [11] Bartels, Richard H. "A stabilization of the simplex method."
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
+ .. [12] Tomlin, J. A. "On scaling linear programming problems."
+ Mathematical Programming Study 4 (1975): 146-166.
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. :doi:`10.1007/s12532-017-0130-5`.
+
+ Examples
+ --------
+ Consider the following problem:
+
+ .. math::
+
+ \min_{x_0, x_1} \ -x_0 + 4x_1 & \\
+ \mbox{such that} \ -3x_0 + x_1 & \leq 6,\\
+ -x_0 - 2x_1 & \geq -4,\\
+ x_1 & \geq -3.
+
+ The problem is not presented in the form accepted by `linprog`. This is
+ easily remedied by converting the "greater than" inequality
+ constraint to a "less than" inequality constraint by
+ multiplying both sides by a factor of :math:`-1`. Note also that the last
+ constraint is really the simple bound :math:`-3 \leq x_1 \leq \infty`.
+ Finally, since there are no bounds on :math:`x_0`, we must explicitly
+ specify the bounds :math:`-\infty \leq x_0 \leq \infty`, as the
+ default is for variables to be non-negative. After collecting coeffecients
+ into arrays and tuples, the input for this problem is:
+
+ >>> from scipy.optimize import linprog
+ >>> c = [-1, 4]
+ >>> A = [[-3, 1], [1, 2]]
+ >>> b = [6, 4]
+ >>> x0_bounds = (None, None)
+ >>> x1_bounds = (-3, None)
+ >>> res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds])
+ >>> res.fun
+ -22.0
+ >>> res.x
+ array([10., -3.])
+ >>> res.message
+ 'Optimization terminated successfully. (HiGHS Status 7: Optimal)'
+
+ The marginals (AKA dual values / shadow prices / Lagrange multipliers)
+ and residuals (slacks) are also available.
+
+ >>> res.ineqlin
+ residual: [ 3.900e+01 0.000e+00]
+ marginals: [-0.000e+00 -1.000e+00]
+
+ For example, because the marginal associated with the second inequality
+ constraint is -1, we expect the optimal value of the objective function
+ to decrease by ``eps`` if we add a small amount ``eps`` to the right hand
+ side of the second inequality constraint:
+
+ >>> eps = 0.05
+ >>> b[1] += eps
+ >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
+ -22.05
+
+ Also, because the residual on the first inequality constraint is 39, we
+ can decrease the right hand side of the first constraint by 39 without
+ affecting the optimal solution.
+
+ >>> b = [6, 4] # reset to original values
+ >>> b[0] -= 39
+ >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
+ -22.0
+
+ """
+
+ meth = method.lower()
+ methods = {"highs", "highs-ds", "highs-ipm",
+ "simplex", "revised simplex", "interior-point"}
+
+ if meth not in methods:
+ raise ValueError(f"Unknown solver '{method}'")
+
+ if x0 is not None and meth != "revised simplex":
+ warning_message = "x0 is used only when method is 'revised simplex'. "
+ warn(warning_message, OptimizeWarning, stacklevel=2)
+
+ if np.any(integrality) and not meth == "highs":
+ integrality = None
+ warning_message = ("Only `method='highs'` supports integer "
+ "constraints. Ignoring `integrality`.")
+ warn(warning_message, OptimizeWarning, stacklevel=2)
+ elif np.any(integrality):
+ integrality = np.broadcast_to(integrality, np.shape(c))
+ else:
+ integrality = None
+
+ lp = _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality)
+ lp, solver_options = _parse_linprog(lp, options, meth)
+ tol = solver_options.get('tol', 1e-9)
+
+ # Give unmodified problem to HiGHS
+ if meth.startswith('highs'):
+ if callback is not None:
+ raise NotImplementedError("HiGHS solvers do not support the "
+ "callback interface.")
+ highs_solvers = {'highs-ipm': 'ipm', 'highs-ds': 'simplex',
+ 'highs': None}
+
+ sol = _linprog_highs(lp, solver=highs_solvers[meth],
+ **solver_options)
+ sol['status'], sol['message'] = (
+ _check_result(sol['x'], sol['fun'], sol['status'], sol['slack'],
+ sol['con'], lp.bounds, tol, sol['message'],
+ integrality))
+ sol['success'] = sol['status'] == 0
+ return OptimizeResult(sol)
+
+ warn(f"`method='{meth}'` is deprecated and will be removed in SciPy "
+ "1.11.0. Please use one of the HiGHS solvers (e.g. "
+ "`method='highs'`) in new code.", DeprecationWarning, stacklevel=2)
+
+ iteration = 0
+ complete = False # will become True if solved in presolve
+ undo = []
+
+ # Keep the original arrays to calculate slack/residuals for original
+ # problem.
+ lp_o = deepcopy(lp)
+
+ # Solve trivial problem, eliminate variables, tighten bounds, etc.
+ rr_method = solver_options.pop('rr_method', None) # need to pop these;
+ rr = solver_options.pop('rr', True) # they're not passed to methods
+ c0 = 0 # we might get a constant term in the objective
+ if solver_options.pop('presolve', True):
+ (lp, c0, x, undo, complete, status, message) = _presolve(lp, rr,
+ rr_method,
+ tol)
+
+ C, b_scale = 1, 1 # for trivial unscaling if autoscale is not used
+ postsolve_args = (lp_o._replace(bounds=lp.bounds), undo, C, b_scale)
+
+ if not complete:
+ A, b, c, c0, x0 = _get_Abc(lp, c0)
+ if solver_options.pop('autoscale', False):
+ A, b, c, x0, C, b_scale = _autoscale(A, b, c, x0)
+ postsolve_args = postsolve_args[:-2] + (C, b_scale)
+
+ if meth == 'simplex':
+ x, status, message, iteration = _linprog_simplex(
+ c, c0=c0, A=A, b=b, callback=callback,
+ postsolve_args=postsolve_args, **solver_options)
+ elif meth == 'interior-point':
+ x, status, message, iteration = _linprog_ip(
+ c, c0=c0, A=A, b=b, callback=callback,
+ postsolve_args=postsolve_args, **solver_options)
+ elif meth == 'revised simplex':
+ x, status, message, iteration = _linprog_rs(
+ c, c0=c0, A=A, b=b, x0=x0, callback=callback,
+ postsolve_args=postsolve_args, **solver_options)
+
+ # Eliminate artificial variables, re-introduce presolved variables, etc.
+ disp = solver_options.get('disp', False)
+
+ x, fun, slack, con = _postsolve(x, postsolve_args, complete)
+
+ status, message = _check_result(x, fun, status, slack, con, lp_o.bounds,
+ tol, message, integrality)
+
+ if disp:
+ _display_summary(message, status, fun, iteration)
+
+ sol = {
+ 'x': x,
+ 'fun': fun,
+ 'slack': slack,
+ 'con': con,
+ 'status': status,
+ 'message': message,
+ 'nit': iteration,
+ 'success': status == 0}
+
+ return OptimizeResult(sol)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_doc.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_doc.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c98c8702923c79695b15908b72e6b4fe053bb45
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_doc.py
@@ -0,0 +1,1434 @@
+"""
+Created on Sat Aug 22 19:49:17 2020
+
+@author: matth
+"""
+
+
+def _linprog_highs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='highs', callback=None,
+ maxiter=None, disp=False, presolve=True,
+ time_limit=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ ipm_optimality_tolerance=None,
+ simplex_dual_edge_weight_strategy=None,
+ mip_rel_gap=None,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using one of the HiGHS solvers.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+
+ This is the method-specific documentation for 'highs', which chooses
+ automatically between
+ :ref:`'highs-ds' ` and
+ :ref:`'highs-ipm' `.
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+ integrality : 1-D array or int, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or ``0``.
+
+ By default, all variables are continuous.
+
+ For mixed integrality constraints, supply an array of shape `c.shape`.
+ To infer a constraint on each decision variable from shorter inputs,
+ the argument will be broadcast to `c.shape` using `np.broadcast_to`.
+
+ This argument is currently used only by the ``'highs'`` method and
+ ignored otherwise.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ For :ref:`'highs-ipm' `, this does not
+ include the number of crossover iterations. Default is the largest
+ possible value for an ``int`` on the platform.
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem;
+ default is the largest possible value for a ``double`` on the
+ platform.
+ dual_feasibility_tolerance : double (default: 1e-07)
+ Dual feasibility tolerance for
+ :ref:`'highs-ds' `.
+ The minimum of this and ``primal_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ primal_feasibility_tolerance : double (default: 1e-07)
+ Primal feasibility tolerance for
+ :ref:`'highs-ds' `.
+ The minimum of this and ``dual_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ ipm_optimality_tolerance : double (default: ``1e-08``)
+ Optimality tolerance for
+ :ref:`'highs-ipm' `.
+ Minimum allowable value is 1e-12.
+ simplex_dual_edge_weight_strategy : str (default: None)
+ Strategy for simplex dual edge weights. The default, ``None``,
+ automatically selects one of the following.
+
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
+ negative reduced cost.
+
+ ``'devex'`` uses the strategy described in [15]_.
+
+ ``steepest`` uses the exact steepest edge strategy as described in
+ [16]_.
+
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
+ until the computation is too costly or inexact and then switches to
+ the devex method.
+
+ Currently, ``None`` always selects ``'steepest-devex'``, but this
+ may change as new options become available.
+ mip_rel_gap : double, optional
+ Termination criterion for MIP solver: solver will terminate when the
+ gap between the primal objective value and the dual objective bound,
+ scaled by the primal objective value, is <= mip_rel_gap. Default: 0.0001.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing
+ all unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed.
+ For the HiGHS simplex method, this includes iterations in all
+ phases. For the HiGHS interior-point method, this does not include
+ crossover iterations.
+ crossover_nit : int
+ The number of primal/dual pushes performed during the
+ crossover routine for the HiGHS interior-point method.
+ This is ``0`` for the HiGHS simplex method.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ Notes
+ -----
+
+ Method :ref:`'highs-ds' ` is a wrapper
+ of the C++ high performance dual revised simplex implementation (HSOL)
+ [13]_, [14]_. Method :ref:`'highs-ipm' `
+ is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
+ **m**\ ethod [13]_; it features a crossover routine, so it is as accurate
+ as a simplex solver. Method :ref:`'highs' ` chooses
+ between the two automatically. For new code involving `linprog`, we
+ recommend explicitly choosing one of these three method values instead of
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy).
+
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. :doi:`10.1007/s12532-017-0130-5`.
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
+ Mathematical programming 5.1 (1973): 1-28.
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
+ """
+ pass
+
+
+def _linprog_highs_ds_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='highs-ds', callback=None,
+ maxiter=None, disp=False, presolve=True,
+ time_limit=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ simplex_dual_edge_weight_strategy=None,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the HiGHS dual simplex solver.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+
+ This is the method-specific documentation for 'highs-ds'.
+ :ref:`'highs' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ Default is the largest possible value for an ``int`` on the platform.
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem;
+ default is the largest possible value for a ``double`` on the
+ platform.
+ dual_feasibility_tolerance : double (default: 1e-07)
+ Dual feasibility tolerance for
+ :ref:`'highs-ds' `.
+ primal_feasibility_tolerance : double (default: 1e-07)
+ Primal feasibility tolerance for
+ :ref:`'highs-ds' `.
+ simplex_dual_edge_weight_strategy : str (default: None)
+ Strategy for simplex dual edge weights. The default, ``None``,
+ automatically selects one of the following.
+
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
+ negative reduced cost.
+
+ ``'devex'`` uses the strategy described in [15]_.
+
+ ``steepest`` uses the exact steepest edge strategy as described in
+ [16]_.
+
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
+ until the computation is too costly or inexact and then switches to
+ the devex method.
+
+ Currently, ``None`` always selects ``'steepest-devex'``, but this
+ may change as new options become available.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing
+ all unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed. This includes iterations
+ in all phases.
+ crossover_nit : int
+ This is always ``0`` for the HiGHS simplex method.
+ For the HiGHS interior-point method, this is the number of
+ primal/dual pushes performed during the crossover routine.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ Notes
+ -----
+
+ Method :ref:`'highs-ds' ` is a wrapper
+ of the C++ high performance dual revised simplex implementation (HSOL)
+ [13]_, [14]_. Method :ref:`'highs-ipm' `
+ is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
+ **m**\ ethod [13]_; it features a crossover routine, so it is as accurate
+ as a simplex solver. Method :ref:`'highs' ` chooses
+ between the two automatically. For new code involving `linprog`, we
+ recommend explicitly choosing one of these three method values instead of
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy).
+
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. :doi:`10.1007/s12532-017-0130-5`.
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
+ Mathematical programming 5.1 (1973): 1-28.
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
+ """
+ pass
+
+
+def _linprog_highs_ipm_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='highs-ipm', callback=None,
+ maxiter=None, disp=False, presolve=True,
+ time_limit=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ ipm_optimality_tolerance=None,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the HiGHS interior point solver.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+
+ This is the method-specific documentation for 'highs-ipm'.
+ :ref:`'highs-ipm' `,
+ :ref:`'highs-ds' `,
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ For :ref:`'highs-ipm' `, this does not
+ include the number of crossover iterations. Default is the largest
+ possible value for an ``int`` on the platform.
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem;
+ default is the largest possible value for a ``double`` on the
+ platform.
+ dual_feasibility_tolerance : double (default: 1e-07)
+ The minimum of this and ``primal_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ primal_feasibility_tolerance : double (default: 1e-07)
+ The minimum of this and ``dual_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ ipm_optimality_tolerance : double (default: ``1e-08``)
+ Optimality tolerance for
+ :ref:`'highs-ipm' `.
+ Minimum allowable value is 1e-12.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing
+ all unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed.
+ For the HiGHS interior-point method, this does not include
+ crossover iterations.
+ crossover_nit : int
+ The number of primal/dual pushes performed during the
+ crossover routine for the HiGHS interior-point method.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ Notes
+ -----
+
+ Method :ref:`'highs-ipm' `
+ is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
+ **m**\ ethod [13]_; it features a crossover routine, so it is as accurate
+ as a simplex solver.
+ Method :ref:`'highs-ds' ` is a wrapper
+ of the C++ high performance dual revised simplex implementation (HSOL)
+ [13]_, [14]_. Method :ref:`'highs' ` chooses
+ between the two automatically. For new code involving `linprog`, we
+ recommend explicitly choosing one of these three method values instead of
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy).
+
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. :doi:`10.1007/s12532-017-0130-5`.
+ """
+ pass
+
+
+def _linprog_ip_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='interior-point', callback=None,
+ maxiter=1000, disp=False, presolve=True,
+ tol=1e-8, autoscale=False, rr=True,
+ alpha0=.99995, beta=0.1, sparse=False,
+ lstsq=False, sym_pos=True, cholesky=True, pc=True,
+ ip=False, permc_spec='MMD_AT_PLUS_A', **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the interior-point method of
+ [4]_.
+
+ .. deprecated:: 1.9.0
+ `method='interior-point'` will be removed in SciPy 1.11.0.
+ It is replaced by `method='highs'` because the latter is
+ faster and more robust.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+ This is the method-specific documentation for 'interior-point'.
+ :ref:`'highs' `,
+ :ref:`'highs-ds' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+
+ Options
+ -------
+ maxiter : int (default: 1000)
+ The maximum number of iterations of the algorithm.
+ disp : bool (default: False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ presolve : bool (default: True)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ tol : float (default: 1e-8)
+ Termination tolerance to be used for all termination criteria;
+ see [4]_ Section 4.5.
+ autoscale : bool (default: False)
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ rr : bool (default: True)
+ Set to ``False`` to disable automatic redundancy removal.
+ alpha0 : float (default: 0.99995)
+ The maximal step size for Mehrota's predictor-corrector search
+ direction; see :math:`\beta_{3}` of [4]_ Table 8.1.
+ beta : float (default: 0.1)
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
+ when Mehrota's predictor-corrector is not in use (uncommon).
+ sparse : bool (default: False)
+ Set to ``True`` if the problem is to be treated as sparse after
+ presolve. If either ``A_eq`` or ``A_ub`` is sparse,
+ this option will automatically be set ``True``, and the problem
+ will be treated as sparse even during presolve. If your constraint
+ matrices contain mostly zeros and the problem is not very small (less
+ than about 100 constraints or variables), consider setting ``True``
+ or providing ``A_eq`` and ``A_ub`` as sparse arrays.
+ lstsq : bool (default: ``False``)
+ Set to ``True`` if the problem is expected to be very poorly
+ conditioned. This should always be left ``False`` unless severe
+ numerical difficulties are encountered. Leave this at the default
+ unless you receive a warning message suggesting otherwise.
+ sym_pos : bool (default: True)
+ Leave ``True`` if the problem is expected to yield a well conditioned
+ symmetric positive definite normal equation matrix
+ (almost always). Leave this at the default unless you receive
+ a warning message suggesting otherwise.
+ cholesky : bool (default: True)
+ Set to ``True`` if the normal equations are to be solved by explicit
+ Cholesky decomposition followed by explicit forward/backward
+ substitution. This is typically faster for problems
+ that are numerically well-behaved.
+ pc : bool (default: True)
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
+ used. This is almost always (if not always) beneficial.
+ ip : bool (default: False)
+ Set to ``True`` if the improved initial point suggestion due to [4]_
+ Section 4.3 is desired. Whether this is beneficial or not
+ depends on the problem.
+ permc_spec : str (default: 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``, and no SuiteSparse.)
+ A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed in all phases.
+
+
+ Notes
+ -----
+ This method implements the algorithm outlined in [4]_ with ideas from [8]_
+ and a structure inspired by the simpler methods of [6]_.
+
+ The primal-dual path following method begins with initial 'guesses' of
+ the primal and dual variables of the standard form problem and iteratively
+ attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the
+ problem with a gradually reduced logarithmic barrier term added to the
+ objective. This particular implementation uses a homogeneous self-dual
+ formulation, which provides certificates of infeasibility or unboundedness
+ where applicable.
+
+ The default initial point for the primal and dual variables is that
+ defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial
+ point option ``ip=True``), an alternate (potentially improved) starting
+ point can be calculated according to the additional recommendations of
+ [4]_ Section 4.4.
+
+ A search direction is calculated using the predictor-corrector method
+ (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1.
+ (A potential improvement would be to implement the method of multiple
+ corrections described in [4]_ Section 4.2.) In practice, this is
+ accomplished by solving the normal equations, [4]_ Section 5.1 Equations
+ 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations
+ 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of
+ solving the normal equations rather than 8.25 directly is that the
+ matrices involved are symmetric positive definite, so Cholesky
+ decomposition can be used rather than the more expensive LU factorization.
+
+ With default options, the solver used to perform the factorization depends
+ on third-party software availability and the conditioning of the problem.
+
+ For dense problems, solvers are tried in the following order:
+
+ 1. ``scipy.linalg.cho_factor``
+
+ 2. ``scipy.linalg.solve`` with option ``sym_pos=True``
+
+ 3. ``scipy.linalg.solve`` with option ``sym_pos=False``
+
+ 4. ``scipy.linalg.lstsq``
+
+ For sparse problems:
+
+ 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are
+ installed)
+
+ 2. ``scipy.sparse.linalg.factorized`` (if scikit-umfpack and SuiteSparse
+ are installed)
+
+ 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy)
+
+ 4. ``scipy.sparse.linalg.lsqr``
+
+ If the solver fails for any reason, successively more robust (but slower)
+ solvers are attempted in the order indicated. Attempting, failing, and
+ re-starting factorization can be time consuming, so if the problem is
+ numerically challenging, options can be set to bypass solvers that are
+ failing. Setting ``cholesky=False`` skips to solver 2,
+ ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips
+ to solver 4 for both sparse and dense problems.
+
+ Potential improvements for combating issues associated with dense
+ columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and
+ [10]_ Section 4.1-4.2; the latter also discusses the alleviation of
+ accuracy issues associated with the substitution approach to free
+ variables.
+
+ After calculating the search direction, the maximum possible step size
+ that does not activate the non-negativity constraints is calculated, and
+ the smaller of this step size and unity is applied (as in [4]_ Section
+ 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size.
+
+ The new point is tested according to the termination conditions of [4]_
+ Section 4.5. The same tolerance, which can be set using the ``tol`` option,
+ is used for all checks. (A potential improvement would be to expose
+ the different tolerances to be set independently.) If optimality,
+ unboundedness, or infeasibility is detected, the solve procedure
+ terminates; otherwise it repeats.
+
+ Whereas the top level ``linprog`` module expects a problem of form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. The problem
+ is automatically converted to the form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ for solution. That is, the original problem contains equality, upper-bound
+ and variable constraints whereas the method specific solver requires
+ equality constraints and variable non-negativity. ``linprog`` converts the
+ original problem to standard form by converting the simple bounds to upper
+ bound constraints, introducing non-negative slack variables for inequality
+ constraints, and expressing unbounded variables as the difference between
+ two non-negative variables. The problem is converted back to the original
+ form before results are reported.
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [10] Andersen, Erling D., et al. Implementation of interior point
+ methods for large scale linear programming. HEC/Universite de
+ Geneve, 1996.
+ """
+ pass
+
+
+def _linprog_rs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='interior-point', callback=None,
+ x0=None, maxiter=5000, disp=False, presolve=True,
+ tol=1e-12, autoscale=False, rr=True, maxupdate=10,
+ mast=False, pivot="mrc", **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the revised simplex method.
+
+ .. deprecated:: 1.9.0
+ `method='revised simplex'` will be removed in SciPy 1.11.0.
+ It is replaced by `method='highs'` because the latter is
+ faster and more robust.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+ This is the method-specific documentation for 'revised simplex'.
+ :ref:`'highs' `,
+ :ref:`'highs-ds' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'interior-point' ` (default),
+ and :ref:`'simplex' ` (legacy)
+ are also available.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+ x0 : 1-D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ Options
+ -------
+ maxiter : int (default: 5000)
+ The maximum number of iterations to perform in either phase.
+ disp : bool (default: False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ presolve : bool (default: True)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ tol : float (default: 1e-12)
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ autoscale : bool (default: False)
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ rr : bool (default: True)
+ Set to ``False`` to disable automatic redundancy removal.
+ maxupdate : int (default: 10)
+ The maximum number of updates performed on the LU factorization.
+ After this many updates is reached, the basis matrix is factorized
+ from scratch.
+ mast : bool (default: False)
+ Minimize Amortized Solve Time. If enabled, the average time to solve
+ a linear system using the basis factorization is measured. Typically,
+ the average solve time will decrease with each successive solve after
+ initial factorization, as factorization takes much more time than the
+ solve operation (and updates). Eventually, however, the updated
+ factorization becomes sufficiently complex that the average solve time
+ begins to increase. When this is detected, the basis is refactorized
+ from scratch. Enable this option to maximize speed at the risk of
+ nondeterministic behavior. Ignored if ``maxupdate`` is 0.
+ pivot : "mrc" or "bland" (default: "mrc")
+ Pivot rule: Minimum Reduced Cost ("mrc") or Bland's rule ("bland").
+ Choose Bland's rule if iteration limit is reached and cycling is
+ suspected.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ ``5`` : Problem has no constraints; turn presolve on.
+
+ ``6`` : Invalid guess provided.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed in all phases.
+
+
+ Notes
+ -----
+ Method *revised simplex* uses the revised simplex method as described in
+ [9]_, except that a factorization [11]_ of the basis matrix, rather than
+ its inverse, is efficiently maintained and used to solve the linear systems
+ at each iteration of the algorithm.
+
+ References
+ ----------
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [11] Bartels, Richard H. "A stabilization of the simplex method."
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
+ """
+ pass
+
+
+def _linprog_simplex_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='interior-point', callback=None,
+ maxiter=5000, disp=False, presolve=True,
+ tol=1e-12, autoscale=False, rr=True, bland=False,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the tableau-based simplex method.
+
+ .. deprecated:: 1.9.0
+ `method='simplex'` will be removed in SciPy 1.11.0.
+ It is replaced by `method='highs'` because the latter is
+ faster and more robust.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+ This is the method-specific documentation for 'simplex'.
+ :ref:`'highs' `,
+ :ref:`'highs-ds' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'interior-point' ` (default),
+ and :ref:`'revised simplex' `
+ are also available.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+
+ Options
+ -------
+ maxiter : int (default: 5000)
+ The maximum number of iterations to perform in either phase.
+ disp : bool (default: False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ presolve : bool (default: True)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ tol : float (default: 1e-12)
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ autoscale : bool (default: False)
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ rr : bool (default: True)
+ Set to ``False`` to disable automatic redundancy removal.
+ bland : bool
+ If True, use Bland's anti-cycling rule [3]_ to choose pivots to
+ prevent cycling. If False, choose pivots which should lead to a
+ converged solution more quickly. The latter method is subject to
+ cycling (non-convergence) in rare instances.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed in all phases.
+
+ References
+ ----------
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
+ """
+ pass
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_highs.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_highs.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bb05ace496abd5a3df53a7df89fa3c6ed80dac0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_highs.py
@@ -0,0 +1,422 @@
+"""HiGHS Linear Optimization Methods
+
+Interface to HiGHS linear optimization software.
+https://highs.dev/
+
+.. versionadded:: 1.5.0
+
+References
+----------
+.. [1] Q. Huangfu and J.A.J. Hall. "Parallelizing the dual revised simplex
+ method." Mathematical Programming Computation, 10 (1), 119-142,
+ 2018. :doi:`10.1007/s12532-017-0130-5`.
+
+"""
+
+import inspect
+import numpy as np
+from ._optimize import OptimizeWarning, OptimizeResult
+from warnings import warn
+from ._highspy._highs_wrapper import _highs_wrapper
+from ._highspy._core import(
+ kHighsInf,
+ HighsDebugLevel,
+ ObjSense,
+ HighsModelStatus,
+ simplex_constants as s_c, # [1]
+)
+from scipy.sparse import csc_array, vstack, issparse
+
+# [1]: Directly importing from "._highspy._core.simplex_constants"
+# causes problems when reloading.
+# See https://github.com/scipy/scipy/pull/22869 for details.
+
+def _highs_to_scipy_status_message(highs_status, highs_message):
+ """Converts HiGHS status number/message to SciPy status number/message"""
+
+ scipy_statuses_messages = {
+ None: (4, "HiGHS did not provide a status code. "),
+ HighsModelStatus.kNotset: (4, ""),
+ HighsModelStatus.kLoadError: (4, ""),
+ HighsModelStatus.kModelError: (2, ""),
+ HighsModelStatus.kPresolveError: (4, ""),
+ HighsModelStatus.kSolveError: (4, ""),
+ HighsModelStatus.kPostsolveError: (4, ""),
+ HighsModelStatus.kModelEmpty: (4, ""),
+ HighsModelStatus.kObjectiveBound: (4, ""),
+ HighsModelStatus.kObjectiveTarget: (4, ""),
+ HighsModelStatus.kOptimal: (0, "Optimization terminated successfully. "),
+ HighsModelStatus.kTimeLimit: (1, "Time limit reached. "),
+ HighsModelStatus.kIterationLimit: (1, "Iteration limit reached. "),
+ HighsModelStatus.kInfeasible: (2, "The problem is infeasible. "),
+ HighsModelStatus.kUnbounded: (3, "The problem is unbounded. "),
+ HighsModelStatus.kUnboundedOrInfeasible: (4, "The problem is unbounded "
+ "or infeasible. ")}
+ unrecognized = (4, "The HiGHS status code was not recognized. ")
+ scipy_status, scipy_message = (
+ scipy_statuses_messages.get(highs_status, unrecognized))
+ hstat = int(highs_status) if highs_status is not None else None
+ scipy_message = (f"{scipy_message}"
+ f"(HiGHS Status {hstat}: {highs_message})")
+ return scipy_status, scipy_message
+
+
+def _replace_inf(x):
+ # Replace `np.inf` with kHighsInf
+ infs = np.isinf(x)
+ with np.errstate(invalid="ignore"):
+ x[infs] = np.sign(x[infs])*kHighsInf
+ return x
+
+
+def _convert_to_highs_enum(option, option_str, choices):
+ # If option is in the choices we can look it up, if not use
+ # the default value taken from function signature and warn:
+ try:
+ return choices[option.lower()]
+ except AttributeError:
+ return choices[option]
+ except KeyError:
+ sig = inspect.signature(_linprog_highs)
+ default_str = sig.parameters[option_str].default
+ warn(f"Option {option_str} is {option}, but only values in "
+ f"{set(choices.keys())} are allowed. Using default: "
+ f"{default_str}.",
+ OptimizeWarning, stacklevel=3)
+ return choices[default_str]
+
+
+def _linprog_highs(lp, solver, time_limit=None, presolve=True,
+ disp=False, maxiter=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ ipm_optimality_tolerance=None,
+ simplex_dual_edge_weight_strategy=None,
+ mip_rel_gap=None,
+ mip_max_nodes=None,
+ **unknown_options):
+ r"""
+ Solve the following linear programming problem using one of the HiGHS
+ solvers:
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ lp : _LPProblem
+ A ``scipy.optimize._linprog_util._LPProblem`` ``namedtuple``.
+ solver : "ipm" or "simplex" or None
+ Which HiGHS solver to use. If ``None``, "simplex" will be used.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase. For
+ ``solver='ipm'``, this does not include the number of crossover
+ iterations. Default is the largest possible value for an ``int``
+ on the platform.
+ disp : bool
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration; default ``False``.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem; default is
+ the largest possible value for a ``double`` on the platform.
+ presolve : bool
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if presolve is
+ to be disabled.
+ dual_feasibility_tolerance : double
+ Dual feasibility tolerance. Default is 1e-07.
+ The minimum of this and ``primal_feasibility_tolerance``
+ is used for the feasibility tolerance when ``solver='ipm'``.
+ primal_feasibility_tolerance : double
+ Primal feasibility tolerance. Default is 1e-07.
+ The minimum of this and ``dual_feasibility_tolerance``
+ is used for the feasibility tolerance when ``solver='ipm'``.
+ ipm_optimality_tolerance : double
+ Optimality tolerance for ``solver='ipm'``. Default is 1e-08.
+ Minimum possible value is 1e-12 and must be smaller than the largest
+ possible value for a ``double`` on the platform.
+ simplex_dual_edge_weight_strategy : str (default: None)
+ Strategy for simplex dual edge weights. The default, ``None``,
+ automatically selects one of the following.
+
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
+ negative reduced cost.
+
+ ``'devex'`` uses the strategy described in [15]_.
+
+ ``steepest`` uses the exact steepest edge strategy as described in
+ [16]_.
+
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
+ until the computation is too costly or inexact and then switches to
+ the devex method.
+
+ Currently, using ``None`` always selects ``'steepest-devex'``, but this
+ may change as new options become available.
+
+ mip_max_nodes : int
+ The maximum number of nodes allotted to solve the problem; default is
+ the largest possible value for a ``HighsInt`` on the platform.
+ Ignored if not using the MIP solver.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ sol : dict
+ A dictionary consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed.
+ For ``solver='simplex'``, this includes iterations in all
+ phases. For ``solver='ipm'``, this does not include
+ crossover iterations.
+ crossover_nit : int
+ The number of primal/dual pushes performed during the
+ crossover routine for ``solver='ipm'``. This is ``0``
+ for ``solver='simplex'``.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ mip_node_count : int
+ The number of subproblems or "nodes" solved by the MILP
+ solver. Only present when `integrality` is not `None`.
+
+ mip_dual_bound : float
+ The MILP solver's final estimate of the lower bound on the
+ optimal solution. Only present when `integrality` is not
+ `None`.
+
+ mip_gap : float
+ The difference between the final objective function value
+ and the final dual bound, scaled by the final objective
+ function value. Only present when `integrality` is not
+ `None`.
+
+ Notes
+ -----
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
+ Mathematical programming 5.1 (1973): 1-28.
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
+ """
+ if unknown_options:
+ message = (f"Unrecognized options detected: {unknown_options}. "
+ "These will be passed to HiGHS verbatim.")
+ warn(message, OptimizeWarning, stacklevel=3)
+
+ # Map options to HiGHS enum values
+ simplex_dual_edge_weight_strategy_enum = _convert_to_highs_enum(
+ simplex_dual_edge_weight_strategy,
+ 'simplex_dual_edge_weight_strategy',
+ choices={'dantzig': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDantzig,
+ 'devex': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDevex,
+ 'steepest-devex': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyChoose,
+ 'steepest': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategySteepestEdge,
+ None: None})
+
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
+
+ lb, ub = bounds.T.copy() # separate bounds, copy->C-cntgs
+ # highs_wrapper solves LHS <= A*x <= RHS, not equality constraints
+ with np.errstate(invalid="ignore"):
+ lhs_ub = -np.ones_like(b_ub)*np.inf # LHS of UB constraints is -inf
+ rhs_ub = b_ub # RHS of UB constraints is b_ub
+ lhs_eq = b_eq # Equality constraint is inequality
+ rhs_eq = b_eq # constraint with LHS=RHS
+ lhs = np.concatenate((lhs_ub, lhs_eq))
+ rhs = np.concatenate((rhs_ub, rhs_eq))
+
+ if issparse(A_ub) or issparse(A_eq):
+ A = vstack((A_ub, A_eq))
+ else:
+ A = np.vstack((A_ub, A_eq))
+ A = csc_array(A)
+
+ options = {
+ 'presolve': presolve,
+ 'sense': ObjSense.kMinimize,
+ 'solver': solver,
+ 'time_limit': time_limit,
+ 'highs_debug_level': HighsDebugLevel.kHighsDebugLevelNone,
+ 'dual_feasibility_tolerance': dual_feasibility_tolerance,
+ 'ipm_optimality_tolerance': ipm_optimality_tolerance,
+ 'log_to_console': disp,
+ 'mip_max_nodes': mip_max_nodes,
+ 'output_flag': disp,
+ 'primal_feasibility_tolerance': primal_feasibility_tolerance,
+ 'simplex_dual_edge_weight_strategy':
+ simplex_dual_edge_weight_strategy_enum,
+ 'simplex_strategy': s_c.SimplexStrategy.kSimplexStrategyDual,
+ 'ipm_iteration_limit': maxiter,
+ 'simplex_iteration_limit': maxiter,
+ 'mip_rel_gap': mip_rel_gap,
+ }
+ options.update(unknown_options)
+
+ # np.inf doesn't work; use very large constant
+ rhs = _replace_inf(rhs)
+ lhs = _replace_inf(lhs)
+ lb = _replace_inf(lb)
+ ub = _replace_inf(ub)
+
+ if integrality is None or np.sum(integrality) == 0:
+ integrality = np.empty(0)
+ else:
+ integrality = np.array(integrality)
+
+ res = _highs_wrapper(c, A.indptr, A.indices, A.data, lhs, rhs,
+ lb, ub, integrality.astype(np.uint8), options)
+
+ # HiGHS represents constraints as lhs/rhs, so
+ # Ax + s = b => Ax = b - s
+ # and we need to split up s by A_ub and A_eq
+ if 'slack' in res:
+ slack = res['slack']
+ con = np.array(slack[len(b_ub):])
+ slack = np.array(slack[:len(b_ub)])
+ else:
+ slack, con = None, None
+
+ # lagrange multipliers for equalities/inequalities and upper/lower bounds
+ if 'lambda' in res:
+ lamda = res['lambda']
+ marg_ineqlin = np.array(lamda[:len(b_ub)])
+ marg_eqlin = np.array(lamda[len(b_ub):])
+ marg_upper = np.array(res['marg_bnds'][1, :])
+ marg_lower = np.array(res['marg_bnds'][0, :])
+ else:
+ marg_ineqlin, marg_eqlin = None, None
+ marg_upper, marg_lower = None, None
+
+ # this needs to be updated if we start choosing the solver intelligently
+
+ # Convert to scipy-style status and message
+ highs_status = res.get('status', None)
+ highs_message = res.get('message', None)
+ status, message = _highs_to_scipy_status_message(highs_status,
+ highs_message)
+
+ x = res['x'] # is None if not set
+ sol = {'x': x,
+ 'slack': slack,
+ 'con': con,
+ 'ineqlin': OptimizeResult({
+ 'residual': slack,
+ 'marginals': marg_ineqlin,
+ }),
+ 'eqlin': OptimizeResult({
+ 'residual': con,
+ 'marginals': marg_eqlin,
+ }),
+ 'lower': OptimizeResult({
+ 'residual': None if x is None else x - lb,
+ 'marginals': marg_lower,
+ }),
+ 'upper': OptimizeResult({
+ 'residual': None if x is None else ub - x,
+ 'marginals': marg_upper
+ }),
+ 'fun': res.get('fun'),
+ 'status': status,
+ 'success': res['status'] == HighsModelStatus.kOptimal,
+ 'message': message,
+ 'nit': res.get('simplex_nit', 0) or res.get('ipm_nit', 0),
+ 'crossover_nit': res.get('crossover_nit'),
+ }
+
+ if np.any(x) and integrality is not None:
+ sol.update({
+ 'mip_node_count': res.get('mip_node_count', 0),
+ 'mip_dual_bound': res.get('mip_dual_bound', 0.0),
+ 'mip_gap': res.get('mip_gap', 0.0),
+ })
+
+ return sol
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_ip.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_ip.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6d035632e0039564c89d03a93397401f9f13ce6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_ip.py
@@ -0,0 +1,1141 @@
+"""Interior-point method for linear programming
+
+The *interior-point* method uses the primal-dual path following algorithm
+outlined in [1]_. This algorithm supports sparse constraint matrices and
+is typically faster than the simplex methods, especially for large, sparse
+problems. Note, however, that the solution returned may be slightly less
+accurate than those of the simplex methods and will not, in general,
+correspond with a vertex of the polytope defined by the constraints.
+
+ .. versionadded:: 1.0.0
+
+References
+----------
+.. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+"""
+# Author: Matt Haberland
+
+import numpy as np
+import scipy as sp
+import scipy.sparse as sps
+from warnings import warn
+from scipy.linalg import LinAlgError
+from ._optimize import OptimizeWarning, OptimizeResult, _check_unknown_options
+from ._linprog_util import _postsolve
+has_umfpack = True
+has_cholmod = True
+try:
+ import sksparse # noqa: F401
+ from sksparse.cholmod import cholesky as cholmod # noqa: F401
+ from sksparse.cholmod import analyze as cholmod_analyze
+ from sksparse.cholmod import CholmodTypeConversionWarning
+ from warnings import catch_warnings
+except ImportError:
+ has_cholmod = False
+try:
+ import scikits.umfpack # test whether to use factorized # noqa: F401
+except ImportError:
+ has_umfpack = False
+
+
+def _get_solver(M, sparse=False, lstsq=False, sym_pos=True,
+ cholesky=True, permc_spec='MMD_AT_PLUS_A'):
+ """
+ Given solver options, return a handle to the appropriate linear system
+ solver.
+
+ Parameters
+ ----------
+ M : 2-D array
+ As defined in [4] Equation 8.31
+ sparse : bool (default = False)
+ True if the system to be solved is sparse. This is typically set
+ True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
+ lstsq : bool (default = False)
+ True if the system is ill-conditioned and/or (nearly) singular and
+ thus a more robust least-squares solver is desired. This is sometimes
+ needed as the solution is approached.
+ sym_pos : bool (default = True)
+ True if the system matrix is symmetric positive definite
+ Sometimes this needs to be set false as the solution is approached,
+ even when the system should be symmetric positive definite, due to
+ numerical difficulties.
+ cholesky : bool (default = True)
+ True if the system is to be solved by Cholesky, rather than LU,
+ decomposition. This is typically faster unless the problem is very
+ small or prone to numerical difficulties.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ Sparsity preservation strategy used by SuperLU. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ See SuperLU documentation.
+
+ Returns
+ -------
+ solve : function
+ Handle to the appropriate solver function
+
+ """
+ try:
+ if sparse:
+ if lstsq:
+ def solve(r, sym_pos=False):
+ return sps.linalg.lsqr(M, r)[0]
+ elif cholesky:
+ # TODO: revert this suppress_warning once the warning bug fix in
+ # sksparse is merged/released
+ # Suppress spurious warning bug from sksparse with csc_array gh-22089
+ # try:
+ # # Will raise an exception in the first call,
+ # # or when the matrix changes due to a new problem
+ # _get_solver.cholmod_factor.cholesky_inplace(M)
+ # except Exception:
+ # _get_solver.cholmod_factor = cholmod_analyze(M)
+ # _get_solver.cholmod_factor.cholesky_inplace(M)
+ with catch_warnings(
+ action='ignore', category=CholmodTypeConversionWarning
+ ):
+ try:
+ # Will raise an exception in the first call,
+ # or when the matrix changes due to a new problem
+ _get_solver.cholmod_factor.cholesky_inplace(M)
+ except Exception:
+ _get_solver.cholmod_factor = cholmod_analyze(M)
+ _get_solver.cholmod_factor.cholesky_inplace(M)
+ solve = _get_solver.cholmod_factor
+ else:
+ if has_umfpack and sym_pos:
+ solve = sps.linalg.factorized(M)
+ else: # factorized doesn't pass permc_spec
+ solve = sps.linalg.splu(M, permc_spec=permc_spec).solve
+
+ else:
+ if lstsq: # sometimes necessary as solution is approached
+ def solve(r):
+ return sp.linalg.lstsq(M, r)[0]
+ elif cholesky:
+ L = sp.linalg.cho_factor(M)
+
+ def solve(r):
+ return sp.linalg.cho_solve(L, r)
+ else:
+ # this seems to cache the matrix factorization, so solving
+ # with multiple right hand sides is much faster
+ def solve(r, sym_pos=sym_pos):
+ if sym_pos:
+ return sp.linalg.solve(M, r, assume_a="pos")
+ else:
+ return sp.linalg.solve(M, r)
+ # There are many things that can go wrong here, and it's hard to say
+ # what all of them are. It doesn't really matter: if the matrix can't be
+ # factorized, return None. get_solver will be called again with different
+ # inputs, and a new routine will try to factorize the matrix.
+ except KeyboardInterrupt:
+ raise
+ except Exception:
+ return None
+ return solve
+
+
+def _get_delta(A, b, c, x, y, z, tau, kappa, gamma, eta, sparse=False,
+ lstsq=False, sym_pos=True, cholesky=True, pc=True, ip=False,
+ permc_spec='MMD_AT_PLUS_A'):
+ """
+ Given standard form problem defined by ``A``, ``b``, and ``c``;
+ current variable estimates ``x``, ``y``, ``z``, ``tau``, and ``kappa``;
+ algorithmic parameters ``gamma and ``eta;
+ and options ``sparse``, ``lstsq``, ``sym_pos``, ``cholesky``, ``pc``
+ (predictor-corrector), and ``ip`` (initial point improvement),
+ get the search direction for increments to the variable estimates.
+
+ Parameters
+ ----------
+ As defined in [4], except:
+ sparse : bool
+ True if the system to be solved is sparse. This is typically set
+ True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
+ lstsq : bool
+ True if the system is ill-conditioned and/or (nearly) singular and
+ thus a more robust least-squares solver is desired. This is sometimes
+ needed as the solution is approached.
+ sym_pos : bool
+ True if the system matrix is symmetric positive definite
+ Sometimes this needs to be set false as the solution is approached,
+ even when the system should be symmetric positive definite, due to
+ numerical difficulties.
+ cholesky : bool
+ True if the system is to be solved by Cholesky, rather than LU,
+ decomposition. This is typically faster unless the problem is very
+ small or prone to numerical difficulties.
+ pc : bool
+ True if the predictor-corrector method of Mehrota is to be used. This
+ is almost always (if not always) beneficial. Even though it requires
+ the solution of an additional linear system, the factorization
+ is typically (implicitly) reused so solution is efficient, and the
+ number of algorithm iterations is typically reduced.
+ ip : bool
+ True if the improved initial point suggestion due to [4] section 4.3
+ is desired. It's unclear whether this is beneficial.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``.) A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+
+ Returns
+ -------
+ Search directions as defined in [4]
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ if A.shape[0] == 0:
+ # If there are no constraints, some solvers fail (understandably)
+ # rather than returning empty solution. This gets the job done.
+ lstsq, sym_pos, cholesky = False, True, False
+ n_x = len(x)
+
+ # [4] Equation 8.8
+ r_P = b * tau - A.dot(x)
+ r_D = c * tau - A.T.dot(y) - z
+ r_G = c.dot(x) - b.transpose().dot(y) + kappa
+ mu = (x.dot(z) + tau * kappa) / (n_x + 1)
+
+ # Assemble M from [4] Equation 8.31
+ Dinv = x / z
+
+ if sparse:
+ M = A.dot(sps.diags_array(Dinv, format="csc").dot(A.T))
+ else:
+ M = A.dot(Dinv.reshape(-1, 1) * A.T)
+ solve = _get_solver(M, sparse, lstsq, sym_pos, cholesky, permc_spec)
+
+ # pc: "predictor-corrector" [4] Section 4.1
+ # In development this option could be turned off
+ # but it always seems to improve performance substantially
+ n_corrections = 1 if pc else 0
+
+ i = 0
+ alpha, d_x, d_z, d_tau, d_kappa = 0, 0, 0, 0, 0
+ while i <= n_corrections:
+ # Reference [4] Eq. 8.6
+ rhatp = eta(gamma) * r_P
+ rhatd = eta(gamma) * r_D
+ rhatg = eta(gamma) * r_G
+
+ # Reference [4] Eq. 8.7
+ rhatxs = gamma * mu - x * z
+ rhattk = gamma * mu - tau * kappa
+
+ if i == 1:
+ if ip: # if the correction is to get "initial point"
+ # Reference [4] Eq. 8.23
+ rhatxs = ((1 - alpha) * gamma * mu -
+ x * z - alpha**2 * d_x * d_z)
+ rhattk = ((1 - alpha) * gamma * mu -
+ tau * kappa -
+ alpha**2 * d_tau * d_kappa)
+ else: # if the correction is for "predictor-corrector"
+ # Reference [4] Eq. 8.13
+ rhatxs -= d_x * d_z
+ rhattk -= d_tau * d_kappa
+
+ # sometimes numerical difficulties arise as the solution is approached
+ # this loop tries to solve the equations using a sequence of functions
+ # for solve. For dense systems, the order is:
+ # 1. scipy.linalg.cho_factor/scipy.linalg.cho_solve,
+ # 2. scipy.linalg.solve w/ sym_pos = True,
+ # 3. scipy.linalg.solve w/ sym_pos = False, and if all else fails
+ # 4. scipy.linalg.lstsq
+ # For sparse systems, the order is:
+ # 1. sksparse.cholmod.cholesky (if available)
+ # 2. scipy.sparse.linalg.factorized (if umfpack available)
+ # 3. scipy.sparse.linalg.splu
+ # 4. scipy.sparse.linalg.lsqr
+ solved = False
+ while not solved:
+ try:
+ # [4] Equation 8.28
+ p, q = _sym_solve(Dinv, A, c, b, solve)
+ # [4] Equation 8.29
+ u, v = _sym_solve(Dinv, A, rhatd -
+ (1 / x) * rhatxs, rhatp, solve)
+ if np.any(np.isnan(p)) or np.any(np.isnan(q)):
+ raise LinAlgError
+ solved = True
+ except (LinAlgError, ValueError, TypeError) as e:
+ # Usually this doesn't happen. If it does, it happens when
+ # there are redundant constraints or when approaching the
+ # solution. If so, change solver.
+ if cholesky:
+ cholesky = False
+ warn(
+ "Solving system with option 'cholesky':True "
+ "failed. It is normal for this to happen "
+ "occasionally, especially as the solution is "
+ "approached. However, if you see this frequently, "
+ "consider setting option 'cholesky' to False.",
+ OptimizeWarning, stacklevel=5)
+ elif sym_pos:
+ sym_pos = False
+ warn(
+ "Solving system with option 'sym_pos':True "
+ "failed. It is normal for this to happen "
+ "occasionally, especially as the solution is "
+ "approached. However, if you see this frequently, "
+ "consider setting option 'sym_pos' to False.",
+ OptimizeWarning, stacklevel=5)
+ elif not lstsq:
+ lstsq = True
+ warn(
+ "Solving system with option 'sym_pos':False "
+ "failed. This may happen occasionally, "
+ "especially as the solution is "
+ "approached. However, if you see this frequently, "
+ "your problem may be numerically challenging. "
+ "If you cannot improve the formulation, consider "
+ "setting 'lstsq' to True. Consider also setting "
+ "`presolve` to True, if it is not already.",
+ OptimizeWarning, stacklevel=5)
+ else:
+ raise e
+ solve = _get_solver(M, sparse, lstsq, sym_pos,
+ cholesky, permc_spec)
+ # [4] Results after 8.29
+ d_tau = ((rhatg + 1 / tau * rhattk - (-c.dot(u) + b.dot(v))) /
+ (1 / tau * kappa + (-c.dot(p) + b.dot(q))))
+ d_x = u + p * d_tau
+ d_y = v + q * d_tau
+
+ # [4] Relations between after 8.25 and 8.26
+ d_z = (1 / x) * (rhatxs - z * d_x)
+ d_kappa = 1 / tau * (rhattk - kappa * d_tau)
+
+ # [4] 8.12 and "Let alpha be the maximal possible step..." before 8.23
+ alpha = _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, 1)
+ if ip: # initial point - see [4] 4.4
+ gamma = 10
+ else: # predictor-corrector, [4] definition after 8.12
+ beta1 = 0.1 # [4] pg. 220 (Table 8.1)
+ gamma = (1 - alpha)**2 * min(beta1, (1 - alpha))
+ i += 1
+
+ return d_x, d_y, d_z, d_tau, d_kappa
+
+
+def _sym_solve(Dinv, A, r1, r2, solve):
+ """
+ An implementation of [4] equation 8.31 and 8.32
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ # [4] 8.31
+ r = r2 + A.dot(Dinv * r1)
+ v = solve(r)
+ # [4] 8.32
+ u = Dinv * (A.T.dot(v) - r1)
+ return u, v
+
+
+def _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, alpha0):
+ """
+ An implementation of [4] equation 8.21
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ # [4] 4.3 Equation 8.21, ignoring 8.20 requirement
+ # same step is taken in primal and dual spaces
+ # alpha0 is basically beta3 from [4] Table 8.1, but instead of beta3
+ # the value 1 is used in Mehrota corrector and initial point correction
+ i_x = d_x < 0
+ i_z = d_z < 0
+ alpha_x = alpha0 * np.min(x[i_x] / -d_x[i_x]) if np.any(i_x) else 1
+ alpha_tau = alpha0 * tau / -d_tau if d_tau < 0 else 1
+ alpha_z = alpha0 * np.min(z[i_z] / -d_z[i_z]) if np.any(i_z) else 1
+ alpha_kappa = alpha0 * kappa / -d_kappa if d_kappa < 0 else 1
+ alpha = np.min([1, alpha_x, alpha_tau, alpha_z, alpha_kappa])
+ return alpha
+
+
+def _get_message(status):
+ """
+ Given problem status code, return a more detailed message.
+
+ Parameters
+ ----------
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ Returns
+ -------
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ """
+ messages = (
+ ["Optimization terminated successfully.",
+ "The iteration limit was reached before the algorithm converged.",
+ "The algorithm terminated successfully and determined that the "
+ "problem is infeasible.",
+ "The algorithm terminated successfully and determined that the "
+ "problem is unbounded.",
+ "Numerical difficulties were encountered before the problem "
+ "converged. Please check your problem formulation for errors, "
+ "independence of linear equality constraints, and reasonable "
+ "scaling and matrix condition numbers. If you continue to "
+ "encounter this error, please submit a bug report."
+ ])
+ return messages[status]
+
+
+def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha):
+ """
+ An implementation of [4] Equation 8.9
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ x = x + alpha * d_x
+ tau = tau + alpha * d_tau
+ z = z + alpha * d_z
+ kappa = kappa + alpha * d_kappa
+ y = y + alpha * d_y
+ return x, y, z, tau, kappa
+
+
+def _get_blind_start(shape):
+ """
+ Return the starting point from [4] 4.4
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ m, n = shape
+ x0 = np.ones(n)
+ y0 = np.zeros(m)
+ z0 = np.ones(n)
+ tau0 = 1
+ kappa0 = 1
+ return x0, y0, z0, tau0, kappa0
+
+
+def _indicators(A, b, c, c0, x, y, z, tau, kappa):
+ """
+ Implementation of several equations from [4] used as indicators of
+ the status of optimization.
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+
+ # residuals for termination are relative to initial values
+ x0, y0, z0, tau0, kappa0 = _get_blind_start(A.shape)
+
+ # See [4], Section 4 - The Homogeneous Algorithm, Equation 8.8
+ def r_p(x, tau):
+ return b * tau - A.dot(x)
+
+ def r_d(y, z, tau):
+ return c * tau - A.T.dot(y) - z
+
+ def r_g(x, y, kappa):
+ return kappa + c.dot(x) - b.dot(y)
+
+ # np.dot unpacks if they are arrays of size one
+ def mu(x, tau, z, kappa):
+ return (x.dot(z) + np.dot(tau, kappa)) / (len(x) + 1)
+
+ obj = c.dot(x / tau) + c0
+
+ def norm(a):
+ return np.linalg.norm(a)
+
+ # See [4], Section 4.5 - The Stopping Criteria
+ r_p0 = r_p(x0, tau0)
+ r_d0 = r_d(y0, z0, tau0)
+ r_g0 = r_g(x0, y0, kappa0)
+ mu_0 = mu(x0, tau0, z0, kappa0)
+ rho_A = norm(c.T.dot(x) - b.T.dot(y)) / (tau + norm(b.T.dot(y)))
+ rho_p = norm(r_p(x, tau)) / max(1, norm(r_p0))
+ rho_d = norm(r_d(y, z, tau)) / max(1, norm(r_d0))
+ rho_g = norm(r_g(x, y, kappa)) / max(1, norm(r_g0))
+ rho_mu = mu(x, tau, z, kappa) / mu_0
+ return rho_p, rho_d, rho_A, rho_g, rho_mu, obj
+
+
+def _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj, header=False):
+ """
+ Print indicators of optimization status to the console.
+
+ Parameters
+ ----------
+ rho_p : float
+ The (normalized) primal feasibility, see [4] 4.5
+ rho_d : float
+ The (normalized) dual feasibility, see [4] 4.5
+ rho_g : float
+ The (normalized) duality gap, see [4] 4.5
+ alpha : float
+ The step size, see [4] 4.3
+ rho_mu : float
+ The (normalized) path parameter, see [4] 4.5
+ obj : float
+ The objective function value of the current iterate
+ header : bool
+ True if a header is to be printed
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ if header:
+ print("Primal Feasibility ",
+ "Dual Feasibility ",
+ "Duality Gap ",
+ "Step ",
+ "Path Parameter ",
+ "Objective ")
+
+ # no clue why this works
+ fmt = '{0:<20.13}{1:<20.13}{2:<20.13}{3:<17.13}{4:<20.13}{5:<20.13}'
+ print(fmt.format(
+ float(rho_p),
+ float(rho_d),
+ float(rho_g),
+ alpha if isinstance(alpha, str) else float(alpha),
+ float(rho_mu),
+ float(obj)))
+
+
+def _ip_hsd(A, b, c, c0, alpha0, beta, maxiter, disp, tol, sparse, lstsq,
+ sym_pos, cholesky, pc, ip, permc_spec, callback, postsolve_args):
+ r"""
+ Solve a linear programming problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ using the interior point method of [4].
+
+ Parameters
+ ----------
+ A : 2-D array
+ 2-D array such that ``A @ x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the RHS of each equality constraint
+ (row) in ``A`` (for standard form problem).
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized (for
+ standard form problem).
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Purely for display.)
+ alpha0 : float
+ The maximal step size for Mehrota's predictor-corrector search
+ direction; see :math:`\beta_3`of [4] Table 8.1
+ beta : float
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
+ maxiter : int
+ The maximum number of iterations of the algorithm.
+ disp : bool
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ tol : float
+ Termination tolerance; see [4]_ Section 4.5.
+ sparse : bool
+ Set to ``True`` if the problem is to be treated as sparse. However,
+ the inputs ``A_eq`` and ``A_ub`` should nonetheless be provided as
+ (dense) arrays rather than sparse matrices.
+ lstsq : bool
+ Set to ``True`` if the problem is expected to be very poorly
+ conditioned. This should always be left as ``False`` unless severe
+ numerical difficulties are frequently encountered, and a better option
+ would be to improve the formulation of the problem.
+ sym_pos : bool
+ Leave ``True`` if the problem is expected to yield a well conditioned
+ symmetric positive definite normal equation matrix (almost always).
+ cholesky : bool
+ Set to ``True`` if the normal equations are to be solved by explicit
+ Cholesky decomposition followed by explicit forward/backward
+ substitution. This is typically faster for moderate, dense problems
+ that are numerically well-behaved.
+ pc : bool
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
+ used. This is almost always (if not always) beneficial.
+ ip : bool
+ Set to ``True`` if the improved initial point suggestion due to [4]_
+ Section 4.3 is desired. It's unclear whether this is beneficial.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``.) A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector
+ fun : float
+ Current value of the objective function
+ success : bool
+ True only when an algorithm has completed successfully,
+ so this is always False as the callback function is called
+ only while the algorithm is still iterating.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``
+ phase : int
+ The phase of the algorithm being executed. This is always
+ 1 for the interior-point method because it has only one phase.
+ status : int
+ For revised simplex, this is always 0 because if a different
+ status is detected, the algorithm terminates.
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Returns
+ -------
+ x_hat : float
+ Solution vector (for standard form problem).
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at:
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+
+ """
+
+ iteration = 0
+
+ # default initial point
+ x, y, z, tau, kappa = _get_blind_start(A.shape)
+
+ # first iteration is special improvement of initial point
+ ip = ip if pc else False
+
+ # [4] 4.5
+ rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators(
+ A, b, c, c0, x, y, z, tau, kappa)
+ go = rho_p > tol or rho_d > tol or rho_A > tol # we might get lucky : )
+
+ if disp:
+ _display_iter(rho_p, rho_d, rho_g, "-", rho_mu, obj, header=True)
+ if callback is not None:
+ x_o, fun, slack, con = _postsolve(x/tau, postsolve_args)
+ res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
+ 'con': con, 'nit': iteration, 'phase': 1,
+ 'complete': False, 'status': 0,
+ 'message': "", 'success': False})
+ callback(res)
+
+ status = 0
+ message = "Optimization terminated successfully."
+
+ if sparse:
+ A = sps.csc_array(A)
+
+ while go:
+
+ iteration += 1
+
+ if ip: # initial point
+ # [4] Section 4.4
+ gamma = 1
+
+ def eta(g):
+ return 1
+ else:
+ # gamma = 0 in predictor step according to [4] 4.1
+ # if predictor/corrector is off, use mean of complementarity [6]
+ # 5.1 / [4] Below Figure 10-4
+ gamma = 0 if pc else beta * np.mean(z * x)
+ # [4] Section 4.1
+
+ def eta(g=gamma):
+ return 1 - g
+
+ try:
+ # Solve [4] 8.6 and 8.7/8.13/8.23
+ d_x, d_y, d_z, d_tau, d_kappa = _get_delta(
+ A, b, c, x, y, z, tau, kappa, gamma, eta,
+ sparse, lstsq, sym_pos, cholesky, pc, ip, permc_spec)
+
+ if ip: # initial point
+ # [4] 4.4
+ # Formula after 8.23 takes a full step regardless if this will
+ # take it negative
+ alpha = 1.0
+ x, y, z, tau, kappa = _do_step(
+ x, y, z, tau, kappa, d_x, d_y,
+ d_z, d_tau, d_kappa, alpha)
+ x[x < 1] = 1
+ z[z < 1] = 1
+ tau = max(1, tau)
+ kappa = max(1, kappa)
+ ip = False # done with initial point
+ else:
+ # [4] Section 4.3
+ alpha = _get_step(x, d_x, z, d_z, tau,
+ d_tau, kappa, d_kappa, alpha0)
+ # [4] Equation 8.9
+ x, y, z, tau, kappa = _do_step(
+ x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha)
+
+ except (LinAlgError, FloatingPointError,
+ ValueError, ZeroDivisionError):
+ # this can happen when sparse solver is used and presolve
+ # is turned off. Also observed ValueError in AppVeyor Python 3.6
+ # Win32 build (PR #8676). I've never seen it otherwise.
+ status = 4
+ message = _get_message(status)
+ break
+
+ # [4] 4.5
+ rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators(
+ A, b, c, c0, x, y, z, tau, kappa)
+ go = rho_p > tol or rho_d > tol or rho_A > tol
+
+ if disp:
+ _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj)
+ if callback is not None:
+ x_o, fun, slack, con = _postsolve(x/tau, postsolve_args)
+ res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
+ 'con': con, 'nit': iteration, 'phase': 1,
+ 'complete': False, 'status': 0,
+ 'message': "", 'success': False})
+ callback(res)
+
+ # [4] 4.5
+ inf1 = (rho_p < tol and rho_d < tol and rho_g < tol and tau < tol *
+ max(1, kappa))
+ inf2 = rho_mu < tol and tau < tol * min(1, kappa)
+ if inf1 or inf2:
+ # [4] Lemma 8.4 / Theorem 8.3
+ if b.transpose().dot(y) > tol:
+ status = 2
+ else: # elif c.T.dot(x) < tol: ? Probably not necessary.
+ status = 3
+ message = _get_message(status)
+ break
+ elif iteration >= maxiter:
+ status = 1
+ message = _get_message(status)
+ break
+
+ x_hat = x / tau
+ # [4] Statement after Theorem 8.2
+ return x_hat, status, message, iteration
+
+
+def _linprog_ip(c, c0, A, b, callback, postsolve_args, maxiter=1000, tol=1e-8,
+ disp=False, alpha0=.99995, beta=0.1, sparse=False, lstsq=False,
+ sym_pos=True, cholesky=None, pc=True, ip=False,
+ permc_spec='MMD_AT_PLUS_A', **unknown_options):
+ r"""
+ Minimize a linear objective function subject to linear
+ equality and non-negativity constraints using the interior point method
+ of [4]_. Linear programming is intended to solve problems
+ of the following form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized.
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Purely for display.)
+ A : 2-D array
+ 2-D array such that ``A @ x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the right hand side of each equality
+ constraint (row) in ``A``.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Options
+ -------
+ maxiter : int (default = 1000)
+ The maximum number of iterations of the algorithm.
+ tol : float (default = 1e-8)
+ Termination tolerance to be used for all termination criteria;
+ see [4]_ Section 4.5.
+ disp : bool (default = False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ alpha0 : float (default = 0.99995)
+ The maximal step size for Mehrota's predictor-corrector search
+ direction; see :math:`\beta_{3}` of [4]_ Table 8.1.
+ beta : float (default = 0.1)
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
+ when Mehrota's predictor-corrector is not in use (uncommon).
+ sparse : bool (default = False)
+ Set to ``True`` if the problem is to be treated as sparse after
+ presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix,
+ this option will automatically be set ``True``, and the problem
+ will be treated as sparse even during presolve. If your constraint
+ matrices contain mostly zeros and the problem is not very small (less
+ than about 100 constraints or variables), consider setting ``True``
+ or providing ``A_eq`` and ``A_ub`` as sparse matrices.
+ lstsq : bool (default = False)
+ Set to ``True`` if the problem is expected to be very poorly
+ conditioned. This should always be left ``False`` unless severe
+ numerical difficulties are encountered. Leave this at the default
+ unless you receive a warning message suggesting otherwise.
+ sym_pos : bool (default = True)
+ Leave ``True`` if the problem is expected to yield a well conditioned
+ symmetric positive definite normal equation matrix
+ (almost always). Leave this at the default unless you receive
+ a warning message suggesting otherwise.
+ cholesky : bool (default = True)
+ Set to ``True`` if the normal equations are to be solved by explicit
+ Cholesky decomposition followed by explicit forward/backward
+ substitution. This is typically faster for problems
+ that are numerically well-behaved.
+ pc : bool (default = True)
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
+ used. This is almost always (if not always) beneficial.
+ ip : bool (default = False)
+ Set to ``True`` if the improved initial point suggestion due to [4]_
+ Section 4.3 is desired. Whether this is beneficial or not
+ depends on the problem.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``, and no SuiteSparse.)
+ A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem.
+
+ Notes
+ -----
+ This method implements the algorithm outlined in [4]_ with ideas from [8]_
+ and a structure inspired by the simpler methods of [6]_.
+
+ The primal-dual path following method begins with initial 'guesses' of
+ the primal and dual variables of the standard form problem and iteratively
+ attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the
+ problem with a gradually reduced logarithmic barrier term added to the
+ objective. This particular implementation uses a homogeneous self-dual
+ formulation, which provides certificates of infeasibility or unboundedness
+ where applicable.
+
+ The default initial point for the primal and dual variables is that
+ defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial
+ point option ``ip=True``), an alternate (potentially improved) starting
+ point can be calculated according to the additional recommendations of
+ [4]_ Section 4.4.
+
+ A search direction is calculated using the predictor-corrector method
+ (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1.
+ (A potential improvement would be to implement the method of multiple
+ corrections described in [4]_ Section 4.2.) In practice, this is
+ accomplished by solving the normal equations, [4]_ Section 5.1 Equations
+ 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations
+ 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of
+ solving the normal equations rather than 8.25 directly is that the
+ matrices involved are symmetric positive definite, so Cholesky
+ decomposition can be used rather than the more expensive LU factorization.
+
+ With default options, the solver used to perform the factorization depends
+ on third-party software availability and the conditioning of the problem.
+
+ For dense problems, solvers are tried in the following order:
+
+ 1. ``scipy.linalg.cho_factor``
+
+ 2. ``scipy.linalg.solve`` with option ``sym_pos=True``
+
+ 3. ``scipy.linalg.solve`` with option ``sym_pos=False``
+
+ 4. ``scipy.linalg.lstsq``
+
+ For sparse problems:
+
+ 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are installed)
+
+ 2. ``scipy.sparse.linalg.factorized``
+ (if scikit-umfpack and SuiteSparse are installed)
+
+ 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy)
+
+ 4. ``scipy.sparse.linalg.lsqr``
+
+ If the solver fails for any reason, successively more robust (but slower)
+ solvers are attempted in the order indicated. Attempting, failing, and
+ re-starting factorization can be time consuming, so if the problem is
+ numerically challenging, options can be set to bypass solvers that are
+ failing. Setting ``cholesky=False`` skips to solver 2,
+ ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips
+ to solver 4 for both sparse and dense problems.
+
+ Potential improvements for combating issues associated with dense
+ columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and
+ [10]_ Section 4.1-4.2; the latter also discusses the alleviation of
+ accuracy issues associated with the substitution approach to free
+ variables.
+
+ After calculating the search direction, the maximum possible step size
+ that does not activate the non-negativity constraints is calculated, and
+ the smaller of this step size and unity is applied (as in [4]_ Section
+ 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size.
+
+ The new point is tested according to the termination conditions of [4]_
+ Section 4.5. The same tolerance, which can be set using the ``tol`` option,
+ is used for all checks. (A potential improvement would be to expose
+ the different tolerances to be set independently.) If optimality,
+ unboundedness, or infeasibility is detected, the solve procedure
+ terminates; otherwise it repeats.
+
+ The expected problem formulation differs between the top level ``linprog``
+ module and the method specific solvers. The method specific solvers expect a
+ problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ Whereas the top level ``linprog`` module expects a problem of form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
+
+ The original problem contains equality, upper-bound and variable constraints
+ whereas the method specific solver requires equality constraints and
+ variable non-negativity.
+
+ ``linprog`` module converts the original problem to standard form by
+ converting the simple bounds to upper bound constraints, introducing
+ non-negative slack variables for inequality constraints, and expressing
+ unbounded variables as the difference between two non-negative variables.
+
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [10] Andersen, Erling D., et al. Implementation of interior point methods
+ for large scale linear programming. HEC/Universite de Geneve, 1996.
+
+ """
+
+ _check_unknown_options(unknown_options)
+
+ # These should be warnings, not errors
+ if (cholesky or cholesky is None) and sparse and not has_cholmod:
+ if cholesky:
+ warn("Sparse cholesky is only available with scikit-sparse. "
+ "Setting `cholesky = False`",
+ OptimizeWarning, stacklevel=3)
+ cholesky = False
+
+ if sparse and lstsq:
+ warn("Option combination 'sparse':True and 'lstsq':True "
+ "is not recommended.",
+ OptimizeWarning, stacklevel=3)
+
+ if lstsq and cholesky:
+ warn("Invalid option combination 'lstsq':True "
+ "and 'cholesky':True; option 'cholesky' has no effect when "
+ "'lstsq' is set True.",
+ OptimizeWarning, stacklevel=3)
+
+ valid_permc_spec = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', 'COLAMD')
+ if permc_spec.upper() not in valid_permc_spec:
+ warn("Invalid permc_spec option: '" + str(permc_spec) + "'. "
+ "Acceptable values are 'NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', "
+ "and 'COLAMD'. Reverting to default.",
+ OptimizeWarning, stacklevel=3)
+ permc_spec = 'MMD_AT_PLUS_A'
+
+ # This can be an error
+ if not sym_pos and cholesky:
+ raise ValueError(
+ "Invalid option combination 'sym_pos':False "
+ "and 'cholesky':True: Cholesky decomposition is only possible "
+ "for symmetric positive definite matrices.")
+
+ cholesky = cholesky or (cholesky is None and sym_pos and not lstsq)
+
+ x, status, message, iteration = _ip_hsd(A, b, c, c0, alpha0, beta,
+ maxiter, disp, tol, sparse,
+ lstsq, sym_pos, cholesky,
+ pc, ip, permc_spec, callback,
+ postsolve_args)
+
+ return x, status, message, iteration
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_rs.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_rs.py
new file mode 100644
index 0000000000000000000000000000000000000000..43fed5805c4e40f0c38de91f053e3926cf1478e4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_rs.py
@@ -0,0 +1,572 @@
+"""Revised simplex method for linear programming
+
+The *revised simplex* method uses the method described in [1]_, except
+that a factorization [2]_ of the basis matrix, rather than its inverse,
+is efficiently maintained and used to solve the linear systems at each
+iteration of the algorithm.
+
+.. versionadded:: 1.3.0
+
+References
+----------
+.. [1] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+.. [2] Bartels, Richard H. "A stabilization of the simplex method."
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
+
+"""
+# Author: Matt Haberland
+
+import numpy as np
+from numpy.linalg import LinAlgError
+
+from scipy.linalg import solve
+from ._optimize import _check_unknown_options
+from ._bglu_dense import LU
+from ._bglu_dense import BGLU as BGLU
+from ._linprog_util import _postsolve
+from ._optimize import OptimizeResult
+
+
+def _phase_one(A, b, x0, callback, postsolve_args, maxiter, tol, disp,
+ maxupdate, mast, pivot):
+ """
+ The purpose of phase one is to find an initial basic feasible solution
+ (BFS) to the original problem.
+
+ Generates an auxiliary problem with a trivial BFS and an objective that
+ minimizes infeasibility of the original problem. Solves the auxiliary
+ problem using the main simplex routine (phase two). This either yields
+ a BFS to the original problem or determines that the original problem is
+ infeasible. If feasible, phase one detects redundant rows in the original
+ constraint matrix and removes them, then chooses additional indices as
+ necessary to complete a basis/BFS for the original problem.
+ """
+
+ m, n = A.shape
+ status = 0
+
+ # generate auxiliary problem to get initial BFS
+ A, b, c, basis, x, status = _generate_auxiliary_problem(A, b, x0, tol)
+
+ if status == 6:
+ residual = c.dot(x)
+ iter_k = 0
+ return x, basis, A, b, residual, status, iter_k
+
+ # solve auxiliary problem
+ phase_one_n = n
+ iter_k = 0
+ x, basis, status, iter_k = _phase_two(c, A, x, basis, callback,
+ postsolve_args,
+ maxiter, tol, disp,
+ maxupdate, mast, pivot,
+ iter_k, phase_one_n)
+
+ # check for infeasibility
+ residual = c.dot(x)
+ if status == 0 and residual > tol:
+ status = 2
+
+ # drive artificial variables out of basis
+ # TODO: test redundant row removal better
+ # TODO: make solve more efficient with BGLU? This could take a while.
+ keep_rows = np.ones(m, dtype=bool)
+ for basis_column in basis[basis >= n]:
+ B = A[:, basis]
+ try:
+ basis_finder = np.abs(solve(B, A)) # inefficient
+ pertinent_row = np.argmax(basis_finder[:, basis_column])
+ eligible_columns = np.ones(n, dtype=bool)
+ eligible_columns[basis[basis < n]] = 0
+ eligible_column_indices = np.where(eligible_columns)[0]
+ index = np.argmax(basis_finder[:, :n]
+ [pertinent_row, eligible_columns])
+ new_basis_column = eligible_column_indices[index]
+ if basis_finder[pertinent_row, new_basis_column] < tol:
+ keep_rows[pertinent_row] = False
+ else:
+ basis[basis == basis_column] = new_basis_column
+ except LinAlgError:
+ status = 4
+
+ # form solution to original problem
+ A = A[keep_rows, :n]
+ basis = basis[keep_rows]
+ x = x[:n]
+ m = A.shape[0]
+ return x, basis, A, b, residual, status, iter_k
+
+
+def _get_more_basis_columns(A, basis):
+ """
+ Called when the auxiliary problem terminates with artificial columns in
+ the basis, which must be removed and replaced with non-artificial
+ columns. Finds additional columns that do not make the matrix singular.
+ """
+ m, n = A.shape
+
+ # options for inclusion are those that aren't already in the basis
+ a = np.arange(m+n)
+ bl = np.zeros(len(a), dtype=bool)
+ bl[basis] = 1
+ options = a[~bl]
+ options = options[options < n] # and they have to be non-artificial
+
+ # form basis matrix
+ B = np.zeros((m, m))
+ B[:, 0:len(basis)] = A[:, basis]
+
+ if (basis.size > 0 and
+ np.linalg.matrix_rank(B[:, :len(basis)]) < len(basis)):
+ raise Exception("Basis has dependent columns")
+
+ rank = 0 # just enter the loop
+ for i in range(n): # somewhat arbitrary, but we need another way out
+ # permute the options, and take as many as needed
+ new_basis = np.random.permutation(options)[:m-len(basis)]
+ B[:, len(basis):] = A[:, new_basis] # update the basis matrix
+ rank = np.linalg.matrix_rank(B) # check the rank
+ if rank == m:
+ break
+
+ return np.concatenate((basis, new_basis))
+
+
+def _generate_auxiliary_problem(A, b, x0, tol):
+ """
+ Modifies original problem to create an auxiliary problem with a trivial
+ initial basic feasible solution and an objective that minimizes
+ infeasibility in the original problem.
+
+ Conceptually, this is done by stacking an identity matrix on the right of
+ the original constraint matrix, adding artificial variables to correspond
+ with each of these new columns, and generating a cost vector that is all
+ zeros except for ones corresponding with each of the new variables.
+
+ A initial basic feasible solution is trivial: all variables are zero
+ except for the artificial variables, which are set equal to the
+ corresponding element of the right hand side `b`.
+
+ Running the simplex method on this auxiliary problem drives all of the
+ artificial variables - and thus the cost - to zero if the original problem
+ is feasible. The original problem is declared infeasible otherwise.
+
+ Much of the complexity below is to improve efficiency by using singleton
+ columns in the original problem where possible, thus generating artificial
+ variables only as necessary, and using an initial 'guess' basic feasible
+ solution.
+ """
+ status = 0
+ m, n = A.shape
+
+ if x0 is not None:
+ x = x0
+ else:
+ x = np.zeros(n)
+
+ r = b - A@x # residual; this must be all zeros for feasibility
+
+ A[r < 0] = -A[r < 0] # express problem with RHS positive for trivial BFS
+ b[r < 0] = -b[r < 0] # to the auxiliary problem
+ r[r < 0] *= -1
+
+ # Rows which we will need to find a trivial way to zero.
+ # This should just be the rows where there is a nonzero residual.
+ # But then we would not necessarily have a column singleton in every row.
+ # This makes it difficult to find an initial basis.
+ if x0 is None:
+ nonzero_constraints = np.arange(m)
+ else:
+ nonzero_constraints = np.where(r > tol)[0]
+
+ # these are (at least some of) the initial basis columns
+ basis = np.where(np.abs(x) > tol)[0]
+
+ if len(nonzero_constraints) == 0 and len(basis) <= m: # already a BFS
+ c = np.zeros(n)
+ basis = _get_more_basis_columns(A, basis)
+ return A, b, c, basis, x, status
+ elif (len(nonzero_constraints) > m - len(basis) or
+ np.any(x < 0)): # can't get trivial BFS
+ c = np.zeros(n)
+ status = 6
+ return A, b, c, basis, x, status
+
+ # chooses existing columns appropriate for inclusion in initial basis
+ cols, rows = _select_singleton_columns(A, r)
+
+ # find the rows we need to zero that we _can_ zero with column singletons
+ i_tofix = np.isin(rows, nonzero_constraints)
+ # these columns can't already be in the basis, though
+ # we are going to add them to the basis and change the corresponding x val
+ i_notinbasis = np.logical_not(np.isin(cols, basis))
+ i_fix_without_aux = np.logical_and(i_tofix, i_notinbasis)
+ rows = rows[i_fix_without_aux]
+ cols = cols[i_fix_without_aux]
+
+ # indices of the rows we can only zero with auxiliary variable
+ # these rows will get a one in each auxiliary column
+ arows = nonzero_constraints[np.logical_not(
+ np.isin(nonzero_constraints, rows))]
+ n_aux = len(arows)
+ acols = n + np.arange(n_aux) # indices of auxiliary columns
+
+ basis_ng = np.concatenate((cols, acols)) # basis columns not from guess
+ basis_ng_rows = np.concatenate((rows, arows)) # rows we need to zero
+
+ # add auxiliary singleton columns
+ A = np.hstack((A, np.zeros((m, n_aux))))
+ A[arows, acols] = 1
+
+ # generate initial BFS
+ x = np.concatenate((x, np.zeros(n_aux)))
+ x[basis_ng] = r[basis_ng_rows]/A[basis_ng_rows, basis_ng]
+
+ # generate costs to minimize infeasibility
+ c = np.zeros(n_aux + n)
+ c[acols] = 1
+
+ # basis columns correspond with nonzeros in guess, those with column
+ # singletons we used to zero remaining constraints, and any additional
+ # columns to get a full set (m columns)
+ basis = np.concatenate((basis, basis_ng))
+ basis = _get_more_basis_columns(A, basis) # add columns as needed
+
+ return A, b, c, basis, x, status
+
+
+def _select_singleton_columns(A, b):
+ """
+ Finds singleton columns for which the singleton entry is of the same sign
+ as the right-hand side; these columns are eligible for inclusion in an
+ initial basis. Determines the rows in which the singleton entries are
+ located. For each of these rows, returns the indices of the one singleton
+ column and its corresponding row.
+ """
+ # find indices of all singleton columns and corresponding row indices
+ column_indices = np.nonzero(np.sum(np.abs(A) != 0, axis=0) == 1)[0]
+ columns = A[:, column_indices] # array of singleton columns
+ row_indices = np.zeros(len(column_indices), dtype=int)
+ nonzero_rows, nonzero_columns = np.nonzero(columns)
+ row_indices[nonzero_columns] = nonzero_rows # corresponding row indices
+
+ # keep only singletons with entries that have same sign as RHS
+ # this is necessary because all elements of BFS must be non-negative
+ same_sign = A[row_indices, column_indices]*b[row_indices] >= 0
+ column_indices = column_indices[same_sign][::-1]
+ row_indices = row_indices[same_sign][::-1]
+ # Reversing the order so that steps below select rightmost columns
+ # for initial basis, which will tend to be slack variables. (If the
+ # guess corresponds with a basic feasible solution but a constraint
+ # is not satisfied with the corresponding slack variable zero, the slack
+ # variable must be basic.)
+
+ # for each row, keep rightmost singleton column with an entry in that row
+ unique_row_indices, first_columns = np.unique(row_indices,
+ return_index=True)
+ return column_indices[first_columns], unique_row_indices
+
+
+def _find_nonzero_rows(A, tol):
+ """
+ Returns logical array indicating the locations of rows with at least
+ one nonzero element.
+ """
+ return np.any(np.abs(A) > tol, axis=1)
+
+
+def _select_enter_pivot(c_hat, bl, a, rule="bland", tol=1e-12):
+ """
+ Selects a pivot to enter the basis. Currently Bland's rule - the smallest
+ index that has a negative reduced cost - is the default.
+ """
+ if rule.lower() == "mrc": # index with minimum reduced cost
+ return a[~bl][np.argmin(c_hat)]
+ else: # smallest index w/ negative reduced cost
+ return a[~bl][c_hat < -tol][0]
+
+
+def _display_iter(phase, iteration, slack, con, fun):
+ """
+ Print indicators of optimization status to the console.
+ """
+ header = True if not iteration % 20 else False
+
+ if header:
+ print("Phase",
+ "Iteration",
+ "Minimum Slack ",
+ "Constraint Residual",
+ "Objective ")
+
+ # := -tol): # all reduced costs positive -> terminate
+ break
+
+ j = _select_enter_pivot(c_hat, bl, a, rule=pivot, tol=tol)
+ u = B.solve(A[:, j]) # similar to u = solve(B, A[:, j])
+
+ i = u > tol # if none of the u are positive, unbounded
+ if not np.any(i):
+ status = 3
+ break
+
+ th = xb[i]/u[i]
+ l = np.argmin(th) # implicitly selects smallest subscript
+ th_star = th[l] # step size
+
+ x[b] = x[b] - th_star*u # take step
+ x[j] = th_star
+ B.update(ab[i][l], j) # modify basis
+ b = B.b # similar to b[ab[i][l]] =
+
+ else:
+ # If the end of the for loop is reached (without a break statement),
+ # then another step has been taken, so the iteration counter should
+ # increment, info should be displayed, and callback should be called.
+ iteration += 1
+ status = 1
+ if disp or callback is not None:
+ _display_and_callback(phase_one_n, x, postsolve_args, status,
+ iteration, disp, callback)
+
+ return x, b, status, iteration
+
+
+def _linprog_rs(c, c0, A, b, x0, callback, postsolve_args,
+ maxiter=5000, tol=1e-12, disp=False,
+ maxupdate=10, mast=False, pivot="mrc",
+ **unknown_options):
+ """
+ Solve the following linear programming problem via a two-phase
+ revised simplex algorithm.::
+
+ minimize: c @ x
+
+ subject to: A @ x == b
+ 0 <= x < oo
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized.
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Currently unused.)
+ A : 2-D array
+ 2-D array which, when matrix-multiplied by ``x``, gives the values of
+ the equality constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the RHS of each equality constraint
+ (row) in ``A_eq``.
+ x0 : 1-D array, optional
+ Starting values of the independent variables, which will be refined by
+ the optimization algorithm. For the revised simplex method, these must
+ correspond with a basic feasible solution.
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector.
+ fun : float
+ Current value of the objective function ``c @ x``.
+ success : bool
+ True only when an algorithm has completed successfully,
+ so this is always False as the callback function is called
+ only while the algorithm is still iterating.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``.
+ phase : int
+ The phase of the algorithm being executed.
+ status : int
+ For revised simplex, this is always 0 because if a different
+ status is detected, the algorithm terminates.
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ disp : bool
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ maxupdate : int
+ The maximum number of updates performed on the LU factorization.
+ After this many updates is reached, the basis matrix is factorized
+ from scratch.
+ mast : bool
+ Minimize Amortized Solve Time. If enabled, the average time to solve
+ a linear system using the basis factorization is measured. Typically,
+ the average solve time will decrease with each successive solve after
+ initial factorization, as factorization takes much more time than the
+ solve operation (and updates). Eventually, however, the updated
+ factorization becomes sufficiently complex that the average solve time
+ begins to increase. When this is detected, the basis is refactorized
+ from scratch. Enable this option to maximize speed at the risk of
+ nondeterministic behavior. Ignored if ``maxupdate`` is 0.
+ pivot : "mrc" or "bland"
+ Pivot rule: Minimum Reduced Cost (default) or Bland's rule. Choose
+ Bland's rule if iteration limit is reached and cycling is suspected.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Numerical difficulties encountered
+ 5 : No constraints; turn presolve on
+ 6 : Guess x0 cannot be converted to a basic feasible solution
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem.
+ """
+
+ _check_unknown_options(unknown_options)
+
+ messages = ["Optimization terminated successfully.",
+ "Iteration limit reached.",
+ "The problem appears infeasible, as the phase one auxiliary "
+ "problem terminated successfully with a residual of {0:.1e}, "
+ "greater than the tolerance {1} required for the solution to "
+ "be considered feasible. Consider increasing the tolerance to "
+ "be greater than {0:.1e}. If this tolerance is unacceptably "
+ "large, the problem is likely infeasible.",
+ "The problem is unbounded, as the simplex algorithm found "
+ "a basic feasible solution from which there is a direction "
+ "with negative reduced cost in which all decision variables "
+ "increase.",
+ "Numerical difficulties encountered; consider trying "
+ "method='interior-point'.",
+ "Problems with no constraints are trivially solved; please "
+ "turn presolve on.",
+ "The guess x0 cannot be converted to a basic feasible "
+ "solution. "
+ ]
+
+ if A.size == 0: # address test_unbounded_below_no_presolve_corrected
+ return np.zeros(c.shape), 5, messages[5], 0
+
+ x, basis, A, b, residual, status, iteration = (
+ _phase_one(A, b, x0, callback, postsolve_args,
+ maxiter, tol, disp, maxupdate, mast, pivot))
+
+ if status == 0:
+ x, basis, status, iteration = _phase_two(c, A, x, basis, callback,
+ postsolve_args,
+ maxiter, tol, disp,
+ maxupdate, mast, pivot,
+ iteration)
+
+ return x, status, messages[status].format(residual, tol), iteration
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_simplex.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_simplex.py
new file mode 100644
index 0000000000000000000000000000000000000000..c47806c9a595f756b9f86d268c5c146ea86c77c6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_simplex.py
@@ -0,0 +1,663 @@
+"""Simplex method for linear programming
+
+The *simplex* method uses a traditional, full-tableau implementation of
+Dantzig's simplex algorithm [1]_, [2]_ (*not* the Nelder-Mead simplex).
+This algorithm is included for backwards compatibility and educational
+purposes.
+
+ .. versionadded:: 0.15.0
+
+Warnings
+--------
+
+The simplex method may encounter numerical difficulties when pivot
+values are close to the specified tolerance. If encountered try
+remove any redundant constraints, change the pivot strategy to Bland's
+rule or increase the tolerance value.
+
+Alternatively, more robust methods maybe be used. See
+:ref:`'interior-point' ` and
+:ref:`'revised simplex' `.
+
+References
+----------
+.. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+.. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+"""
+
+import numpy as np
+from warnings import warn
+from ._optimize import OptimizeResult, OptimizeWarning, _check_unknown_options
+from ._linprog_util import _postsolve
+
+
+def _pivot_col(T, tol=1e-9, bland=False):
+ """
+ Given a linear programming simplex tableau, determine the column
+ of the variable to enter the basis.
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ tol : float
+ Elements in the objective row larger than -tol will not be considered
+ for pivoting. Nominally this value is zero, but numerical issues
+ cause a tolerance about zero to be necessary.
+ bland : bool
+ If True, use Bland's rule for selection of the column (select the
+ first column with a negative coefficient in the objective row,
+ regardless of magnitude).
+
+ Returns
+ -------
+ status: bool
+ True if a suitable pivot column was found, otherwise False.
+ A return of False indicates that the linear programming simplex
+ algorithm is complete.
+ col: int
+ The index of the column of the pivot element.
+ If status is False, col will be returned as nan.
+ """
+ ma = np.ma.masked_where(T[-1, :-1] >= -tol, T[-1, :-1], copy=False)
+ if ma.count() == 0:
+ return False, np.nan
+ if bland:
+ # ma.mask is sometimes 0d
+ return True, np.nonzero(np.logical_not(np.atleast_1d(ma.mask)))[0][0]
+ return True, np.ma.nonzero(ma == ma.min())[0][0]
+
+
+def _pivot_row(T, basis, pivcol, phase, tol=1e-9, bland=False):
+ """
+ Given a linear programming simplex tableau, determine the row for the
+ pivot operation.
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a Problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ basis : array
+ A list of the current basic variables.
+ pivcol : int
+ The index of the pivot column.
+ phase : int
+ The phase of the simplex algorithm (1 or 2).
+ tol : float
+ Elements in the pivot column smaller than tol will not be considered
+ for pivoting. Nominally this value is zero, but numerical issues
+ cause a tolerance about zero to be necessary.
+ bland : bool
+ If True, use Bland's rule for selection of the row (if more than one
+ row can be used, choose the one with the lowest variable index).
+
+ Returns
+ -------
+ status: bool
+ True if a suitable pivot row was found, otherwise False. A return
+ of False indicates that the linear programming problem is unbounded.
+ row: int
+ The index of the row of the pivot element. If status is False, row
+ will be returned as nan.
+ """
+ if phase == 1:
+ k = 2
+ else:
+ k = 1
+ ma = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, pivcol], copy=False)
+ if ma.count() == 0:
+ return False, np.nan
+ mb = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, -1], copy=False)
+ q = mb / ma
+ min_rows = np.ma.nonzero(q == q.min())[0]
+ if bland:
+ return True, min_rows[np.argmin(np.take(basis, min_rows))]
+ return True, min_rows[0]
+
+
+def _apply_pivot(T, basis, pivrow, pivcol, tol=1e-9):
+ """
+ Pivot the simplex tableau inplace on the element given by (pivrow, pivol).
+ The entering variable corresponds to the column given by pivcol forcing
+ the variable basis[pivrow] to leave the basis.
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ basis : 1-D array
+ An array of the indices of the basic variables, such that basis[i]
+ contains the column corresponding to the basic variable for row i.
+ Basis is modified in place by _apply_pivot.
+ pivrow : int
+ Row index of the pivot.
+ pivcol : int
+ Column index of the pivot.
+ """
+ basis[pivrow] = pivcol
+ pivval = T[pivrow, pivcol]
+ T[pivrow] = T[pivrow] / pivval
+ for irow in range(T.shape[0]):
+ if irow != pivrow:
+ T[irow] = T[irow] - T[pivrow] * T[irow, pivcol]
+
+ # The selected pivot should never lead to a pivot value less than the tol.
+ if np.isclose(pivval, tol, atol=0, rtol=1e4):
+ message = (
+ f"The pivot operation produces a pivot value of:{pivval: .1e}, "
+ "which is only slightly greater than the specified "
+ f"tolerance{tol: .1e}. This may lead to issues regarding the "
+ "numerical stability of the simplex method. "
+ "Removing redundant constraints, changing the pivot strategy "
+ "via Bland's rule or increasing the tolerance may "
+ "help reduce the issue.")
+ warn(message, OptimizeWarning, stacklevel=5)
+
+
+def _solve_simplex(T, n, basis, callback, postsolve_args,
+ maxiter=1000, tol=1e-9, phase=2, bland=False, nit0=0,
+ ):
+ """
+ Solve a linear programming problem in "standard form" using the Simplex
+ Method. Linear Programming is intended to solve the following problem form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ n : int
+ The number of true variables in the problem.
+ basis : 1-D array
+ An array of the indices of the basic variables, such that basis[i]
+ contains the column corresponding to the basic variable for row i.
+ Basis is modified in place by _solve_simplex
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback must accept a
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector
+ fun : float
+ Current value of the objective function
+ success : bool
+ True only when a phase has completed successfully. This
+ will be False for most iterations.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+ maxiter : int
+ The maximum number of iterations to perform before aborting the
+ optimization.
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ bland : bool
+ If True, choose pivots using Bland's rule [3]_. In problems which
+ fail to converge due to cycling, using Bland's rule can provide
+ convergence at the expense of a less optimal path about the simplex.
+ nit0 : int
+ The initial iteration number used to keep an accurate iteration total
+ in a two-phase problem.
+
+ Returns
+ -------
+ nit : int
+ The number of iterations. Used to keep an accurate iteration total
+ in the two-phase problem.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ """
+ nit = nit0
+ status = 0
+ message = ''
+ complete = False
+
+ if phase == 1:
+ m = T.shape[1]-2
+ elif phase == 2:
+ m = T.shape[1]-1
+ else:
+ raise ValueError("Argument 'phase' to _solve_simplex must be 1 or 2")
+
+ if phase == 2:
+ # Check if any artificial variables are still in the basis.
+ # If yes, check if any coefficients from this row and a column
+ # corresponding to one of the non-artificial variable is non-zero.
+ # If found, pivot at this term. If not, start phase 2.
+ # Do this for all artificial variables in the basis.
+ # Ref: "An Introduction to Linear Programming and Game Theory"
+ # by Paul R. Thie, Gerard E. Keough, 3rd Ed,
+ # Chapter 3.7 Redundant Systems (pag 102)
+ for pivrow in [row for row in range(basis.size)
+ if basis[row] > T.shape[1] - 2]:
+ non_zero_row = [col for col in range(T.shape[1] - 1)
+ if abs(T[pivrow, col]) > tol]
+ if len(non_zero_row) > 0:
+ pivcol = non_zero_row[0]
+ _apply_pivot(T, basis, pivrow, pivcol, tol)
+ nit += 1
+
+ if len(basis[:m]) == 0:
+ solution = np.empty(T.shape[1] - 1, dtype=np.float64)
+ else:
+ solution = np.empty(max(T.shape[1] - 1, max(basis[:m]) + 1),
+ dtype=np.float64)
+
+ while not complete:
+ # Find the pivot column
+ pivcol_found, pivcol = _pivot_col(T, tol, bland)
+ if not pivcol_found:
+ pivcol = np.nan
+ pivrow = np.nan
+ status = 0
+ complete = True
+ else:
+ # Find the pivot row
+ pivrow_found, pivrow = _pivot_row(T, basis, pivcol, phase, tol, bland)
+ if not pivrow_found:
+ status = 3
+ complete = True
+
+ if callback is not None:
+ solution[:] = 0
+ solution[basis[:n]] = T[:n, -1]
+ x = solution[:m]
+ x, fun, slack, con = _postsolve(
+ x, postsolve_args
+ )
+ res = OptimizeResult({
+ 'x': x,
+ 'fun': fun,
+ 'slack': slack,
+ 'con': con,
+ 'status': status,
+ 'message': message,
+ 'nit': nit,
+ 'success': status == 0 and complete,
+ 'phase': phase,
+ 'complete': complete,
+ })
+ callback(res)
+
+ if not complete:
+ if nit >= maxiter:
+ # Iteration limit exceeded
+ status = 1
+ complete = True
+ else:
+ _apply_pivot(T, basis, pivrow, pivcol, tol)
+ nit += 1
+ return nit, status
+
+
+def _linprog_simplex(c, c0, A, b, callback, postsolve_args,
+ maxiter=1000, tol=1e-9, disp=False, bland=False,
+ **unknown_options):
+ """
+ Minimize a linear objective function subject to linear equality and
+ non-negativity constraints using the two phase simplex method.
+ Linear programming is intended to solve problems of the following form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized.
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Purely for display.)
+ A : 2-D array
+ 2-D array such that ``A @ x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the right hand side of each equality
+ constraint (row) in ``A``.
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector
+ fun : float
+ Current value of the objective function
+ success : bool
+ True when an algorithm has completed successfully.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``
+ phase : int
+ The phase of the algorithm being executed.
+ status : int
+ An integer representing the status of the optimization::
+
+ 0 : Algorithm proceeding nominally
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform.
+ disp : bool
+ If True, print exit status message to sys.stdout
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ bland : bool
+ If True, use Bland's anti-cycling rule [3]_ to choose pivots to
+ prevent cycling. If False, choose pivots which should lead to a
+ converged solution more quickly. The latter method is subject to
+ cycling (non-convergence) in rare instances.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem.
+
+ References
+ ----------
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
+
+
+ Notes
+ -----
+ The expected problem formulation differs between the top level ``linprog``
+ module and the method specific solvers. The method specific solvers expect a
+ problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ Whereas the top level ``linprog`` module expects a problem of form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
+
+ The original problem contains equality, upper-bound and variable constraints
+ whereas the method specific solver requires equality constraints and
+ variable non-negativity.
+
+ ``linprog`` module converts the original problem to standard form by
+ converting the simple bounds to upper bound constraints, introducing
+ non-negative slack variables for inequality constraints, and expressing
+ unbounded variables as the difference between two non-negative variables.
+ """
+ _check_unknown_options(unknown_options)
+
+ status = 0
+ messages = {0: "Optimization terminated successfully.",
+ 1: "Iteration limit reached.",
+ 2: "Optimization failed. Unable to find a feasible"
+ " starting point.",
+ 3: "Optimization failed. The problem appears to be unbounded.",
+ 4: "Optimization failed. Singular matrix encountered."}
+
+ n, m = A.shape
+
+ # All constraints must have b >= 0.
+ is_negative_constraint = np.less(b, 0)
+ A[is_negative_constraint] *= -1
+ b[is_negative_constraint] *= -1
+
+ # As all constraints are equality constraints the artificial variables
+ # will also be basic variables.
+ av = np.arange(n) + m
+ basis = av.copy()
+
+ # Format the phase one tableau by adding artificial variables and stacking
+ # the constraints, the objective row and pseudo-objective row.
+ row_constraints = np.hstack((A, np.eye(n), b[:, np.newaxis]))
+ row_objective = np.hstack((c, np.zeros(n), c0))
+ row_pseudo_objective = -row_constraints.sum(axis=0)
+ row_pseudo_objective[av] = 0
+ T = np.vstack((row_constraints, row_objective, row_pseudo_objective))
+
+ nit1, status = _solve_simplex(T, n, basis, callback=callback,
+ postsolve_args=postsolve_args,
+ maxiter=maxiter, tol=tol, phase=1,
+ bland=bland
+ )
+ # if pseudo objective is zero, remove the last row from the tableau and
+ # proceed to phase 2
+ nit2 = nit1
+ if abs(T[-1, -1]) < tol:
+ # Remove the pseudo-objective row from the tableau
+ T = T[:-1, :]
+ # Remove the artificial variable columns from the tableau
+ T = np.delete(T, av, 1)
+ else:
+ # Failure to find a feasible starting point
+ status = 2
+ messages[status] = (
+ "Phase 1 of the simplex method failed to find a feasible "
+ "solution. The pseudo-objective function evaluates to "
+ f"{abs(T[-1, -1]):.1e} "
+ f"which exceeds the required tolerance of {tol} for a solution to be "
+ "considered 'close enough' to zero to be a basic solution. "
+ "Consider increasing the tolerance to be greater than "
+ f"{abs(T[-1, -1]):.1e}. "
+ "If this tolerance is unacceptably large the problem may be "
+ "infeasible."
+ )
+
+ if status == 0:
+ # Phase 2
+ nit2, status = _solve_simplex(T, n, basis, callback=callback,
+ postsolve_args=postsolve_args,
+ maxiter=maxiter, tol=tol, phase=2,
+ bland=bland, nit0=nit1
+ )
+
+ solution = np.zeros(n + m)
+ solution[basis[:n]] = T[:n, -1]
+ x = solution[:m]
+
+ return x, status, messages[status], int(nit2)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_util.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..11176c9a606e9f69de81a13004351f765a53680a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_linprog_util.py
@@ -0,0 +1,1521 @@
+"""
+Method agnostic utility functions for linear programming
+"""
+
+import numpy as np
+import scipy.sparse as sps
+from warnings import warn
+from ._optimize import OptimizeWarning
+from scipy.optimize._remove_redundancy import (
+ _remove_redundancy_svd, _remove_redundancy_pivot_sparse,
+ _remove_redundancy_pivot_dense, _remove_redundancy_id
+ )
+from collections import namedtuple
+
+_LPProblem = namedtuple('_LPProblem',
+ 'c A_ub b_ub A_eq b_eq bounds x0 integrality')
+_LPProblem.__new__.__defaults__ = (None,) * 7 # make c the only required arg
+_LPProblem.__doc__ = \
+ """ Represents a linear-programming problem.
+
+ Attributes
+ ----------
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : various valid formats, optional
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
+ If bounds are specified for all N variables separately, valid formats
+ are:
+ * a 2D array (N x 2);
+ * a sequence of N sequences, each with 2 values.
+ If all variables have the same bounds, the bounds can be specified as
+ a 1-D or 2-D array or sequence with 2 scalar values.
+ If all variables have a lower bound of 0 and no upper bound, the bounds
+ parameter can be omitted (or given as None).
+ Absent lower and/or upper bounds can be specified as -numpy.inf (no
+ lower bound), numpy.inf (no upper bound) or None (both).
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+ integrality : 1-D array or int, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or ``0``.
+
+ By default, all variables are continuous.
+
+ For mixed integrality constraints, supply an array of shape `c.shape`.
+ To infer a constraint on each decision variable from shorter inputs,
+ the argument will be broadcast to `c.shape` using `np.broadcast_to`.
+
+ This argument is currently used only by the ``'highs'`` method and
+ ignored otherwise.
+
+ Notes
+ -----
+ This namedtuple supports 2 ways of initialization:
+ >>> lp1 = _LPProblem(c=[-1, 4], A_ub=[[-3, 1], [1, 2]], b_ub=[6, 4])
+ >>> lp2 = _LPProblem([-1, 4], [[-3, 1], [1, 2]], [6, 4])
+
+ Note that only ``c`` is a required argument here, whereas all other arguments
+ ``A_ub``, ``b_ub``, ``A_eq``, ``b_eq``, ``bounds``, ``x0`` are optional with
+ default values of None.
+ For example, ``A_eq`` and ``b_eq`` can be set without ``A_ub`` or ``b_ub``:
+ >>> lp3 = _LPProblem(c=[-1, 4], A_eq=[[2, 1]], b_eq=[10])
+ """
+
+
+def _check_sparse_inputs(options, meth, A_ub, A_eq):
+ """
+ Check the provided ``A_ub`` and ``A_eq`` matrices conform to the specified
+ optional sparsity variables.
+
+ Parameters
+ ----------
+ A_ub : 2-D array, optional
+ 2-D array such that ``A_ub @ x`` gives the values of the upper-bound
+ inequality constraints at ``x``.
+ A_eq : 2-D array, optional
+ 2-D array such that ``A_eq @ x`` gives the values of the equality
+ constraints at ``x``.
+ options : dict
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+ method : str, optional
+ The algorithm used to solve the standard form problem.
+
+ Returns
+ -------
+ A_ub : 2-D array, optional
+ 2-D array such that ``A_ub @ x`` gives the values of the upper-bound
+ inequality constraints at ``x``.
+ A_eq : 2-D array, optional
+ 2-D array such that ``A_eq @ x`` gives the values of the equality
+ constraints at ``x``.
+ options : dict
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+ """
+ # This is an undocumented option for unit testing sparse presolve
+ _sparse_presolve = options.pop('_sparse_presolve', False)
+ if _sparse_presolve and A_eq is not None:
+ A_eq = sps.coo_array(A_eq)
+ if _sparse_presolve and A_ub is not None:
+ A_ub = sps.coo_array(A_ub)
+
+ sparse_constraint = sps.issparse(A_eq) or sps.issparse(A_ub)
+
+ preferred_methods = {"highs", "highs-ds", "highs-ipm"}
+ dense_methods = {"simplex", "revised simplex"}
+ if meth in dense_methods and sparse_constraint:
+ raise ValueError(f"Method '{meth}' does not support sparse "
+ "constraint matrices. Please consider using one of "
+ f"{preferred_methods}.")
+
+ sparse = options.get('sparse', False)
+ if not sparse and sparse_constraint and meth == 'interior-point':
+ options['sparse'] = True
+ warn("Sparse constraint matrix detected; setting 'sparse':True.",
+ OptimizeWarning, stacklevel=4)
+ return options, A_ub, A_eq
+
+
+def _format_A_constraints(A, n_x, sparse_lhs=False):
+ """Format the left hand side of the constraints to a 2-D array
+
+ Parameters
+ ----------
+ A : 2-D array
+ 2-D array such that ``A @ x`` gives the values of the upper-bound
+ (in)equality constraints at ``x``.
+ n_x : int
+ The number of variables in the linear programming problem.
+ sparse_lhs : bool
+ Whether either of `A_ub` or `A_eq` are sparse. If true return a
+ coo_array instead of a numpy array.
+
+ Returns
+ -------
+ np.ndarray or sparse.coo_array
+ 2-D array such that ``A @ x`` gives the values of the upper-bound
+ (in)equality constraints at ``x``.
+
+ """
+ if sparse_lhs:
+ return sps.coo_array(
+ (0, n_x) if A is None else A, dtype=float, copy=True
+ )
+ elif A is None:
+ return np.zeros((0, n_x), dtype=float)
+ else:
+ return np.array(A, dtype=float, copy=True)
+
+
+def _format_b_constraints(b):
+ """Format the upper bounds of the constraints to a 1-D array
+
+ Parameters
+ ----------
+ b : 1-D array
+ 1-D array of values representing the upper-bound of each (in)equality
+ constraint (row) in ``A``.
+
+ Returns
+ -------
+ 1-D np.array
+ 1-D array of values representing the upper-bound of each (in)equality
+ constraint (row) in ``A``.
+
+ """
+ if b is None:
+ return np.array([], dtype=float)
+ b = np.array(b, dtype=float, copy=True).squeeze()
+ return b if b.size != 1 else b.reshape(-1)
+
+
+def _clean_inputs(lp):
+ """
+ Given user inputs for a linear programming problem, return the
+ objective vector, upper bound constraints, equality constraints,
+ and simple bounds in a preferred format.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : various valid formats, optional
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
+ If bounds are specified for all N variables separately, valid formats are:
+ * a 2D array (2 x N or N x 2);
+ * a sequence of N sequences, each with 2 values.
+ If all variables have the same bounds, a single pair of values can
+ be specified. Valid formats are:
+ * a sequence with 2 scalar values;
+ * a sequence with a single element containing 2 scalar values.
+ If all variables have a lower bound of 0 and no upper bound, the bounds
+ parameter can be omitted (or given as None).
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ Returns
+ -------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
+ elements of ``x``. The N x 2 array contains lower bounds in the first
+ column and upper bounds in the 2nd. Unbounded variables have lower
+ bound -np.inf and/or upper bound np.inf.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ """
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
+
+ if c is None:
+ raise TypeError
+
+ try:
+ c = np.array(c, dtype=np.float64, copy=True).squeeze()
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: c must be a 1-D array of numerical "
+ "coefficients") from e
+ else:
+ # If c is a single value, convert it to a 1-D array.
+ if c.size == 1:
+ c = c.reshape(-1)
+
+ n_x = len(c)
+ if n_x == 0 or len(c.shape) != 1:
+ raise ValueError(
+ "Invalid input for linprog: c must be a 1-D array and must "
+ "not have more than one non-singleton dimension")
+ if not np.isfinite(c).all():
+ raise ValueError(
+ "Invalid input for linprog: c must not contain values "
+ "inf, nan, or None")
+
+ sparse_lhs = sps.issparse(A_eq) or sps.issparse(A_ub)
+ try:
+ A_ub = _format_A_constraints(A_ub, n_x, sparse_lhs=sparse_lhs)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: A_ub must be a 2-D array "
+ "of numerical values") from e
+ else:
+ n_ub = A_ub.shape[0]
+ if len(A_ub.shape) != 2 or A_ub.shape[1] != n_x:
+ raise ValueError(
+ "Invalid input for linprog: A_ub must have exactly two "
+ "dimensions, and the number of columns in A_ub must be "
+ "equal to the size of c")
+ if (sps.issparse(A_ub) and not np.isfinite(A_ub.data).all()
+ or not sps.issparse(A_ub) and not np.isfinite(A_ub).all()):
+ raise ValueError(
+ "Invalid input for linprog: A_ub must not contain values "
+ "inf, nan, or None")
+
+ try:
+ b_ub = _format_b_constraints(b_ub)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: b_ub must be a 1-D array of "
+ "numerical values, each representing the upper bound of an "
+ "inequality constraint (row) in A_ub") from e
+ else:
+ if b_ub.shape != (n_ub,):
+ raise ValueError(
+ "Invalid input for linprog: b_ub must be a 1-D array; b_ub "
+ "must not have more than one non-singleton dimension and "
+ "the number of rows in A_ub must equal the number of values "
+ "in b_ub")
+ if not np.isfinite(b_ub).all():
+ raise ValueError(
+ "Invalid input for linprog: b_ub must not contain values "
+ "inf, nan, or None")
+
+ try:
+ A_eq = _format_A_constraints(A_eq, n_x, sparse_lhs=sparse_lhs)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: A_eq must be a 2-D array "
+ "of numerical values") from e
+ else:
+ n_eq = A_eq.shape[0]
+ if len(A_eq.shape) != 2 or A_eq.shape[1] != n_x:
+ raise ValueError(
+ "Invalid input for linprog: A_eq must have exactly two "
+ "dimensions, and the number of columns in A_eq must be "
+ "equal to the size of c")
+
+ if (sps.issparse(A_eq) and not np.isfinite(A_eq.data).all()
+ or not sps.issparse(A_eq) and not np.isfinite(A_eq).all()):
+ raise ValueError(
+ "Invalid input for linprog: A_eq must not contain values "
+ "inf, nan, or None")
+
+ try:
+ b_eq = _format_b_constraints(b_eq)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: b_eq must be a dense, 1-D array of "
+ "numerical values, each representing the right hand side of an "
+ "equality constraint (row) in A_eq") from e
+ else:
+ if b_eq.shape != (n_eq,):
+ raise ValueError(
+ "Invalid input for linprog: b_eq must be a 1-D array; b_eq "
+ "must not have more than one non-singleton dimension and "
+ "the number of rows in A_eq must equal the number of values "
+ "in b_eq")
+ if not np.isfinite(b_eq).all():
+ raise ValueError(
+ "Invalid input for linprog: b_eq must not contain values "
+ "inf, nan, or None")
+
+ # x0 gives a (optional) starting solution to the solver. If x0 is None,
+ # skip the checks. Initial solution will be generated automatically.
+ if x0 is not None:
+ try:
+ x0 = np.array(x0, dtype=float, copy=True).squeeze()
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: x0 must be a 1-D array of "
+ "numerical coefficients") from e
+ if x0.ndim == 0:
+ x0 = x0.reshape(-1)
+ if len(x0) == 0 or x0.ndim != 1:
+ raise ValueError(
+ "Invalid input for linprog: x0 should be a 1-D array; it "
+ "must not have more than one non-singleton dimension")
+ if not x0.size == c.size:
+ raise ValueError(
+ "Invalid input for linprog: x0 and c should contain the "
+ "same number of elements")
+ if not np.isfinite(x0).all():
+ raise ValueError(
+ "Invalid input for linprog: x0 must not contain values "
+ "inf, nan, or None")
+
+ # Bounds can be one of these formats:
+ # (1) a 2-D array or sequence, with shape N x 2
+ # (2) a 1-D or 2-D sequence or array with 2 scalars
+ # (3) None (or an empty sequence or array)
+ # Unspecified bounds can be represented by None or (-)np.inf.
+ # All formats are converted into an N x 2 np.array with (-)np.inf where
+ # bounds are unspecified.
+
+ # Prepare clean bounds array
+ bounds_clean = np.zeros((n_x, 2), dtype=float)
+
+ # Convert to a numpy array.
+ # np.array(..,dtype=float) raises an error if dimensions are inconsistent
+ # or if there are invalid data types in bounds. Just add a linprog prefix
+ # to the error and re-raise.
+ # Creating at least a 2-D array simplifies the cases to distinguish below.
+ if bounds is None or np.array_equal(bounds, []) or np.array_equal(bounds, [[]]):
+ bounds = (0, np.inf)
+ try:
+ bounds_conv = np.atleast_2d(np.array(bounds, dtype=float))
+ except ValueError as e:
+ raise ValueError(
+ "Invalid input for linprog: unable to interpret bounds, "
+ "check values and dimensions: " + e.args[0]) from e
+ except TypeError as e:
+ raise TypeError(
+ "Invalid input for linprog: unable to interpret bounds, "
+ "check values and dimensions: " + e.args[0]) from e
+
+ # Check bounds options
+ bsh = bounds_conv.shape
+ if len(bsh) > 2:
+ # Do not try to handle multidimensional bounds input
+ raise ValueError(
+ "Invalid input for linprog: provide a 2-D array for bounds, "
+ f"not a {len(bsh):d}-D array.")
+ elif np.all(bsh == (n_x, 2)):
+ # Regular N x 2 array
+ bounds_clean = bounds_conv
+ elif (np.all(bsh == (2, 1)) or np.all(bsh == (1, 2))):
+ # 2 values: interpret as overall lower and upper bound
+ bounds_flat = bounds_conv.flatten()
+ bounds_clean[:, 0] = bounds_flat[0]
+ bounds_clean[:, 1] = bounds_flat[1]
+ elif np.all(bsh == (2, n_x)):
+ # Reject a 2 x N array
+ raise ValueError(
+ f"Invalid input for linprog: provide a {n_x:d} x 2 array for bounds, "
+ f"not a 2 x {n_x:d} array.")
+ else:
+ raise ValueError(
+ "Invalid input for linprog: unable to interpret bounds with this "
+ f"dimension tuple: {bsh}.")
+
+ # The process above creates nan-s where the input specified None
+ # Convert the nan-s in the 1st column to -np.inf and in the 2nd column
+ # to np.inf
+ i_none = np.isnan(bounds_clean[:, 0])
+ bounds_clean[i_none, 0] = -np.inf
+ i_none = np.isnan(bounds_clean[:, 1])
+ bounds_clean[i_none, 1] = np.inf
+
+ return _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds_clean, x0, integrality)
+
+
+def _presolve(lp, rr, rr_method, tol=1e-9):
+ """
+ Given inputs for a linear programming problem in preferred format,
+ presolve the problem: identify trivial infeasibilities, redundancies,
+ and unboundedness, tighten bounds where possible, and eliminate fixed
+ variables.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
+ elements of ``x``. The N x 2 array contains lower bounds in the first
+ column and upper bounds in the 2nd. Unbounded variables have lower
+ bound -np.inf and/or upper bound np.inf.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ rr : bool
+ If ``True`` attempts to eliminate any redundant rows in ``A_eq``.
+ Set False if ``A_eq`` is known to be of full row rank, or if you are
+ looking for a potential speedup (at the expense of reliability).
+ rr_method : str
+ Method used to identify and remove redundant rows from the
+ equality constraint matrix after presolve.
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+
+ Returns
+ -------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, possibly tightened.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ c0 : 1D array
+ Constant term in objective function due to fixed (and eliminated)
+ variables.
+ x : 1D array
+ Solution vector (when the solution is trivial and can be determined
+ in presolve)
+ revstack: list of functions
+ the functions in the list reverse the operations of _presolve()
+ the function signature is x_org = f(x_mod), where x_mod is the result
+ of a presolve step and x_org the value at the start of the step
+ (currently, the revstack contains only one function)
+ complete: bool
+ Whether the solution is complete (solved or determined to be infeasible
+ or unbounded in presolve)
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [5] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+
+ """
+ # ideas from Reference [5] by Andersen and Andersen
+ # however, unlike the reference, this is performed before converting
+ # problem to standard form
+ # There are a few advantages:
+ # * artificial variables have not been added, so matrices are smaller
+ # * bounds have not been converted to constraints yet. (It is better to
+ # do that after presolve because presolve may adjust the simple bounds.)
+ # There are many improvements that can be made, namely:
+ # * implement remaining checks from [5]
+ # * loop presolve until no additional changes are made
+ # * implement additional efficiency improvements in redundancy removal [2]
+
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, _ = lp
+
+ revstack = [] # record of variables eliminated from problem
+ # constant term in cost function may be added if variables are eliminated
+ c0 = 0
+ complete = False # complete is True if detected infeasible/unbounded
+ x = np.zeros(c.shape) # this is solution vector if completed in presolve
+
+ status = 0 # all OK unless determined otherwise
+ message = ""
+
+ # Lower and upper bounds. Copy to prevent feedback.
+ lb = bounds[:, 0].copy()
+ ub = bounds[:, 1].copy()
+
+ m_eq, n = A_eq.shape
+ m_ub, n = A_ub.shape
+
+ if (rr_method is not None
+ and rr_method.lower() not in {"svd", "pivot", "id"}):
+ message = ("'" + str(rr_method) + "' is not a valid option "
+ "for redundancy removal. Valid options are 'SVD', "
+ "'pivot', and 'ID'.")
+ raise ValueError(message)
+
+ if sps.issparse(A_eq):
+ A_eq = A_eq.tocsr()
+ A_ub = A_ub.tocsr()
+
+ def where(A):
+ return A.nonzero()
+
+ vstack = sps.vstack
+ else:
+ where = np.where
+ vstack = np.vstack
+
+ # upper bounds > lower bounds
+ if np.any(ub < lb) or np.any(lb == np.inf) or np.any(ub == -np.inf):
+ status = 2
+ message = ("The problem is (trivially) infeasible since one "
+ "or more upper bounds are smaller than the corresponding "
+ "lower bounds, a lower bound is np.inf or an upper bound "
+ "is -np.inf.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+ # zero row in equality constraints
+ zero_row = np.array(np.sum(A_eq != 0, axis=1) == 0).flatten()
+ if np.any(zero_row):
+ if np.any(
+ np.logical_and(
+ zero_row,
+ np.abs(b_eq) > tol)): # test_zero_row_1
+ # infeasible if RHS is not zero
+ status = 2
+ message = ("The problem is (trivially) infeasible due to a row "
+ "of zeros in the equality constraint matrix with a "
+ "nonzero corresponding constraint value.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ else: # test_zero_row_2
+ # if RHS is zero, we can eliminate this equation entirely
+ A_eq = A_eq[np.logical_not(zero_row), :]
+ b_eq = b_eq[np.logical_not(zero_row)]
+
+ # zero row in inequality constraints
+ zero_row = np.array(np.sum(A_ub != 0, axis=1) == 0).flatten()
+ if np.any(zero_row):
+ if np.any(np.logical_and(zero_row, b_ub < -tol)): # test_zero_row_1
+ # infeasible if RHS is less than zero (because LHS is zero)
+ status = 2
+ message = ("The problem is (trivially) infeasible due to a row "
+ "of zeros in the equality constraint matrix with a "
+ "nonzero corresponding constraint value.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ else: # test_zero_row_2
+ # if LHS is >= 0, we can eliminate this constraint entirely
+ A_ub = A_ub[np.logical_not(zero_row), :]
+ b_ub = b_ub[np.logical_not(zero_row)]
+
+ # zero column in (both) constraints
+ # this indicates that a variable isn't constrained and can be removed
+ A = vstack((A_eq, A_ub))
+ if A.shape[0] > 0:
+ zero_col = np.array(np.sum(A != 0, axis=0) == 0).flatten()
+ # variable will be at upper or lower bound, depending on objective
+ x[np.logical_and(zero_col, c < 0)] = ub[
+ np.logical_and(zero_col, c < 0)]
+ x[np.logical_and(zero_col, c > 0)] = lb[
+ np.logical_and(zero_col, c > 0)]
+ if np.any(np.isinf(x)): # if an unconstrained variable has no bound
+ status = 3
+ message = ("If feasible, the problem is (trivially) unbounded "
+ "due to a zero column in the constraint matrices. If "
+ "you wish to check whether the problem is infeasible, "
+ "turn presolve off.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ # variables will equal upper/lower bounds will be removed later
+ lb[np.logical_and(zero_col, c < 0)] = ub[
+ np.logical_and(zero_col, c < 0)]
+ ub[np.logical_and(zero_col, c > 0)] = lb[
+ np.logical_and(zero_col, c > 0)]
+
+ # row singleton in equality constraints
+ # this fixes a variable and removes the constraint
+ singleton_row = np.array(np.sum(A_eq != 0, axis=1) == 1).flatten()
+ rows = where(singleton_row)[0]
+ cols = where(A_eq[rows, :])[1]
+ if len(rows) > 0:
+ for row, col in zip(rows, cols):
+ val = b_eq[row] / A_eq[row, col]
+ if not lb[col] - tol <= val <= ub[col] + tol:
+ # infeasible if fixed value is not within bounds
+ status = 2
+ message = ("The problem is (trivially) infeasible because a "
+ "singleton row in the equality constraints is "
+ "inconsistent with the bounds.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ else:
+ # sets upper and lower bounds at that fixed value - variable
+ # will be removed later
+ lb[col] = val
+ ub[col] = val
+ A_eq = A_eq[np.logical_not(singleton_row), :]
+ b_eq = b_eq[np.logical_not(singleton_row)]
+
+ # row singleton in inequality constraints
+ # this indicates a simple bound and the constraint can be removed
+ # simple bounds may be adjusted here
+ # After all of the simple bound information is combined here, get_Abc will
+ # turn the simple bounds into constraints
+ singleton_row = np.array(np.sum(A_ub != 0, axis=1) == 1).flatten()
+ cols = where(A_ub[singleton_row, :])[1]
+ rows = where(singleton_row)[0]
+ if len(rows) > 0:
+ for row, col in zip(rows, cols):
+ val = b_ub[row] / A_ub[row, col]
+ if A_ub[row, col] > 0: # upper bound
+ if val < lb[col] - tol: # infeasible
+ complete = True
+ elif val < ub[col]: # new upper bound
+ ub[col] = val
+ else: # lower bound
+ if val > ub[col] + tol: # infeasible
+ complete = True
+ elif val > lb[col]: # new lower bound
+ lb[col] = val
+ if complete:
+ status = 2
+ message = ("The problem is (trivially) infeasible because a "
+ "singleton row in the upper bound constraints is "
+ "inconsistent with the bounds.")
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ A_ub = A_ub[np.logical_not(singleton_row), :]
+ b_ub = b_ub[np.logical_not(singleton_row)]
+
+ # identical bounds indicate that variable can be removed
+ i_f = np.abs(lb - ub) < tol # indices of "fixed" variables
+ i_nf = np.logical_not(i_f) # indices of "not fixed" variables
+
+ # test_bounds_equal_but_infeasible
+ if np.all(i_f): # if bounds define solution, check for consistency
+ residual = b_eq - A_eq.dot(lb)
+ slack = b_ub - A_ub.dot(lb)
+ if ((A_ub.size > 0 and np.any(slack < 0)) or
+ (A_eq.size > 0 and not np.allclose(residual, 0))):
+ status = 2
+ message = ("The problem is (trivially) infeasible because the "
+ "bounds fix all variables to values inconsistent with "
+ "the constraints")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+ ub_mod = ub
+ lb_mod = lb
+ if np.any(i_f):
+ c0 += c[i_f].dot(lb[i_f])
+ b_eq = b_eq - A_eq[:, i_f].dot(lb[i_f])
+ b_ub = b_ub - A_ub[:, i_f].dot(lb[i_f])
+ c = c[i_nf]
+ x_undo = lb[i_f] # not x[i_f], x is just zeroes
+ x = x[i_nf]
+ # user guess x0 stays separate from presolve solution x
+ if x0 is not None:
+ x0 = x0[i_nf]
+ A_eq = A_eq[:, i_nf]
+ A_ub = A_ub[:, i_nf]
+ # modify bounds
+ lb_mod = lb[i_nf]
+ ub_mod = ub[i_nf]
+
+ def rev(x_mod):
+ # Function to restore x: insert x_undo into x_mod.
+ # When elements have been removed at positions k1, k2, k3, ...
+ # then these must be replaced at (after) positions k1-1, k2-2,
+ # k3-3, ... in the modified array to recreate the original
+ i = np.flatnonzero(i_f)
+ # Number of variables to restore
+ N = len(i)
+ index_offset = np.arange(N)
+ # Create insert indices
+ insert_indices = i - index_offset
+ x_rev = np.insert(x_mod.astype(float), insert_indices, x_undo)
+ return x_rev
+
+ # Use revstack as a list of functions, currently just this one.
+ revstack.append(rev)
+
+ # no constraints indicates that problem is trivial
+ if A_eq.size == 0 and A_ub.size == 0:
+ b_eq = np.array([])
+ b_ub = np.array([])
+ # test_empty_constraint_1
+ if c.size == 0:
+ status = 0
+ message = ("The solution was determined in presolve as there are "
+ "no non-trivial constraints.")
+ elif (np.any(np.logical_and(c < 0, ub_mod == np.inf)) or
+ np.any(np.logical_and(c > 0, lb_mod == -np.inf))):
+ # test_no_constraints()
+ # test_unbounded_no_nontrivial_constraints_1
+ # test_unbounded_no_nontrivial_constraints_2
+ status = 3
+ message = ("The problem is (trivially) unbounded "
+ "because there are no non-trivial constraints and "
+ "a) at least one decision variable is unbounded "
+ "above and its corresponding cost is negative, or "
+ "b) at least one decision variable is unbounded below "
+ "and its corresponding cost is positive. ")
+ else: # test_empty_constraint_2
+ status = 0
+ message = ("The solution was determined in presolve as there are "
+ "no non-trivial constraints.")
+ complete = True
+ x[c < 0] = ub_mod[c < 0]
+ x[c > 0] = lb_mod[c > 0]
+ # where c is zero, set x to a finite bound or zero
+ x_zero_c = ub_mod[c == 0]
+ x_zero_c[np.isinf(x_zero_c)] = ub_mod[c == 0][np.isinf(x_zero_c)]
+ x_zero_c[np.isinf(x_zero_c)] = 0
+ x[c == 0] = x_zero_c
+ # if this is not the last step of presolve, should convert bounds back
+ # to array and return here
+
+ # Convert modified lb and ub back into N x 2 bounds
+ bounds = np.hstack((lb_mod[:, np.newaxis], ub_mod[:, np.newaxis]))
+
+ # remove redundant (linearly dependent) rows from equality constraints
+ n_rows_A = A_eq.shape[0]
+ redundancy_warning = ("A_eq does not appear to be of full row rank. To "
+ "improve performance, check the problem formulation "
+ "for redundant equality constraints.")
+ if (sps.issparse(A_eq)):
+ if rr and A_eq.size > 0: # TODO: Fast sparse rank check?
+ rr_res = _remove_redundancy_pivot_sparse(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ if A_eq.shape[0] < n_rows_A:
+ warn(redundancy_warning, OptimizeWarning, stacklevel=1)
+ if status != 0:
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+ # This is a wild guess for which redundancy removal algorithm will be
+ # faster. More testing would be good.
+ small_nullspace = 5
+ if rr and A_eq.size > 0:
+ try: # TODO: use results of first SVD in _remove_redundancy_svd
+ rank = np.linalg.matrix_rank(A_eq)
+ # oh well, we'll have to go with _remove_redundancy_pivot_dense
+ except Exception:
+ rank = 0
+ if rr and A_eq.size > 0 and rank < A_eq.shape[0]:
+ warn(redundancy_warning, OptimizeWarning, stacklevel=3)
+ dim_row_nullspace = A_eq.shape[0]-rank
+ if rr_method is None:
+ if dim_row_nullspace <= small_nullspace:
+ rr_res = _remove_redundancy_svd(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ if dim_row_nullspace > small_nullspace or status == 4:
+ rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+
+ else:
+ rr_method = rr_method.lower()
+ if rr_method == "svd":
+ rr_res = _remove_redundancy_svd(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ elif rr_method == "pivot":
+ rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ elif rr_method == "id":
+ rr_res = _remove_redundancy_id(A_eq, b_eq, rank)
+ A_eq, b_eq, status, message = rr_res
+ else: # shouldn't get here; option validity checked above
+ pass
+ if A_eq.shape[0] < rank:
+ message = ("Due to numerical issues, redundant equality "
+ "constraints could not be removed automatically. "
+ "Try providing your constraint matrices as sparse "
+ "matrices to activate sparse presolve, try turning "
+ "off redundancy removal, or try turning off presolve "
+ "altogether.")
+ status = 4
+ if status != 0:
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+
+def _parse_linprog(lp, options, meth):
+ """
+ Parse the provided linear programming problem
+
+ ``_parse_linprog`` employs two main steps ``_check_sparse_inputs`` and
+ ``_clean_inputs``. ``_check_sparse_inputs`` checks for sparsity in the
+ provided constraints (``A_ub`` and ``A_eq) and if these match the provided
+ sparsity optional values.
+
+ ``_clean inputs`` checks of the provided inputs. If no violations are
+ identified the objective vector, upper bound constraints, equality
+ constraints, and simple bounds are returned in the expected format.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : various valid formats, optional
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
+ If bounds are specified for all N variables separately, valid formats are:
+ * a 2D array (2 x N or N x 2);
+ * a sequence of N sequences, each with 2 values.
+ If all variables have the same bounds, a single pair of values can
+ be specified. Valid formats are:
+ * a sequence with 2 scalar values;
+ * a sequence with a single element containing 2 scalar values.
+ If all variables have a lower bound of 0 and no upper bound, the bounds
+ parameter can be omitted (or given as None).
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ options : dict
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+
+ Returns
+ -------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
+ elements of ``x``. The N x 2 array contains lower bounds in the first
+ column and upper bounds in the 2nd. Unbounded variables have lower
+ bound -np.inf and/or upper bound np.inf.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ options : dict, optional
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+
+ """
+ if options is None:
+ options = {}
+
+ solver_options = {k: v for k, v in options.items()}
+ solver_options, A_ub, A_eq = _check_sparse_inputs(solver_options, meth,
+ lp.A_ub, lp.A_eq)
+ # Convert lists to numpy arrays, etc...
+ lp = _clean_inputs(lp._replace(A_ub=A_ub, A_eq=A_eq))
+ return lp, solver_options
+
+
+def _get_Abc(lp, c0):
+ """
+ Given a linear programming problem of the form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
+
+ Return the problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ by adding slack variables and making variable substitutions as necessary.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, lower bounds in the 1st column, upper
+ bounds in the 2nd column. The bounds are possibly tightened
+ by the presolve procedure.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables.
+
+ Returns
+ -------
+ A : 2-D array
+ 2-D array such that ``A`` @ ``x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the RHS of each equality constraint
+ (row) in A (for standard form problem).
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized (for
+ standard form problem).
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables.
+ x0 : 1-D array
+ Starting values of the independent variables, which will be refined by
+ the optimization algorithm
+
+ References
+ ----------
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+
+ """
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
+
+ if sps.issparse(A_eq):
+ sparse = True
+ A_eq = sps.csr_array(A_eq)
+ A_ub = sps.csr_array(A_ub)
+
+ def hstack(blocks):
+ return sps.hstack(blocks, format="csr")
+
+ def vstack(blocks):
+ return sps.vstack(blocks, format="csr")
+
+ zeros = sps.csr_array
+ eye = sps.eye_array
+ else:
+ sparse = False
+ hstack = np.hstack
+ vstack = np.vstack
+ zeros = np.zeros
+ eye = np.eye
+
+ # Variables lbs and ubs (see below) may be changed, which feeds back into
+ # bounds, so copy.
+ bounds = np.array(bounds, copy=True)
+
+ # modify problem such that all variables have only non-negativity bounds
+ lbs = bounds[:, 0]
+ ubs = bounds[:, 1]
+ m_ub, n_ub = A_ub.shape
+
+ lb_none = np.equal(lbs, -np.inf)
+ ub_none = np.equal(ubs, np.inf)
+ lb_some = np.logical_not(lb_none)
+ ub_some = np.logical_not(ub_none)
+
+ # unbounded below: substitute xi = -xi' (unbounded above)
+ # if -inf <= xi <= ub, then -ub <= -xi <= inf, so swap and invert bounds
+ l_nolb_someub = np.logical_and(lb_none, ub_some)
+ i_nolb = np.nonzero(l_nolb_someub)[0]
+ lbs[l_nolb_someub], ubs[l_nolb_someub] = (
+ -ubs[l_nolb_someub], -lbs[l_nolb_someub])
+ lb_none = np.equal(lbs, -np.inf)
+ ub_none = np.equal(ubs, np.inf)
+ lb_some = np.logical_not(lb_none)
+ ub_some = np.logical_not(ub_none)
+ c[i_nolb] *= -1
+ if x0 is not None:
+ x0[i_nolb] *= -1
+ if len(i_nolb) > 0:
+ if A_ub.shape[0] > 0: # sometimes needed for sparse arrays... weird
+ A_ub[:, i_nolb] *= -1
+ if A_eq.shape[0] > 0:
+ A_eq[:, i_nolb] *= -1
+
+ # upper bound: add inequality constraint
+ i_newub, = ub_some.nonzero()
+ ub_newub = ubs[ub_some]
+ n_bounds = len(i_newub)
+ if n_bounds > 0:
+ shape = (n_bounds, A_ub.shape[1])
+ if sparse:
+ idxs = (np.arange(n_bounds), i_newub)
+ A_ub = vstack((A_ub, sps.csr_array((np.ones(n_bounds), idxs),
+ shape=shape)))
+ else:
+ A_ub = vstack((A_ub, np.zeros(shape)))
+ A_ub[np.arange(m_ub, A_ub.shape[0]), i_newub] = 1
+ b_ub = np.concatenate((b_ub, np.zeros(n_bounds)))
+ b_ub[m_ub:] = ub_newub
+
+ A1 = vstack((A_ub, A_eq))
+ b = np.concatenate((b_ub, b_eq))
+ c = np.concatenate((c, np.zeros((A_ub.shape[0],))))
+ if x0 is not None:
+ x0 = np.concatenate((x0, np.zeros((A_ub.shape[0],))))
+ # unbounded: substitute xi = xi+ + xi-
+ l_free = np.logical_and(lb_none, ub_none)
+ i_free = np.nonzero(l_free)[0]
+ n_free = len(i_free)
+ c = np.concatenate((c, np.zeros(n_free)))
+ if x0 is not None:
+ x0 = np.concatenate((x0, np.zeros(n_free)))
+ A1 = hstack((A1[:, :n_ub], -A1[:, i_free]))
+ c[n_ub:n_ub+n_free] = -c[i_free]
+ if x0 is not None:
+ i_free_neg = x0[i_free] < 0
+ x0[np.arange(n_ub, A1.shape[1])[i_free_neg]] = -x0[i_free[i_free_neg]]
+ x0[i_free[i_free_neg]] = 0
+
+ # add slack variables
+ A2 = vstack([eye(A_ub.shape[0]), zeros((A_eq.shape[0], A_ub.shape[0]))])
+
+ A = hstack([A1, A2])
+
+ # lower bound: substitute xi = xi' + lb
+ # now there is a constant term in objective
+ i_shift = np.nonzero(lb_some)[0]
+ lb_shift = lbs[lb_some].astype(float)
+ c0 += np.sum(lb_shift * c[i_shift])
+ if sparse:
+ A = A.tocsc()
+ b -= (A[:, i_shift] @ sps.diags_array(lb_shift)).sum(axis=1)
+ else:
+ b -= (A[:, i_shift] * lb_shift).sum(axis=1)
+ if x0 is not None:
+ x0[i_shift] -= lb_shift
+
+ return A, b, c, c0, x0
+
+
+def _round_to_power_of_two(x):
+ """
+ Round elements of the array to the nearest power of two.
+ """
+ return 2**np.around(np.log2(x))
+
+
+def _autoscale(A, b, c, x0):
+ """
+ Scales the problem according to equilibration from [12].
+ Also normalizes the right hand side vector by its maximum element.
+ """
+ m, n = A.shape
+
+ C = 1
+ R = 1
+
+ if A.size > 0:
+
+ R = np.max(np.abs(A), axis=1)
+ if sps.issparse(A):
+ R = R.toarray().flatten()
+ R[R == 0] = 1
+ R = 1/_round_to_power_of_two(R)
+ A = sps.diags_array(R)@A if sps.issparse(A) else A*R.reshape(m, 1)
+ b = b*R
+
+ C = np.max(np.abs(A), axis=0)
+ if sps.issparse(A):
+ C = C.toarray().flatten()
+ C[C == 0] = 1
+ C = 1/_round_to_power_of_two(C)
+ A = A@sps.diags_array(C) if sps.issparse(A) else A*C
+ c = c*C
+
+ b_scale = np.max(np.abs(b)) if b.size > 0 else 1
+ if b_scale == 0:
+ b_scale = 1.
+ b = b/b_scale
+
+ if x0 is not None:
+ x0 = x0/b_scale*(1/C)
+ return A, b, c, x0, C, b_scale
+
+
+def _unscale(x, C, b_scale):
+ """
+ Converts solution to _autoscale problem -> solution to original problem.
+ """
+
+ try:
+ n = len(C)
+ # fails if sparse or scalar; that's OK.
+ # this is only needed for original simplex (never sparse)
+ except TypeError:
+ n = len(x)
+
+ return x[:n]*b_scale*C
+
+
+def _display_summary(message, status, fun, iteration):
+ """
+ Print the termination summary of the linear program
+
+ Parameters
+ ----------
+ message : str
+ A string descriptor of the exit status of the optimization.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ fun : float
+ Value of the objective function.
+ iteration : iteration
+ The number of iterations performed.
+ """
+ print(message)
+ if status in (0, 1):
+ print(f" Current function value: {fun: <12.6f}")
+ print(f" Iterations: {iteration:d}")
+
+
+def _postsolve(x, postsolve_args, complete=False):
+ """
+ Given solution x to presolved, standard form linear program x, add
+ fixed variables back into the problem and undo the variable substitutions
+ to get solution to original linear program. Also, calculate the objective
+ function value, slack in original upper bound constraints, and residuals
+ in original equality constraints.
+
+ Parameters
+ ----------
+ x : 1-D array
+ Solution vector to the standard-form problem.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem, including:
+
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, lower bounds in the 1st column, upper
+ bounds in the 2nd column. The bounds are possibly tightened
+ by the presolve procedure.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ revstack: list of functions
+ the functions in the list reverse the operations of _presolve()
+ the function signature is x_org = f(x_mod), where x_mod is the result
+ of a presolve step and x_org the value at the start of the step
+ complete : bool
+ Whether the solution is was determined in presolve (``True`` if so)
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector to original linear programming problem
+ fun: float
+ optimal objective value for original problem
+ slack : 1-D array
+ The (non-negative) slack in the upper bound constraints, that is,
+ ``b_ub - A_ub @ x``
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``
+ """
+ # note that all the inputs are the ORIGINAL, unmodified versions
+ # no rows, columns have been removed
+
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = postsolve_args[0]
+ revstack, C, b_scale = postsolve_args[1:]
+
+ x = _unscale(x, C, b_scale)
+
+ # Undo variable substitutions of _get_Abc()
+ # if "complete", problem was solved in presolve; don't do anything here
+ n_x = bounds.shape[0]
+ if not complete and bounds is not None: # bounds are never none, probably
+ n_unbounded = 0
+ for i, bi in enumerate(bounds):
+ lbi = bi[0]
+ ubi = bi[1]
+ if lbi == -np.inf and ubi == np.inf:
+ n_unbounded += 1
+ x[i] = x[i] - x[n_x + n_unbounded - 1]
+ else:
+ if lbi == -np.inf:
+ x[i] = ubi - x[i]
+ else:
+ x[i] += lbi
+ # all the rest of the variables were artificial
+ x = x[:n_x]
+
+ # If there were variables removed from the problem, add them back into the
+ # solution vector
+ # Apply the functions in revstack (reverse direction)
+ for rev in reversed(revstack):
+ x = rev(x)
+
+ fun = x.dot(c)
+ with np.errstate(invalid="ignore"):
+ slack = b_ub - A_ub.dot(x) # report slack for ORIGINAL UB constraints
+ # report residuals of ORIGINAL EQ constraints
+ con = b_eq - A_eq.dot(x)
+
+ return x, fun, slack, con
+
+
+def _check_result(x, fun, status, slack, con, bounds, tol, message,
+ integrality):
+ """
+ Check the validity of the provided solution.
+
+ A valid (optimal) solution satisfies all bounds, all slack variables are
+ negative and all equality constraint residuals are strictly non-zero.
+ Further, the lower-bounds, upper-bounds, slack and residuals contain
+ no nan values.
+
+ Parameters
+ ----------
+ x : 1-D array
+ Solution vector to original linear programming problem
+ fun: float
+ optimal objective value for original problem
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ slack : 1-D array
+ The (non-negative) slack in the upper bound constraints, that is,
+ ``b_ub - A_ub @ x``
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``
+ bounds : 2D array
+ The bounds on the original variables ``x``
+ message : str
+ A string descriptor of the exit status of the optimization.
+ tol : float
+ Termination tolerance; see [1]_ Section 4.5.
+
+ Returns
+ -------
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ """
+ # Somewhat arbitrary
+ tol = np.sqrt(tol) * 10
+
+ if x is None:
+ # HiGHS does not provide x if infeasible/unbounded
+ if status == 0: # Observed with HiGHS Simplex Primal
+ status = 4
+ message = ("The solver did not provide a solution nor did it "
+ "report a failure. Please submit a bug report.")
+ return status, message
+
+ contains_nans = (
+ np.isnan(x).any()
+ or np.isnan(fun)
+ or np.isnan(slack).any()
+ or np.isnan(con).any()
+ )
+
+ if contains_nans:
+ is_feasible = False
+ else:
+ if integrality is None:
+ integrality = 0
+ valid_bounds = (x >= bounds[:, 0] - tol) & (x <= bounds[:, 1] + tol)
+ # When integrality is 2 or 3, x must be within bounds OR take value 0
+ valid_bounds |= (integrality > 1) & np.isclose(x, 0, atol=tol)
+ invalid_bounds = not np.all(valid_bounds)
+
+ invalid_slack = status != 3 and (slack < -tol).any()
+ invalid_con = status != 3 and (np.abs(con) > tol).any()
+ is_feasible = not (invalid_bounds or invalid_slack or invalid_con)
+
+ if status == 0 and not is_feasible:
+ status = 4
+ message = ("The solution does not satisfy the constraints within the "
+ "required tolerance of " + f"{tol:.2E}" + ", yet "
+ "no errors were raised and there is no certificate of "
+ "infeasibility or unboundedness. Check whether "
+ "the slack and constraint residuals are acceptable; "
+ "if not, consider enabling presolve, adjusting the "
+ "tolerance option(s), and/or using a different method. "
+ "Please consider submitting a bug report.")
+ elif status == 2 and is_feasible:
+ # Occurs if the simplex method exits after phase one with a very
+ # nearly basic feasible solution. Postsolving can make the solution
+ # basic, however, this solution is NOT optimal
+ status = 4
+ message = ("The solution is feasible, but the solver did not report "
+ "that the solution was optimal. Please try a different "
+ "method.")
+
+ return status, message
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsap.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsap.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..f24572fb179393ce3b8d291f51d107393da637aa
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsap.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f60adcc891304e34ac9d85d108b6a232b4bf0c93
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/__init__.py
@@ -0,0 +1,5 @@
+"""This module contains least-squares algorithms."""
+from .least_squares import least_squares
+from .lsq_linear import lsq_linear
+
+__all__ = ['least_squares', 'lsq_linear']
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/bvls.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/bvls.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f34ead4a1fc4edbb3c2ab50a204aa9a3cc21cff
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/bvls.py
@@ -0,0 +1,183 @@
+"""Bounded-variable least-squares algorithm."""
+import numpy as np
+from numpy.linalg import norm, lstsq
+from scipy.optimize import OptimizeResult
+
+from .common import print_header_linear, print_iteration_linear
+
+
+def compute_kkt_optimality(g, on_bound):
+ """Compute the maximum violation of KKT conditions."""
+ g_kkt = g * on_bound
+ free_set = on_bound == 0
+ g_kkt[free_set] = np.abs(g[free_set])
+ return np.max(g_kkt)
+
+
+def bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose, rcond=None):
+ m, n = A.shape
+
+ x = x_lsq.copy()
+ on_bound = np.zeros(n)
+
+ mask = x <= lb
+ x[mask] = lb[mask]
+ on_bound[mask] = -1
+
+ mask = x >= ub
+ x[mask] = ub[mask]
+ on_bound[mask] = 1
+
+ free_set = on_bound == 0
+ active_set = ~free_set
+ free_set, = np.nonzero(free_set)
+
+ r = A.dot(x) - b
+ cost = 0.5 * np.dot(r, r)
+ initial_cost = cost
+ g = A.T.dot(r)
+
+ cost_change = None
+ step_norm = None
+ iteration = 0
+
+ if verbose == 2:
+ print_header_linear()
+
+ # This is the initialization loop. The requirement is that the
+ # least-squares solution on free variables is feasible before BVLS starts.
+ # One possible initialization is to set all variables to lower or upper
+ # bounds, but many iterations may be required from this state later on.
+ # The implemented ad-hoc procedure which intuitively should give a better
+ # initial state: find the least-squares solution on current free variables,
+ # if its feasible then stop, otherwise, set violating variables to
+ # corresponding bounds and continue on the reduced set of free variables.
+
+ while free_set.size > 0:
+ if verbose == 2:
+ optimality = compute_kkt_optimality(g, on_bound)
+ print_iteration_linear(iteration, cost, cost_change, step_norm,
+ optimality)
+
+ iteration += 1
+ x_free_old = x[free_set].copy()
+
+ A_free = A[:, free_set]
+ b_free = b - A.dot(x * active_set)
+ z = lstsq(A_free, b_free, rcond=rcond)[0]
+
+ lbv = z < lb[free_set]
+ ubv = z > ub[free_set]
+ v = lbv | ubv
+
+ if np.any(lbv):
+ ind = free_set[lbv]
+ x[ind] = lb[ind]
+ active_set[ind] = True
+ on_bound[ind] = -1
+
+ if np.any(ubv):
+ ind = free_set[ubv]
+ x[ind] = ub[ind]
+ active_set[ind] = True
+ on_bound[ind] = 1
+
+ ind = free_set[~v]
+ x[ind] = z[~v]
+
+ r = A.dot(x) - b
+ cost_new = 0.5 * np.dot(r, r)
+ cost_change = cost - cost_new
+ cost = cost_new
+ g = A.T.dot(r)
+ step_norm = norm(x[free_set] - x_free_old)
+
+ if np.any(v):
+ free_set = free_set[~v]
+ else:
+ break
+
+ if max_iter is None:
+ max_iter = n
+ max_iter += iteration
+
+ termination_status = None
+
+ # Main BVLS loop.
+
+ optimality = compute_kkt_optimality(g, on_bound)
+ for iteration in range(iteration, max_iter): # BVLS Loop A
+ if verbose == 2:
+ print_iteration_linear(iteration, cost, cost_change,
+ step_norm, optimality)
+
+ if optimality < tol:
+ termination_status = 1
+
+ if termination_status is not None:
+ break
+
+ move_to_free = np.argmax(g * on_bound)
+ on_bound[move_to_free] = 0
+
+ while True: # BVLS Loop B
+
+ free_set = on_bound == 0
+ active_set = ~free_set
+ free_set, = np.nonzero(free_set)
+
+ x_free = x[free_set]
+ x_free_old = x_free.copy()
+ lb_free = lb[free_set]
+ ub_free = ub[free_set]
+
+ A_free = A[:, free_set]
+ b_free = b - A.dot(x * active_set)
+ z = lstsq(A_free, b_free, rcond=rcond)[0]
+
+ lbv, = np.nonzero(z < lb_free)
+ ubv, = np.nonzero(z > ub_free)
+ v = np.hstack((lbv, ubv))
+
+ if v.size > 0:
+ alphas = np.hstack((
+ lb_free[lbv] - x_free[lbv],
+ ub_free[ubv] - x_free[ubv])) / (z[v] - x_free[v])
+
+ i = np.argmin(alphas)
+ i_free = v[i]
+ alpha = alphas[i]
+
+ x_free *= 1 - alpha
+ x_free += alpha * z
+ x[free_set] = x_free
+
+ if i < lbv.size:
+ on_bound[free_set[i_free]] = -1
+ else:
+ on_bound[free_set[i_free]] = 1
+ else:
+ x_free = z
+ x[free_set] = x_free
+ break
+
+ step_norm = norm(x_free - x_free_old)
+
+ r = A.dot(x) - b
+ cost_new = 0.5 * np.dot(r, r)
+ cost_change = cost - cost_new
+
+ if cost_change < tol * cost:
+ termination_status = 2
+ cost = cost_new
+
+ g = A.T.dot(r)
+ optimality = compute_kkt_optimality(g, on_bound)
+
+ if termination_status is None:
+ termination_status = 0
+
+ return OptimizeResult(
+ x=x, fun=r, cost=cost, optimality=optimality, active_mask=on_bound,
+ nit=iteration + 1, status=termination_status,
+ initial_cost=initial_cost)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/common.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..6943e9d5c21ed504760920eb2129b3029eaa0407
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/common.py
@@ -0,0 +1,731 @@
+"""Functions used by least-squares algorithms."""
+from math import copysign
+
+import numpy as np
+from numpy.linalg import norm
+
+from scipy.linalg import cho_factor, cho_solve, LinAlgError
+from scipy.sparse.linalg import LinearOperator, aslinearoperator
+from scipy._lib._sparse import issparse
+
+
+EPS = np.finfo(float).eps
+
+
+# Functions related to a trust-region problem.
+
+
+def intersect_trust_region(x, s, Delta):
+ """Find the intersection of a line with the boundary of a trust region.
+
+ This function solves the quadratic equation with respect to t
+ ||(x + s*t)||**2 = Delta**2.
+
+ Returns
+ -------
+ t_neg, t_pos : tuple of float
+ Negative and positive roots.
+
+ Raises
+ ------
+ ValueError
+ If `s` is zero or `x` is not within the trust region.
+ """
+ a = np.dot(s, s)
+ if a == 0:
+ raise ValueError("`s` is zero.")
+
+ b = np.dot(x, s)
+
+ c = np.dot(x, x) - Delta**2
+ if c > 0:
+ raise ValueError("`x` is not within the trust region.")
+
+ d = np.sqrt(b*b - a*c) # Root from one fourth of the discriminant.
+
+ # Computations below avoid loss of significance, see "Numerical Recipes".
+ q = -(b + copysign(d, b))
+ t1 = q / a
+ t2 = c / q
+
+ if t1 < t2:
+ return t1, t2
+ else:
+ return t2, t1
+
+
+def solve_lsq_trust_region(n, m, uf, s, V, Delta, initial_alpha=None,
+ rtol=0.01, max_iter=10):
+ """Solve a trust-region problem arising in least-squares minimization.
+
+ This function implements a method described by J. J. More [1]_ and used
+ in MINPACK, but it relies on a single SVD of Jacobian instead of series
+ of Cholesky decompositions. Before running this function, compute:
+ ``U, s, VT = svd(J, full_matrices=False)``.
+
+ Parameters
+ ----------
+ n : int
+ Number of variables.
+ m : int
+ Number of residuals.
+ uf : ndarray
+ Computed as U.T.dot(f).
+ s : ndarray
+ Singular values of J.
+ V : ndarray
+ Transpose of VT.
+ Delta : float
+ Radius of a trust region.
+ initial_alpha : float, optional
+ Initial guess for alpha, which might be available from a previous
+ iteration. If None, determined automatically.
+ rtol : float, optional
+ Stopping tolerance for the root-finding procedure. Namely, the
+ solution ``p`` will satisfy ``abs(norm(p) - Delta) < rtol * Delta``.
+ max_iter : int, optional
+ Maximum allowed number of iterations for the root-finding procedure.
+
+ Returns
+ -------
+ p : ndarray, shape (n,)
+ Found solution of a trust-region problem.
+ alpha : float
+ Positive value such that (J.T*J + alpha*I)*p = -J.T*f.
+ Sometimes called Levenberg-Marquardt parameter.
+ n_iter : int
+ Number of iterations made by root-finding procedure. Zero means
+ that Gauss-Newton step was selected as the solution.
+
+ References
+ ----------
+ .. [1] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture Notes
+ in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
+ """
+ def phi_and_derivative(alpha, suf, s, Delta):
+ """Function of which to find zero.
+
+ It is defined as "norm of regularized (by alpha) least-squares
+ solution minus `Delta`". Refer to [1]_.
+ """
+ denom = s**2 + alpha
+ p_norm = norm(suf / denom)
+ phi = p_norm - Delta
+ phi_prime = -np.sum(suf ** 2 / denom**3) / p_norm
+ return phi, phi_prime
+
+ suf = s * uf
+
+ # Check if J has full rank and try Gauss-Newton step.
+ if m >= n:
+ threshold = EPS * m * s[0]
+ full_rank = s[-1] > threshold
+ else:
+ full_rank = False
+
+ if full_rank:
+ p = -V.dot(uf / s)
+ if norm(p) <= Delta:
+ return p, 0.0, 0
+
+ alpha_upper = norm(suf) / Delta
+
+ if full_rank:
+ phi, phi_prime = phi_and_derivative(0.0, suf, s, Delta)
+ alpha_lower = -phi / phi_prime
+ else:
+ alpha_lower = 0.0
+
+ if initial_alpha is None or not full_rank and initial_alpha == 0:
+ alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5)
+ else:
+ alpha = initial_alpha
+
+ for it in range(max_iter):
+ if alpha < alpha_lower or alpha > alpha_upper:
+ alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5)
+
+ phi, phi_prime = phi_and_derivative(alpha, suf, s, Delta)
+
+ if phi < 0:
+ alpha_upper = alpha
+
+ ratio = phi / phi_prime
+ alpha_lower = max(alpha_lower, alpha - ratio)
+ alpha -= (phi + Delta) * ratio / Delta
+
+ if np.abs(phi) < rtol * Delta:
+ break
+
+ p = -V.dot(suf / (s**2 + alpha))
+
+ # Make the norm of p equal to Delta, p is changed only slightly during
+ # this. It is done to prevent p lie outside the trust region (which can
+ # cause problems later).
+ p *= Delta / norm(p)
+
+ return p, alpha, it + 1
+
+
+def solve_trust_region_2d(B, g, Delta):
+ """Solve a general trust-region problem in 2 dimensions.
+
+ The problem is reformulated as a 4th order algebraic equation,
+ the solution of which is found by numpy.roots.
+
+ Parameters
+ ----------
+ B : ndarray, shape (2, 2)
+ Symmetric matrix, defines a quadratic term of the function.
+ g : ndarray, shape (2,)
+ Defines a linear term of the function.
+ Delta : float
+ Radius of a trust region.
+
+ Returns
+ -------
+ p : ndarray, shape (2,)
+ Found solution.
+ newton_step : bool
+ Whether the returned solution is the Newton step which lies within
+ the trust region.
+ """
+ try:
+ R, lower = cho_factor(B)
+ p = -cho_solve((R, lower), g)
+ if np.dot(p, p) <= Delta**2:
+ return p, True
+ except LinAlgError:
+ pass
+
+ a = B[0, 0] * Delta**2
+ b = B[0, 1] * Delta**2
+ c = B[1, 1] * Delta**2
+
+ d = g[0] * Delta
+ f = g[1] * Delta
+
+ coeffs = np.array(
+ [-b + d, 2 * (a - c + f), 6 * b, 2 * (-a + c + f), -b - d])
+ t = np.roots(coeffs) # Can handle leading zeros.
+ t = np.real(t[np.isreal(t)])
+
+ p = Delta * np.vstack((2 * t / (1 + t**2), (1 - t**2) / (1 + t**2)))
+ value = 0.5 * np.sum(p * B.dot(p), axis=0) + np.dot(g, p)
+ i = np.argmin(value)
+ p = p[:, i]
+
+ return p, False
+
+
+def update_tr_radius(Delta, actual_reduction, predicted_reduction,
+ step_norm, bound_hit):
+ """Update the radius of a trust region based on the cost reduction.
+
+ Returns
+ -------
+ Delta : float
+ New radius.
+ ratio : float
+ Ratio between actual and predicted reductions.
+ """
+ if predicted_reduction > 0:
+ ratio = actual_reduction / predicted_reduction
+ elif predicted_reduction == actual_reduction == 0:
+ ratio = 1
+ else:
+ ratio = 0
+
+ if ratio < 0.25:
+ Delta = 0.25 * step_norm
+ elif ratio > 0.75 and bound_hit:
+ Delta *= 2.0
+
+ return Delta, ratio
+
+
+# Construction and minimization of quadratic functions.
+
+
+def build_quadratic_1d(J, g, s, diag=None, s0=None):
+ """Parameterize a multivariate quadratic function along a line.
+
+ The resulting univariate quadratic function is given as follows::
+
+ f(t) = 0.5 * (s0 + s*t).T * (J.T*J + diag) * (s0 + s*t) +
+ g.T * (s0 + s*t)
+
+ Parameters
+ ----------
+ J : ndarray, sparse array or LinearOperator shape (m, n)
+ Jacobian matrix, affects the quadratic term.
+ g : ndarray, shape (n,)
+ Gradient, defines the linear term.
+ s : ndarray, shape (n,)
+ Direction vector of a line.
+ diag : None or ndarray with shape (n,), optional
+ Addition diagonal part, affects the quadratic term.
+ If None, assumed to be 0.
+ s0 : None or ndarray with shape (n,), optional
+ Initial point. If None, assumed to be 0.
+
+ Returns
+ -------
+ a : float
+ Coefficient for t**2.
+ b : float
+ Coefficient for t.
+ c : float
+ Free term. Returned only if `s0` is provided.
+ """
+ v = J.dot(s)
+ a = np.dot(v, v)
+ if diag is not None:
+ a += np.dot(s * diag, s)
+ a *= 0.5
+
+ b = np.dot(g, s)
+
+ if s0 is not None:
+ u = J.dot(s0)
+ b += np.dot(u, v)
+ c = 0.5 * np.dot(u, u) + np.dot(g, s0)
+ if diag is not None:
+ b += np.dot(s0 * diag, s)
+ c += 0.5 * np.dot(s0 * diag, s0)
+ return a, b, c
+ else:
+ return a, b
+
+
+def minimize_quadratic_1d(a, b, lb, ub, c=0):
+ """Minimize a 1-D quadratic function subject to bounds.
+
+ The free term `c` is 0 by default. Bounds must be finite.
+
+ Returns
+ -------
+ t : float
+ Minimum point.
+ y : float
+ Minimum value.
+ """
+ t = [lb, ub]
+ if a != 0:
+ extremum = -0.5 * b / a
+ if lb < extremum < ub:
+ t.append(extremum)
+ t = np.asarray(t)
+ y = t * (a * t + b) + c
+ min_index = np.argmin(y)
+ return t[min_index], y[min_index]
+
+
+def evaluate_quadratic(J, g, s, diag=None):
+ """Compute values of a quadratic function arising in least squares.
+
+ The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s.
+
+ Parameters
+ ----------
+ J : ndarray, sparse array or LinearOperator, shape (m, n)
+ Jacobian matrix, affects the quadratic term.
+ g : ndarray, shape (n,)
+ Gradient, defines the linear term.
+ s : ndarray, shape (k, n) or (n,)
+ Array containing steps as rows.
+ diag : ndarray, shape (n,), optional
+ Addition diagonal part, affects the quadratic term.
+ If None, assumed to be 0.
+
+ Returns
+ -------
+ values : ndarray with shape (k,) or float
+ Values of the function. If `s` was 2-D, then ndarray is
+ returned, otherwise, float is returned.
+ """
+ if s.ndim == 1:
+ Js = J.dot(s)
+ q = np.dot(Js, Js)
+ if diag is not None:
+ q += np.dot(s * diag, s)
+ else:
+ Js = J.dot(s.T)
+ q = np.sum(Js**2, axis=0)
+ if diag is not None:
+ q += np.sum(diag * s**2, axis=1)
+
+ l = np.dot(s, g)
+
+ return 0.5 * q + l
+
+
+# Utility functions to work with bound constraints.
+
+
+def in_bounds(x, lb, ub):
+ """Check if a point lies within bounds."""
+ return np.all((x >= lb) & (x <= ub))
+
+
+def step_size_to_bound(x, s, lb, ub):
+ """Compute a min_step size required to reach a bound.
+
+ The function computes a positive scalar t, such that x + s * t is on
+ the bound.
+
+ Returns
+ -------
+ step : float
+ Computed step. Non-negative value.
+ hits : ndarray of int with shape of x
+ Each element indicates whether a corresponding variable reaches the
+ bound:
+
+ * 0 - the bound was not hit.
+ * -1 - the lower bound was hit.
+ * 1 - the upper bound was hit.
+ """
+ non_zero = np.nonzero(s)
+ s_non_zero = s[non_zero]
+ steps = np.empty_like(x)
+ steps.fill(np.inf)
+ with np.errstate(over='ignore'):
+ steps[non_zero] = np.maximum((lb - x)[non_zero] / s_non_zero,
+ (ub - x)[non_zero] / s_non_zero)
+ min_step = np.min(steps)
+ return min_step, np.equal(steps, min_step) * np.sign(s).astype(int)
+
+
+def find_active_constraints(x, lb, ub, rtol=1e-10):
+ """Determine which constraints are active in a given point.
+
+ The threshold is computed using `rtol` and the absolute value of the
+ closest bound.
+
+ Returns
+ -------
+ active : ndarray of int with shape of x
+ Each component shows whether the corresponding constraint is active:
+
+ * 0 - a constraint is not active.
+ * -1 - a lower bound is active.
+ * 1 - an upper bound is active.
+ """
+ active = np.zeros_like(x, dtype=int)
+
+ if rtol == 0:
+ active[x <= lb] = -1
+ active[x >= ub] = 1
+ return active
+
+ lower_dist = x - lb
+ upper_dist = ub - x
+
+ lower_threshold = rtol * np.maximum(1, np.abs(lb))
+ upper_threshold = rtol * np.maximum(1, np.abs(ub))
+
+ lower_active = (np.isfinite(lb) &
+ (lower_dist <= np.minimum(upper_dist, lower_threshold)))
+ active[lower_active] = -1
+
+ upper_active = (np.isfinite(ub) &
+ (upper_dist <= np.minimum(lower_dist, upper_threshold)))
+ active[upper_active] = 1
+
+ return active
+
+
+def make_strictly_feasible(x, lb, ub, rstep=1e-10):
+ """Shift a point to the interior of a feasible region.
+
+ Each element of the returned vector is at least at a relative distance
+ `rstep` from the closest bound. If ``rstep=0`` then `np.nextafter` is used.
+ """
+ x_new = x.copy()
+
+ active = find_active_constraints(x, lb, ub, rstep)
+ lower_mask = np.equal(active, -1)
+ upper_mask = np.equal(active, 1)
+
+ if rstep == 0:
+ x_new[lower_mask] = np.nextafter(lb[lower_mask], ub[lower_mask])
+ x_new[upper_mask] = np.nextafter(ub[upper_mask], lb[upper_mask])
+ else:
+ x_new[lower_mask] = (lb[lower_mask] +
+ rstep * np.maximum(1, np.abs(lb[lower_mask])))
+ x_new[upper_mask] = (ub[upper_mask] -
+ rstep * np.maximum(1, np.abs(ub[upper_mask])))
+
+ tight_bounds = (x_new < lb) | (x_new > ub)
+ x_new[tight_bounds] = 0.5 * (lb[tight_bounds] + ub[tight_bounds])
+
+ return x_new
+
+
+def CL_scaling_vector(x, g, lb, ub):
+ """Compute Coleman-Li scaling vector and its derivatives.
+
+ Components of a vector v are defined as follows::
+
+ | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
+ v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
+ | 1, otherwise
+
+ According to this definition v[i] >= 0 for all i. It differs from the
+ definition in paper [1]_ (eq. (2.2)), where the absolute value of v is
+ used. Both definitions are equivalent down the line.
+ Derivatives of v with respect to x take value 1, -1 or 0 depending on a
+ case.
+
+ Returns
+ -------
+ v : ndarray with shape of x
+ Scaling vector.
+ dv : ndarray with shape of x
+ Derivatives of v[i] with respect to x[i], diagonal elements of v's
+ Jacobian.
+
+ References
+ ----------
+ .. [1] M.A. Branch, T.F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+ """
+ v = np.ones_like(x)
+ dv = np.zeros_like(x)
+
+ mask = (g < 0) & np.isfinite(ub)
+ v[mask] = ub[mask] - x[mask]
+ dv[mask] = -1
+
+ mask = (g > 0) & np.isfinite(lb)
+ v[mask] = x[mask] - lb[mask]
+ dv[mask] = 1
+
+ return v, dv
+
+
+def reflective_transformation(y, lb, ub):
+ """Compute reflective transformation and its gradient."""
+ if in_bounds(y, lb, ub):
+ return y, np.ones_like(y)
+
+ lb_finite = np.isfinite(lb)
+ ub_finite = np.isfinite(ub)
+
+ x = y.copy()
+ g_negative = np.zeros_like(y, dtype=bool)
+
+ mask = lb_finite & ~ub_finite
+ x[mask] = np.maximum(y[mask], 2 * lb[mask] - y[mask])
+ g_negative[mask] = y[mask] < lb[mask]
+
+ mask = ~lb_finite & ub_finite
+ x[mask] = np.minimum(y[mask], 2 * ub[mask] - y[mask])
+ g_negative[mask] = y[mask] > ub[mask]
+
+ mask = lb_finite & ub_finite
+ d = ub - lb
+ t = np.remainder(y[mask] - lb[mask], 2 * d[mask])
+ x[mask] = lb[mask] + np.minimum(t, 2 * d[mask] - t)
+ g_negative[mask] = t > d[mask]
+
+ g = np.ones_like(y)
+ g[g_negative] = -1
+
+ return x, g
+
+
+# Functions to display algorithm's progress.
+
+
+def print_header_nonlinear():
+ print("{:^15}{:^15}{:^15}{:^15}{:^15}{:^15}"
+ .format("Iteration", "Total nfev", "Cost", "Cost reduction",
+ "Step norm", "Optimality"))
+
+
+def print_iteration_nonlinear(iteration, nfev, cost, cost_reduction,
+ step_norm, optimality):
+ if cost_reduction is None:
+ cost_reduction = " " * 15
+ else:
+ cost_reduction = f"{cost_reduction:^15.2e}"
+
+ if step_norm is None:
+ step_norm = " " * 15
+ else:
+ step_norm = f"{step_norm:^15.2e}"
+
+ print(f"{iteration:^15}{nfev:^15}{cost:^15.4e}{cost_reduction}{step_norm}{optimality:^15.2e}")
+
+
+def print_header_linear():
+ print("{:^15}{:^15}{:^15}{:^15}{:^15}"
+ .format("Iteration", "Cost", "Cost reduction", "Step norm",
+ "Optimality"))
+
+
+def print_iteration_linear(iteration, cost, cost_reduction, step_norm,
+ optimality):
+ if cost_reduction is None:
+ cost_reduction = " " * 15
+ else:
+ cost_reduction = f"{cost_reduction:^15.2e}"
+
+ if step_norm is None:
+ step_norm = " " * 15
+ else:
+ step_norm = f"{step_norm:^15.2e}"
+
+ print(f"{iteration:^15}{cost:^15.4e}{cost_reduction}{step_norm}{optimality:^15.2e}")
+
+
+# Simple helper functions.
+
+
+def compute_grad(J, f):
+ """Compute gradient of the least-squares cost function."""
+ if isinstance(J, LinearOperator):
+ return J.rmatvec(f)
+ else:
+ return J.T.dot(f)
+
+
+def compute_jac_scale(J, scale_inv_old=None):
+ """Compute variables scale based on the Jacobian matrix."""
+ if issparse(J):
+ scale_inv = np.asarray(J.power(2).sum(axis=0)).ravel()**0.5
+ else:
+ scale_inv = np.sum(J**2, axis=0)**0.5
+
+ if scale_inv_old is None:
+ scale_inv[scale_inv == 0] = 1
+ else:
+ scale_inv = np.maximum(scale_inv, scale_inv_old)
+
+ return 1 / scale_inv, scale_inv
+
+
+def left_multiplied_operator(J, d):
+ """Return diag(d) J as LinearOperator."""
+ J = aslinearoperator(J)
+
+ def matvec(x):
+ return d * J.matvec(x)
+
+ def matmat(X):
+ return d[:, np.newaxis] * J.matmat(X)
+
+ def rmatvec(x):
+ return J.rmatvec(x.ravel() * d)
+
+ return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
+ rmatvec=rmatvec)
+
+
+def right_multiplied_operator(J, d):
+ """Return J diag(d) as LinearOperator."""
+ J = aslinearoperator(J)
+
+ def matvec(x):
+ return J.matvec(np.ravel(x) * d)
+
+ def matmat(X):
+ return J.matmat(X * d[:, np.newaxis])
+
+ def rmatvec(x):
+ return d * J.rmatvec(x)
+
+ return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
+ rmatvec=rmatvec)
+
+
+def regularized_lsq_operator(J, diag):
+ """Return a matrix arising in regularized least squares as LinearOperator.
+
+ The matrix is
+ [ J ]
+ [ D ]
+ where D is diagonal matrix with elements from `diag`.
+ """
+ J = aslinearoperator(J)
+ m, n = J.shape
+
+ def matvec(x):
+ return np.hstack((J.matvec(x), diag * x))
+
+ def rmatvec(x):
+ x1 = x[:m]
+ x2 = x[m:]
+ return J.rmatvec(x1) + diag * x2
+
+ return LinearOperator((m + n, n), matvec=matvec, rmatvec=rmatvec)
+
+
+def right_multiply(J, d, copy=True):
+ """Compute J diag(d).
+
+ If `copy` is False, `J` is modified in place (unless being LinearOperator).
+ """
+ if copy and not isinstance(J, LinearOperator):
+ J = J.copy()
+
+ if issparse(J):
+ J.data *= d.take(J.indices, mode='clip') # scikit-learn recipe.
+ elif isinstance(J, LinearOperator):
+ J = right_multiplied_operator(J, d)
+ else:
+ J *= d
+
+ return J
+
+
+def left_multiply(J, d, copy=True):
+ """Compute diag(d) J.
+
+ If `copy` is False, `J` is modified in place (unless being LinearOperator).
+ """
+ if copy and not isinstance(J, LinearOperator):
+ J = J.copy()
+
+ if issparse(J):
+ J.data *= np.repeat(d, np.diff(J.indptr)) # scikit-learn recipe.
+ elif isinstance(J, LinearOperator):
+ J = left_multiplied_operator(J, d)
+ else:
+ J *= d[:, np.newaxis]
+
+ return J
+
+
+def check_termination(dF, F, dx_norm, x_norm, ratio, ftol, xtol):
+ """Check termination condition for nonlinear least squares."""
+ ftol_satisfied = dF < ftol * F and ratio > 0.25
+ xtol_satisfied = dx_norm < xtol * (xtol + x_norm)
+
+ if ftol_satisfied and xtol_satisfied:
+ return 4
+ elif ftol_satisfied:
+ return 2
+ elif xtol_satisfied:
+ return 3
+ else:
+ return None
+
+
+def scale_for_robust_loss_function(J, f, rho):
+ """Scale Jacobian and residuals for a robust loss function.
+
+ Arrays are modified in place.
+ """
+ J_scale = rho[1] + 2 * rho[2] * f**2
+ J_scale[J_scale < EPS] = EPS
+ J_scale **= 0.5
+
+ f *= rho[1] / J_scale
+
+ return left_multiply(J, J_scale, copy=False), f
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..7694c75d491bb014ff8e9b338d37cafdf9bec8a0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.py
@@ -0,0 +1,345 @@
+"""
+Dogleg algorithm with rectangular trust regions for least-squares minimization.
+
+The description of the algorithm can be found in [Voglis]_. The algorithm does
+trust-region iterations, but the shape of trust regions is rectangular as
+opposed to conventional elliptical. The intersection of a trust region and
+an initial feasible region is again some rectangle. Thus, on each iteration a
+bound-constrained quadratic optimization problem is solved.
+
+A quadratic problem is solved by well-known dogleg approach, where the
+function is minimized along piecewise-linear "dogleg" path [NumOpt]_,
+Chapter 4. If Jacobian is not rank-deficient then the function is decreasing
+along this path, and optimization amounts to simply following along this
+path as long as a point stays within the bounds. A constrained Cauchy step
+(along the anti-gradient) is considered for safety in rank deficient cases,
+in this situations the convergence might be slow.
+
+If during iterations some variable hit the initial bound and the component
+of anti-gradient points outside the feasible region, then a next dogleg step
+won't make any progress. At this state such variables satisfy first-order
+optimality conditions and they are excluded before computing a next dogleg
+step.
+
+Gauss-Newton step can be computed exactly by `numpy.linalg.lstsq` (for dense
+Jacobian matrices) or by iterative procedure `scipy.sparse.linalg.lsmr` (for
+dense and sparse matrices, or Jacobian being LinearOperator). The second
+option allows to solve very large problems (up to couple of millions of
+residuals on a regular PC), provided the Jacobian matrix is sufficiently
+sparse. But note that dogbox is not very good for solving problems with
+large number of constraints, because of variables exclusion-inclusion on each
+iteration (a required number of function evaluations might be high or accuracy
+of a solution will be poor), thus its large-scale usage is probably limited
+to unconstrained problems.
+
+References
+----------
+.. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region Dogleg
+ Approach for Unconstrained and Bound Constrained Nonlinear
+ Optimization", WSEAS International Conference on Applied
+ Mathematics, Corfu, Greece, 2004.
+.. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization, 2nd edition".
+"""
+import numpy as np
+from numpy.linalg import lstsq, norm
+
+from scipy.sparse.linalg import LinearOperator, aslinearoperator, lsmr
+from scipy.optimize import OptimizeResult
+from scipy._lib._util import _call_callback_maybe_halt
+
+
+from .common import (
+ step_size_to_bound, in_bounds, update_tr_radius, evaluate_quadratic,
+ build_quadratic_1d, minimize_quadratic_1d, compute_grad,
+ compute_jac_scale, check_termination, scale_for_robust_loss_function,
+ print_header_nonlinear, print_iteration_nonlinear)
+
+
+def lsmr_operator(Jop, d, active_set):
+ """Compute LinearOperator to use in LSMR by dogbox algorithm.
+
+ `active_set` mask is used to excluded active variables from computations
+ of matrix-vector products.
+ """
+ m, n = Jop.shape
+
+ def matvec(x):
+ x_free = x.ravel().copy()
+ x_free[active_set] = 0
+ return Jop.matvec(x * d)
+
+ def rmatvec(x):
+ r = d * Jop.rmatvec(x)
+ r[active_set] = 0
+ return r
+
+ return LinearOperator((m, n), matvec=matvec, rmatvec=rmatvec, dtype=float)
+
+
+def find_intersection(x, tr_bounds, lb, ub):
+ """Find intersection of trust-region bounds and initial bounds.
+
+ Returns
+ -------
+ lb_total, ub_total : ndarray with shape of x
+ Lower and upper bounds of the intersection region.
+ orig_l, orig_u : ndarray of bool with shape of x
+ True means that an original bound is taken as a corresponding bound
+ in the intersection region.
+ tr_l, tr_u : ndarray of bool with shape of x
+ True means that a trust-region bound is taken as a corresponding bound
+ in the intersection region.
+ """
+ lb_centered = lb - x
+ ub_centered = ub - x
+
+ lb_total = np.maximum(lb_centered, -tr_bounds)
+ ub_total = np.minimum(ub_centered, tr_bounds)
+
+ orig_l = np.equal(lb_total, lb_centered)
+ orig_u = np.equal(ub_total, ub_centered)
+
+ tr_l = np.equal(lb_total, -tr_bounds)
+ tr_u = np.equal(ub_total, tr_bounds)
+
+ return lb_total, ub_total, orig_l, orig_u, tr_l, tr_u
+
+
+def dogleg_step(x, newton_step, g, a, b, tr_bounds, lb, ub):
+ """Find dogleg step in a rectangular region.
+
+ Returns
+ -------
+ step : ndarray, shape (n,)
+ Computed dogleg step.
+ bound_hits : ndarray of int, shape (n,)
+ Each component shows whether a corresponding variable hits the
+ initial bound after the step is taken:
+ * 0 - a variable doesn't hit the bound.
+ * -1 - lower bound is hit.
+ * 1 - upper bound is hit.
+ tr_hit : bool
+ Whether the step hit the boundary of the trust-region.
+ """
+ lb_total, ub_total, orig_l, orig_u, tr_l, tr_u = find_intersection(
+ x, tr_bounds, lb, ub
+ )
+ bound_hits = np.zeros_like(x, dtype=int)
+
+ if in_bounds(newton_step, lb_total, ub_total):
+ return newton_step, bound_hits, False
+
+ to_bounds, _ = step_size_to_bound(np.zeros_like(x), -g, lb_total, ub_total)
+
+ # The classical dogleg algorithm would check if Cauchy step fits into
+ # the bounds, and just return it constrained version if not. But in a
+ # rectangular trust region it makes sense to try to improve constrained
+ # Cauchy step too. Thus, we don't distinguish these two cases.
+
+ cauchy_step = -minimize_quadratic_1d(a, b, 0, to_bounds)[0] * g
+
+ step_diff = newton_step - cauchy_step
+ step_size, hits = step_size_to_bound(cauchy_step, step_diff,
+ lb_total, ub_total)
+ bound_hits[(hits < 0) & orig_l] = -1
+ bound_hits[(hits > 0) & orig_u] = 1
+ tr_hit = np.any((hits < 0) & tr_l | (hits > 0) & tr_u)
+
+ return cauchy_step + step_size * step_diff, bound_hits, tr_hit
+
+
+def dogbox(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=None):
+ f = f0
+ f_true = f.copy()
+ nfev = 1
+
+ J = J0
+ njev = 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ cost = 0.5 * np.sum(rho[0])
+ J, f = scale_for_robust_loss_function(J, f, rho)
+ else:
+ cost = 0.5 * np.dot(f, f)
+
+ g = compute_grad(J, f)
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J)
+ else:
+ scale, scale_inv = x_scale, 1 / x_scale
+
+ Delta = norm(x0 * scale_inv, ord=np.inf)
+ if Delta == 0:
+ Delta = 1.0
+
+ on_bound = np.zeros_like(x0, dtype=int)
+ on_bound[np.equal(x0, lb)] = -1
+ on_bound[np.equal(x0, ub)] = 1
+
+ x = x0
+ step = np.empty_like(x0)
+
+ if max_nfev is None:
+ max_nfev = x0.size * 100
+
+ termination_status = None
+ iteration = 0
+ step_norm = None
+ actual_reduction = None
+
+ if verbose == 2:
+ print_header_nonlinear()
+
+ while True:
+ active_set = on_bound * g < 0
+ free_set = ~active_set
+
+ g_free = g[free_set]
+ g_full = g.copy()
+ g[active_set] = 0
+
+ g_norm = norm(g, ord=np.inf)
+ if g_norm < gtol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
+ step_norm, g_norm)
+
+ if termination_status is not None or nfev == max_nfev:
+ break
+
+ x_free = x[free_set]
+ lb_free = lb[free_set]
+ ub_free = ub[free_set]
+ scale_free = scale[free_set]
+
+ # Compute (Gauss-)Newton and build quadratic model for Cauchy step.
+ if tr_solver == 'exact':
+ J_free = J[:, free_set]
+ newton_step = lstsq(J_free, -f, rcond=-1)[0]
+
+ # Coefficients for the quadratic model along the anti-gradient.
+ a, b = build_quadratic_1d(J_free, g_free, -g_free)
+ elif tr_solver == 'lsmr':
+ Jop = aslinearoperator(J)
+
+ # We compute lsmr step in scaled variables and then
+ # transform back to normal variables, if lsmr would give exact lsq
+ # solution, this would be equivalent to not doing any
+ # transformations, but from experience it's better this way.
+
+ # We pass active_set to make computations as if we selected
+ # the free subset of J columns, but without actually doing any
+ # slicing, which is expensive for sparse matrices and impossible
+ # for LinearOperator.
+
+ lsmr_op = lsmr_operator(Jop, scale, active_set)
+ newton_step = -lsmr(lsmr_op, f, **tr_options)[0][free_set]
+ newton_step *= scale_free
+
+ # Components of g for active variables were zeroed, so this call
+ # is correct and equivalent to using J_free and g_free.
+ a, b = build_quadratic_1d(Jop, g, -g)
+
+ actual_reduction = -1.0
+ while actual_reduction <= 0 and nfev < max_nfev:
+ tr_bounds = Delta * scale_free
+
+ step_free, on_bound_free, tr_hit = dogleg_step(
+ x_free, newton_step, g_free, a, b, tr_bounds, lb_free, ub_free)
+
+ step.fill(0.0)
+ step[free_set] = step_free
+
+ if tr_solver == 'exact':
+ predicted_reduction = -evaluate_quadratic(J_free, g_free,
+ step_free)
+ elif tr_solver == 'lsmr':
+ predicted_reduction = -evaluate_quadratic(Jop, g, step)
+
+ # gh11403 ensure that solution is fully within bounds.
+ x_new = np.clip(x + step, lb, ub)
+
+ f_new = fun(x_new)
+ nfev += 1
+
+ step_h_norm = norm(step * scale_inv, ord=np.inf)
+
+ if not np.all(np.isfinite(f_new)):
+ Delta = 0.25 * step_h_norm
+ continue
+
+ # Usual trust-region step quality estimation.
+ if loss_function is not None:
+ cost_new = loss_function(f_new, cost_only=True)
+ else:
+ cost_new = 0.5 * np.dot(f_new, f_new)
+ actual_reduction = cost - cost_new
+
+ Delta, ratio = update_tr_radius(
+ Delta, actual_reduction, predicted_reduction,
+ step_h_norm, tr_hit
+ )
+
+ step_norm = norm(step)
+ termination_status = check_termination(
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
+
+ if termination_status is not None:
+ break
+
+ if actual_reduction > 0:
+ on_bound[free_set] = on_bound_free
+
+ x = x_new
+ # Set variables exactly at the boundary.
+ mask = on_bound == -1
+ x[mask] = lb[mask]
+ mask = on_bound == 1
+ x[mask] = ub[mask]
+
+ f = f_new
+ f_true = f.copy()
+
+ cost = cost_new
+
+ J = jac(x)
+ njev += 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ J, f = scale_for_robust_loss_function(J, f, rho)
+
+ g = compute_grad(J, f)
+
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
+ else:
+ step_norm = 0
+ actual_reduction = 0
+
+ iteration += 1
+
+ # Call callback function and possibly stop optimization
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=x, fun=f, nit=iteration, nfev=nfev)
+ intermediate_result["cost"] = cost_new
+
+ if _call_callback_maybe_halt(
+ callback, intermediate_result
+ ):
+ termination_status = -2
+ break
+
+ if termination_status is None:
+ termination_status = 0
+
+ return OptimizeResult(
+ x=x, cost=cost, fun=f_true, jac=J, grad=g_full, optimality=g_norm,
+ active_mask=on_bound, nfev=nfev, njev=njev, status=termination_status)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/givens_elimination.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/givens_elimination.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5cb3b9865b230e5ea4544af99d424419f02bc428
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/givens_elimination.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..793f36fb7fa389c28efec613d1906f103827f1be
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py
@@ -0,0 +1,1044 @@
+"""Generic interface for least-squares minimization."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import norm
+
+from scipy.sparse.linalg import LinearOperator
+from scipy.optimize import _minpack, OptimizeResult
+from scipy.optimize._differentiable_functions import VectorFunction
+from scipy.optimize._numdiff import group_columns
+from scipy.optimize._minimize import Bounds
+from scipy._lib._sparse import issparse
+from scipy._lib._array_api import array_namespace
+from scipy._lib._util import _workers_wrapper
+
+from .trf import trf
+from .dogbox import dogbox
+from .common import EPS, in_bounds, make_strictly_feasible
+
+
+from scipy.optimize._optimize import _wrap_callback
+
+TERMINATION_MESSAGES = {
+ -2: "Stopped because `callback` function raised `StopIteration` or returned `True`",
+ -1: "Improper input parameters status returned from `leastsq`",
+ 0: "The maximum number of function evaluations is exceeded.",
+ 1: "`gtol` termination condition is satisfied.",
+ 2: "`ftol` termination condition is satisfied.",
+ 3: "`xtol` termination condition is satisfied.",
+ 4: "Both `ftol` and `xtol` termination conditions are satisfied."
+}
+
+
+FROM_MINPACK_TO_COMMON = {
+ 0: -1, # Improper input parameters from MINPACK.
+ 1: 2,
+ 2: 3,
+ 3: 4,
+ 4: 1,
+ 5: 0
+ # There are 6, 7, 8 for too small tolerance parameters,
+ # but we guard against it by checking ftol, xtol, gtol beforehand.
+}
+
+
+def call_minpack(fun, x0, jac, ftol, xtol, gtol, max_nfev, x_scale, jac_method=None):
+ n = x0.size
+
+ # Compute MINPACK's `diag`, which is inverse of our `x_scale` and
+ # ``x_scale='jac'`` corresponds to ``diag=None``.
+
+ # 1.16.0 - default x_scale changed to 'jac', with diag=None
+ if x_scale is None or (isinstance(x_scale, str) and x_scale == 'jac'):
+ diag = None
+ else:
+ # x_scale specified, so use that
+ diag = 1 / x_scale
+
+ full_output = True
+ col_deriv = False
+ factor = 100.0
+
+ if max_nfev is None:
+ max_nfev = 100 * n
+
+ # lmder is typically used for systems with analytic jacobians, with lmdif being
+ # used if there is only an objective fun (lmdif uses finite differences to estimate
+ # jacobian). Otherwise they're very similar internally.
+ # We now do all the finite differencing in VectorFunction, which means we can drop
+ # lmdif and just use lmder.
+
+ # for sending a copy of x0 into _lmder
+ xp = array_namespace(x0)
+
+ x, info, status = _minpack._lmder(
+ fun, jac, xp.astype(x0, x0.dtype), (), full_output, col_deriv,
+ ftol, xtol, gtol, max_nfev, factor, diag)
+
+ f = info['fvec']
+ J = jac(x)
+
+ cost = 0.5 * np.dot(f, f)
+ g = J.T.dot(f)
+ g_norm = norm(g, ord=np.inf)
+
+ nfev = info['nfev']
+ if callable(jac_method):
+ # user supplied a callable ("analytic") jac
+ njev = info.get('njev', None)
+ else:
+ # If there are no analytic jacobian evaluations we need to set `njev=None`.
+ njev = None
+
+ status = FROM_MINPACK_TO_COMMON[status]
+ active_mask = np.zeros_like(x0, dtype=int)
+
+ return OptimizeResult(
+ x=x, cost=cost, fun=f, jac=J, grad=g, optimality=g_norm,
+ active_mask=active_mask, nfev=nfev, njev=njev, status=status)
+
+
+def prepare_bounds(bounds, n):
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
+ if lb.ndim == 0:
+ lb = np.resize(lb, n)
+
+ if ub.ndim == 0:
+ ub = np.resize(ub, n)
+
+ return lb, ub
+
+
+def check_tolerance(ftol, xtol, gtol, method):
+ def check(tol, name):
+ if tol is None:
+ tol = 0
+ elif tol < EPS:
+ warn(f"Setting `{name}` below the machine epsilon ({EPS:.2e}) effectively "
+ f"disables the corresponding termination condition.",
+ stacklevel=3)
+ return tol
+
+ ftol = check(ftol, "ftol")
+ xtol = check(xtol, "xtol")
+ gtol = check(gtol, "gtol")
+
+ if method == "lm" and (ftol < EPS or xtol < EPS or gtol < EPS):
+ raise ValueError("All tolerances must be higher than machine epsilon "
+ f"({EPS:.2e}) for method 'lm'.")
+ elif ftol < EPS and xtol < EPS and gtol < EPS:
+ raise ValueError("At least one of the tolerances must be higher than "
+ f"machine epsilon ({EPS:.2e}).")
+
+ return ftol, xtol, gtol
+
+
+def check_x_scale(x_scale, x0, method):
+ # normalise the default scaling
+ if x_scale is None:
+ if method == 'lm':
+ return 'jac'
+ else: # dogbox, trf
+ x_scale = 1.0
+
+ if isinstance(x_scale, str) and x_scale == 'jac':
+ return x_scale
+
+ try:
+ x_scale = np.asarray(x_scale, dtype=float)
+ valid = np.all(np.isfinite(x_scale)) and np.all(x_scale > 0)
+ except (ValueError, TypeError):
+ valid = False
+
+ if not valid:
+ raise ValueError("`x_scale` must be 'jac' or array_like with "
+ "positive numbers.")
+
+ if x_scale.ndim == 0:
+ x_scale = np.resize(x_scale, x0.shape)
+
+ if x_scale.shape != x0.shape:
+ raise ValueError("Inconsistent shapes between `x_scale` and `x0`.")
+
+ return x_scale
+
+
+def check_jac_sparsity(jac_sparsity, m, n):
+ if jac_sparsity is None:
+ return None
+
+ if not issparse(jac_sparsity):
+ jac_sparsity = np.atleast_2d(jac_sparsity)
+
+ if jac_sparsity.shape != (m, n):
+ raise ValueError("`jac_sparsity` has wrong shape.")
+
+ return jac_sparsity, group_columns(jac_sparsity)
+
+
+# Loss functions.
+
+
+def huber(z, rho, cost_only):
+ mask = z <= 1
+ rho[0, mask] = z[mask]
+ rho[0, ~mask] = 2 * z[~mask]**0.5 - 1
+ if cost_only:
+ return
+ rho[1, mask] = 1
+ rho[1, ~mask] = z[~mask]**-0.5
+ rho[2, mask] = 0
+ rho[2, ~mask] = -0.5 * z[~mask]**-1.5
+
+
+def soft_l1(z, rho, cost_only):
+ t = 1 + z
+ rho[0] = 2 * (t**0.5 - 1)
+ if cost_only:
+ return
+ rho[1] = t**-0.5
+ rho[2] = -0.5 * t**-1.5
+
+
+def cauchy(z, rho, cost_only):
+ rho[0] = np.log1p(z)
+ if cost_only:
+ return
+ t = 1 + z
+ rho[1] = 1 / t
+ rho[2] = -1 / t**2
+
+
+def arctan(z, rho, cost_only):
+ rho[0] = np.arctan(z)
+ if cost_only:
+ return
+ t = 1 + z**2
+ rho[1] = 1 / t
+ rho[2] = -2 * z / t**2
+
+
+IMPLEMENTED_LOSSES = dict(linear=None, huber=huber, soft_l1=soft_l1,
+ cauchy=cauchy, arctan=arctan)
+
+
+def construct_loss_function(m, loss, f_scale):
+ if loss == 'linear':
+ return None
+
+ if not callable(loss):
+ loss = IMPLEMENTED_LOSSES[loss]
+ rho = np.empty((3, m))
+
+ def loss_function(f, cost_only=False):
+ z = (f / f_scale) ** 2
+ loss(z, rho, cost_only=cost_only)
+ if cost_only:
+ return 0.5 * f_scale ** 2 * np.sum(rho[0])
+ rho[0] *= f_scale ** 2
+ rho[2] /= f_scale ** 2
+ return rho
+ else:
+ def loss_function(f, cost_only=False):
+ z = (f / f_scale) ** 2
+ rho = loss(z)
+ if cost_only:
+ return 0.5 * f_scale ** 2 * np.sum(rho[0])
+ rho[0] *= f_scale ** 2
+ rho[2] /= f_scale ** 2
+ return rho
+
+ return loss_function
+
+
+class _WrapArgsKwargs:
+ # Supplies a user function with args and kwargs.
+ def __init__(self, f, args=(), kwargs=None):
+ self.f = f
+ self.args = args
+ self.kwargs = kwargs or {}
+
+ def __call__(self, x):
+ return self.f(x, *self.args, **self.kwargs)
+
+
+@_workers_wrapper
+def least_squares(
+ fun, x0, jac='2-point', bounds=(-np.inf, np.inf), method='trf',
+ ftol=1e-8, xtol=1e-8, gtol=1e-8, x_scale=None, loss='linear',
+ f_scale=1.0, diff_step=None, tr_solver=None, tr_options=None,
+ jac_sparsity=None, max_nfev=None, verbose=0, args=(), kwargs=None,
+ callback=None, workers=None
+):
+ """Solve a nonlinear least-squares problem with bounds on the variables.
+
+ Given the residuals f(x) (an m-D real function of n real
+ variables) and the loss function rho(s) (a scalar function), `least_squares`
+ finds a local minimum of the cost function F(x)::
+
+ minimize F(x) = 0.5 * sum(rho(f_i(x)**2), i = 0, ..., m - 1)
+ subject to lb <= x <= ub
+
+ The purpose of the loss function rho(s) is to reduce the influence of
+ outliers on the solution.
+
+ Parameters
+ ----------
+ fun : callable
+ Function which computes the vector of residuals, with the signature
+ ``fun(x, *args, **kwargs)``, i.e., the minimization proceeds with
+ respect to its first argument. The argument ``x`` passed to this
+ function is an ndarray of shape (n,) (never a scalar, even for n=1).
+ It must allocate and return a 1-D array_like of shape (m,) or a scalar.
+ If the argument ``x`` is complex or the function ``fun`` returns
+ complex residuals, it must be wrapped in a real function of real
+ arguments, as shown at the end of the Examples section.
+ x0 : array_like with shape (n,) or float
+ Initial guess on independent variables. If float, it will be treated
+ as a 1-D array with one element. When `method` is 'trf', the initial
+ guess might be slightly adjusted to lie sufficiently within the given
+ `bounds`.
+ jac : {'2-point', '3-point', 'cs', callable}, optional
+ Method of computing the Jacobian matrix (an m-by-n matrix, where
+ element (i, j) is the partial derivative of f[i] with respect to
+ x[j]). The keywords select a finite difference scheme for numerical
+ estimation. The scheme '3-point' is more accurate, but requires
+ twice as many operations as '2-point' (default). The scheme 'cs'
+ uses complex steps, and while potentially the most accurate, it is
+ applicable only when `fun` correctly handles complex inputs and
+ can be analytically continued to the complex plane. If callable, it is used as
+ ``jac(x, *args, **kwargs)`` and should return a good approximation
+ (or the exact value) for the Jacobian as an array_like (np.atleast_2d
+ is applied), a sparse array (csr_array preferred for performance) or
+ a `scipy.sparse.linalg.LinearOperator`.
+
+ .. versionchanged:: 1.16.0
+ An ability to use the '3-point', 'cs' keywords with the 'lm' method.
+ Previously 'lm' was limited to '2-point' and callable.
+
+ bounds : 2-tuple of array_like or `Bounds`, optional
+ There are two ways to specify bounds:
+
+ 1. Instance of `Bounds` class
+ 2. Lower and upper bounds on independent variables. Defaults to no
+ bounds. Each array must match the size of `x0` or be a scalar,
+ in the latter case a bound will be the same for all variables.
+ Use ``np.inf`` with an appropriate sign to disable bounds on all
+ or some variables.
+
+ method : {'trf', 'dogbox', 'lm'}, optional
+ Algorithm to perform minimization.
+
+ * 'trf' : Trust Region Reflective algorithm, particularly suitable
+ for large sparse problems with bounds. Generally robust method.
+ * 'dogbox' : dogleg algorithm with rectangular trust regions,
+ typical use case is small problems with bounds. Not recommended
+ for problems with rank-deficient Jacobian.
+ * 'lm' : Levenberg-Marquardt algorithm as implemented in MINPACK.
+ Doesn't handle bounds and sparse Jacobians. Usually the most
+ efficient method for small unconstrained problems.
+
+ Default is 'trf'. See Notes for more information.
+ ftol : float or None, optional
+ Tolerance for termination by the change of the cost function. Default
+ is 1e-8. The optimization process is stopped when ``dF < ftol * F``,
+ and there was an adequate agreement between a local quadratic model and
+ the true model in the last step.
+
+ If None and 'method' is not 'lm', the termination by this condition is
+ disabled. If 'method' is 'lm', this tolerance must be higher than
+ machine epsilon.
+ xtol : float or None, optional
+ Tolerance for termination by the change of the independent variables.
+ Default is 1e-8. The exact condition depends on the `method` used:
+
+ * For 'trf' and 'dogbox' : ``norm(dx) < xtol * (xtol + norm(x))``.
+ * For 'lm' : ``Delta < xtol * norm(xs)``, where ``Delta`` is
+ a trust-region radius and ``xs`` is the value of ``x``
+ scaled according to `x_scale` parameter (see below).
+
+ If None and 'method' is not 'lm', the termination by this condition is
+ disabled. If 'method' is 'lm', this tolerance must be higher than
+ machine epsilon.
+ gtol : float or None, optional
+ Tolerance for termination by the norm of the gradient. Default is 1e-8.
+ The exact condition depends on a `method` used:
+
+ * For 'trf' : ``norm(g_scaled, ord=np.inf) < gtol``, where
+ ``g_scaled`` is the value of the gradient scaled to account for
+ the presence of the bounds [STIR]_.
+ * For 'dogbox' : ``norm(g_free, ord=np.inf) < gtol``, where
+ ``g_free`` is the gradient with respect to the variables which
+ are not in the optimal state on the boundary.
+ * For 'lm' : the maximum absolute value of the cosine of angles
+ between columns of the Jacobian and the residual vector is less
+ than `gtol`, or the residual vector is zero.
+
+ If None and 'method' is not 'lm', the termination by this condition is
+ disabled. If 'method' is 'lm', this tolerance must be higher than
+ machine epsilon.
+ x_scale : {None, array_like, 'jac'}, optional
+ Characteristic scale of each variable. Setting `x_scale` is equivalent
+ to reformulating the problem in scaled variables ``xs = x / x_scale``.
+ An alternative view is that the size of a trust region along jth
+ dimension is proportional to ``x_scale[j]``. Improved convergence may
+ be achieved by setting `x_scale` such that a step of a given size
+ along any of the scaled variables has a similar effect on the cost
+ function. If set to 'jac', the scale is iteratively updated using the
+ inverse norms of the columns of the Jacobian matrix (as described in
+ [JJMore]_). The default scaling for each method (i.e.
+ if ``x_scale is None``) is as follows:
+
+ * For 'trf' : ``x_scale == 1``
+ * For 'dogbox' : ``x_scale == 1``
+ * For 'lm' : ``x_scale == 'jac'``
+
+ .. versionchanged:: 1.16.0
+ The default keyword value is changed from 1 to None to indicate that
+ a default approach to scaling is used.
+ For the 'lm' method the default scaling is changed from 1 to 'jac'.
+ This has been found to give better performance, and is the same
+ scaling as performed by ``leastsq``.
+
+ loss : str or callable, optional
+ Determines the loss function. The following keyword values are allowed:
+
+ * 'linear' (default) : ``rho(z) = z``. Gives a standard
+ least-squares problem.
+ * 'soft_l1' : ``rho(z) = 2 * ((1 + z)**0.5 - 1)``. The smooth
+ approximation of l1 (absolute value) loss. Usually a good
+ choice for robust least squares.
+ * 'huber' : ``rho(z) = z if z <= 1 else 2*z**0.5 - 1``. Works
+ similarly to 'soft_l1'.
+ * 'cauchy' : ``rho(z) = ln(1 + z)``. Severely weakens outliers
+ influence, but may cause difficulties in optimization process.
+ * 'arctan' : ``rho(z) = arctan(z)``. Limits a maximum loss on
+ a single residual, has properties similar to 'cauchy'.
+
+ If callable, it must take a 1-D ndarray ``z=f**2`` and return an
+ array_like with shape (3, m) where row 0 contains function values,
+ row 1 contains first derivatives and row 2 contains second
+ derivatives. Method 'lm' supports only 'linear' loss.
+ f_scale : float, optional
+ Value of soft margin between inlier and outlier residuals, default
+ is 1.0. The loss function is evaluated as follows
+ ``rho_(f**2) = C**2 * rho(f**2 / C**2)``, where ``C`` is `f_scale`,
+ and ``rho`` is determined by `loss` parameter. This parameter has
+ no effect with ``loss='linear'``, but for other `loss` values it is
+ of crucial importance.
+ diff_step : None or array_like, optional
+ Determines the relative step size for the finite difference
+ approximation of the Jacobian. The actual step is computed as
+ ``x * diff_step``. If None (default), then `diff_step` is taken to be
+ a conventional "optimal" power of machine epsilon for the finite
+ difference scheme used [NR]_.
+ tr_solver : {None, 'exact', 'lsmr'}, optional
+ Method for solving trust-region subproblems, relevant only for 'trf'
+ and 'dogbox' methods.
+
+ * 'exact' is suitable for not very large problems with dense
+ Jacobian matrices. The computational complexity per iteration is
+ comparable to a singular value decomposition of the Jacobian
+ matrix.
+ * 'lsmr' is suitable for problems with sparse and large Jacobian
+ matrices. It uses the iterative procedure
+ `scipy.sparse.linalg.lsmr` for finding a solution of a linear
+ least-squares problem and only requires matrix-vector product
+ evaluations.
+
+ If None (default), the solver is chosen based on the type of Jacobian
+ returned on the first iteration.
+ tr_options : dict, optional
+ Keyword options passed to trust-region solver.
+
+ * ``tr_solver='exact'``: `tr_options` are ignored.
+ * ``tr_solver='lsmr'``: options for `scipy.sparse.linalg.lsmr`.
+ Additionally, ``method='trf'`` supports 'regularize' option
+ (bool, default is True), which adds a regularization term to the
+ normal equation, which improves convergence if the Jacobian is
+ rank-deficient [Byrd]_ (eq. 3.4).
+
+ jac_sparsity : {None, array_like, sparse array}, optional
+ Defines the sparsity structure of the Jacobian matrix for finite
+ difference estimation, its shape must be (m, n). If the Jacobian has
+ only few non-zero elements in *each* row, providing the sparsity
+ structure will greatly speed up the computations [Curtis]_. A zero
+ entry means that a corresponding element in the Jacobian is identically
+ zero. If provided, forces the use of 'lsmr' trust-region solver.
+ If None (default), then dense differencing will be used. Has no effect
+ for 'lm' method.
+ max_nfev : None or int, optional
+ For all methods this parameter controls the maximum number of function
+ evaluations used by each method, separate to those used in numerical
+ approximation of the jacobian.
+ If None (default), the value is chosen automatically as 100 * n.
+
+ .. versionchanged:: 1.16.0
+ The default for the 'lm' method is changed to 100 * n, for both a callable
+ and a numerically estimated jacobian. Previously the default when using an
+ estimated jacobian was 100 * n * (n + 1), because the method included
+ evaluations used in the estimation.
+
+ verbose : {0, 1, 2}, optional
+ Level of algorithm's verbosity:
+
+ * 0 (default) : work silently.
+ * 1 : display a termination report.
+ * 2 : display progress during iterations (not supported by 'lm'
+ method).
+
+ args, kwargs : tuple and dict, optional
+ Additional arguments passed to `fun` and `jac`. Both empty by default.
+ The calling signature is ``fun(x, *args, **kwargs)`` and the same for
+ `jac`.
+ callback : None or callable, optional
+ Callback function that is called by the algorithm on each iteration.
+ This can be used to print or plot the optimization results at each
+ step, and to stop the optimization algorithm based on some user-defined
+ condition. Only implemented for the `trf` and `dogbox` methods.
+
+ The signature is ``callback(intermediate_result: OptimizeResult)``
+
+ `intermediate_result is a `scipy.optimize.OptimizeResult`
+ which contains the intermediate results of the optimization at the
+ current iteration.
+
+ The callback also supports a signature like: ``callback(x)``
+
+ Introspection is used to determine which of the signatures is invoked.
+
+ If the `callback` function raises `StopIteration` the optimization algorithm
+ will stop and return with status code -2.
+
+ .. versionadded:: 1.16.0
+ workers : map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ result : OptimizeResult
+ `OptimizeResult` with the following fields defined:
+
+ x : ndarray, shape (n,)
+ Solution found.
+ cost : float
+ Value of the cost function at the solution.
+ fun : ndarray, shape (m,)
+ Vector of residuals at the solution.
+ jac : ndarray, sparse array or LinearOperator, shape (m, n)
+ Modified Jacobian matrix at the solution, in the sense that J^T J
+ is a Gauss-Newton approximation of the Hessian of the cost function.
+ The type is the same as the one used by the algorithm.
+ grad : ndarray, shape (m,)
+ Gradient of the cost function at the solution.
+ optimality : float
+ First-order optimality measure. In unconstrained problems, it is
+ always the uniform norm of the gradient. In constrained problems,
+ it is the quantity which was compared with `gtol` during iterations.
+ active_mask : ndarray of int, shape (n,)
+ Each component shows whether a corresponding constraint is active
+ (that is, whether a variable is at the bound):
+
+ * 0 : a constraint is not active.
+ * -1 : a lower bound is active.
+ * 1 : an upper bound is active.
+
+ Might be somewhat arbitrary for 'trf' method as it generates a
+ sequence of strictly feasible iterates and `active_mask` is
+ determined within a tolerance threshold.
+ nfev : int
+ Number of function evaluations done. This number does not include
+ the function calls used for numerical Jacobian approximation.
+
+ .. versionchanged:: 1.16.0
+ For the 'lm' method the number of function calls used in numerical
+ Jacobian approximation is no longer included. This is to bring all
+ methods into line.
+
+ njev : int or None
+ Number of Jacobian evaluations done. If numerical Jacobian
+ approximation is used in 'lm' method, it is set to None.
+ status : int
+ The reason for algorithm termination:
+
+ * -2 : terminated because callback raised StopIteration.
+ * -1 : improper input parameters status returned from MINPACK.
+ * 0 : the maximum number of function evaluations is exceeded.
+ * 1 : `gtol` termination condition is satisfied.
+ * 2 : `ftol` termination condition is satisfied.
+ * 3 : `xtol` termination condition is satisfied.
+ * 4 : Both `ftol` and `xtol` termination conditions are satisfied.
+
+ message : str
+ Verbal description of the termination reason.
+ success : bool
+ True if one of the convergence criteria is satisfied (`status` > 0).
+
+ See Also
+ --------
+ leastsq : A legacy wrapper for the MINPACK implementation of the
+ Levenberg-Marquadt algorithm.
+ curve_fit : Least-squares minimization applied to a curve-fitting problem.
+
+ Notes
+ -----
+ Method 'lm' (Levenberg-Marquardt) calls a wrapper over a least-squares
+ algorithm implemented in MINPACK (lmder). It runs the
+ Levenberg-Marquardt algorithm formulated as a trust-region type algorithm.
+ The implementation is based on paper [JJMore]_, it is very robust and
+ efficient with a lot of smart tricks. It should be your first choice
+ for unconstrained problems. Note that it doesn't support bounds. Also,
+ it doesn't work when m < n.
+
+ Method 'trf' (Trust Region Reflective) is motivated by the process of
+ solving a system of equations, which constitute the first-order optimality
+ condition for a bound-constrained minimization problem as formulated in
+ [STIR]_. The algorithm iteratively solves trust-region subproblems
+ augmented by a special diagonal quadratic term and with trust-region shape
+ determined by the distance from the bounds and the direction of the
+ gradient. This enhancements help to avoid making steps directly into bounds
+ and efficiently explore the whole space of variables. To further improve
+ convergence, the algorithm considers search directions reflected from the
+ bounds. To obey theoretical requirements, the algorithm keeps iterates
+ strictly feasible. With dense Jacobians trust-region subproblems are
+ solved by an exact method very similar to the one described in [JJMore]_
+ (and implemented in MINPACK). The difference from the MINPACK
+ implementation is that a singular value decomposition of a Jacobian
+ matrix is done once per iteration, instead of a QR decomposition and series
+ of Givens rotation eliminations. For large sparse Jacobians a 2-D subspace
+ approach of solving trust-region subproblems is used [STIR]_, [Byrd]_.
+ The subspace is spanned by a scaled gradient and an approximate
+ Gauss-Newton solution delivered by `scipy.sparse.linalg.lsmr`. When no
+ constraints are imposed the algorithm is very similar to MINPACK and has
+ generally comparable performance. The algorithm works quite robust in
+ unbounded and bounded problems, thus it is chosen as a default algorithm.
+
+ Method 'dogbox' operates in a trust-region framework, but considers
+ rectangular trust regions as opposed to conventional ellipsoids [Voglis]_.
+ The intersection of a current trust region and initial bounds is again
+ rectangular, so on each iteration a quadratic minimization problem subject
+ to bound constraints is solved approximately by Powell's dogleg method
+ [NumOpt]_. The required Gauss-Newton step can be computed exactly for
+ dense Jacobians or approximately by `scipy.sparse.linalg.lsmr` for large
+ sparse Jacobians. The algorithm is likely to exhibit slow convergence when
+ the rank of Jacobian is less than the number of variables. The algorithm
+ often outperforms 'trf' in bounded problems with a small number of
+ variables.
+
+ Robust loss functions are implemented as described in [BA]_. The idea
+ is to modify a residual vector and a Jacobian matrix on each iteration
+ such that computed gradient and Gauss-Newton Hessian approximation match
+ the true gradient and Hessian approximation of the cost function. Then
+ the algorithm proceeds in a normal way, i.e., robust loss functions are
+ implemented as a simple wrapper over standard least-squares algorithms.
+
+ .. versionadded:: 0.17.0
+
+ References
+ ----------
+ .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+ .. [NR] William H. Press et. al., "Numerical Recipes. The Art of Scientific
+ Computing. 3rd edition", Sec. 5.7.
+ .. [Byrd] R. H. Byrd, R. B. Schnabel and G. A. Shultz, "Approximate
+ solution of the trust region problem by minimization over
+ two-dimensional subspaces", Math. Programming, 40, pp. 247-263,
+ 1988.
+ .. [Curtis] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of
+ Mathematics and its Applications, 13, pp. 117-120, 1974.
+ .. [JJMore] J. J. More, "The Levenberg-Marquardt Algorithm: Implementation
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
+ Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
+ .. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region
+ Dogleg Approach for Unconstrained and Bound Constrained
+ Nonlinear Optimization", WSEAS International Conference on
+ Applied Mathematics, Corfu, Greece, 2004.
+ .. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization,
+ 2nd edition", Chapter 4.
+ .. [BA] B. Triggs et. al., "Bundle Adjustment - A Modern Synthesis",
+ Proceedings of the International Workshop on Vision Algorithms:
+ Theory and Practice, pp. 298-372, 1999.
+
+ Examples
+ --------
+ In this example we find a minimum of the Rosenbrock function without bounds
+ on independent variables.
+
+ >>> import numpy as np
+ >>> def fun_rosenbrock(x):
+ ... return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])
+
+ Notice that we only provide the vector of the residuals. The algorithm
+ constructs the cost function as a sum of squares of the residuals, which
+ gives the Rosenbrock function. The exact minimum is at ``x = [1.0, 1.0]``.
+
+ >>> from scipy.optimize import least_squares
+ >>> x0_rosenbrock = np.array([2, 2])
+ >>> res_1 = least_squares(fun_rosenbrock, x0_rosenbrock)
+ >>> res_1.x
+ array([ 1., 1.])
+ >>> res_1.cost
+ 9.8669242910846867e-30
+ >>> res_1.optimality
+ 8.8928864934219529e-14
+
+ We now constrain the variables, in such a way that the previous solution
+ becomes infeasible. Specifically, we require that ``x[1] >= 1.5``, and
+ ``x[0]`` left unconstrained. To this end, we specify the `bounds` parameter
+ to `least_squares` in the form ``bounds=([-np.inf, 1.5], np.inf)``.
+
+ We also provide the analytic Jacobian:
+
+ >>> def jac_rosenbrock(x):
+ ... return np.array([
+ ... [-20 * x[0], 10],
+ ... [-1, 0]])
+
+ Putting this all together, we see that the new solution lies on the bound:
+
+ >>> res_2 = least_squares(fun_rosenbrock, x0_rosenbrock, jac_rosenbrock,
+ ... bounds=([-np.inf, 1.5], np.inf))
+ >>> res_2.x
+ array([ 1.22437075, 1.5 ])
+ >>> res_2.cost
+ 0.025213093946805685
+ >>> res_2.optimality
+ 1.5885401433157753e-07
+
+ Now we solve a system of equations (i.e., the cost function should be zero
+ at a minimum) for a Broyden tridiagonal vector-valued function of 100000
+ variables:
+
+ >>> def fun_broyden(x):
+ ... f = (3 - x) * x + 1
+ ... f[1:] -= x[:-1]
+ ... f[:-1] -= 2 * x[1:]
+ ... return f
+
+ The corresponding Jacobian matrix is sparse. We tell the algorithm to
+ estimate it by finite differences and provide the sparsity structure of
+ Jacobian to significantly speed up this process.
+
+ >>> from scipy.sparse import lil_array
+ >>> def sparsity_broyden(n):
+ ... sparsity = lil_array((n, n), dtype=int)
+ ... i = np.arange(n)
+ ... sparsity[i, i] = 1
+ ... i = np.arange(1, n)
+ ... sparsity[i, i - 1] = 1
+ ... i = np.arange(n - 1)
+ ... sparsity[i, i + 1] = 1
+ ... return sparsity
+ ...
+ >>> n = 100000
+ >>> x0_broyden = -np.ones(n)
+ ...
+ >>> res_3 = least_squares(fun_broyden, x0_broyden,
+ ... jac_sparsity=sparsity_broyden(n))
+ >>> res_3.cost
+ 4.5687069299604613e-23
+ >>> res_3.optimality
+ 1.1650454296851518e-11
+
+ Let's also solve a curve fitting problem using robust loss function to
+ take care of outliers in the data. Define the model function as
+ ``y = a + b * exp(c * t)``, where t is a predictor variable, y is an
+ observation and a, b, c are parameters to estimate.
+
+ First, define the function which generates the data with noise and
+ outliers, define the model parameters, and generate data:
+
+ >>> from numpy.random import default_rng
+ >>> rng = default_rng()
+ >>> def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None):
+ ... rng = default_rng(seed)
+ ...
+ ... y = a + b * np.exp(t * c)
+ ...
+ ... error = noise * rng.standard_normal(t.size)
+ ... outliers = rng.integers(0, t.size, n_outliers)
+ ... error[outliers] *= 10
+ ...
+ ... return y + error
+ ...
+ >>> a = 0.5
+ >>> b = 2.0
+ >>> c = -1
+ >>> t_min = 0
+ >>> t_max = 10
+ >>> n_points = 15
+ ...
+ >>> t_train = np.linspace(t_min, t_max, n_points)
+ >>> y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3)
+
+ Define function for computing residuals and initial estimate of
+ parameters.
+
+ >>> def fun(x, t, y):
+ ... return x[0] + x[1] * np.exp(x[2] * t) - y
+ ...
+ >>> x0 = np.array([1.0, 1.0, 0.0])
+
+ Compute a standard least-squares solution:
+
+ >>> res_lsq = least_squares(fun, x0, args=(t_train, y_train))
+
+ Now compute two solutions with two different robust loss functions. The
+ parameter `f_scale` is set to 0.1, meaning that inlier residuals should
+ not significantly exceed 0.1 (the noise level used).
+
+ >>> res_soft_l1 = least_squares(fun, x0, loss='soft_l1', f_scale=0.1,
+ ... args=(t_train, y_train))
+ >>> res_log = least_squares(fun, x0, loss='cauchy', f_scale=0.1,
+ ... args=(t_train, y_train))
+
+ And, finally, plot all the curves. We see that by selecting an appropriate
+ `loss` we can get estimates close to optimal even in the presence of
+ strong outliers. But keep in mind that generally it is recommended to try
+ 'soft_l1' or 'huber' losses first (if at all necessary) as the other two
+ options may cause difficulties in optimization process.
+
+ >>> t_test = np.linspace(t_min, t_max, n_points * 10)
+ >>> y_true = gen_data(t_test, a, b, c)
+ >>> y_lsq = gen_data(t_test, *res_lsq.x)
+ >>> y_soft_l1 = gen_data(t_test, *res_soft_l1.x)
+ >>> y_log = gen_data(t_test, *res_log.x)
+ ...
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(t_train, y_train, 'o')
+ >>> plt.plot(t_test, y_true, 'k', linewidth=2, label='true')
+ >>> plt.plot(t_test, y_lsq, label='linear loss')
+ >>> plt.plot(t_test, y_soft_l1, label='soft_l1 loss')
+ >>> plt.plot(t_test, y_log, label='cauchy loss')
+ >>> plt.xlabel("t")
+ >>> plt.ylabel("y")
+ >>> plt.legend()
+ >>> plt.show()
+
+ In the next example, we show how complex-valued residual functions of
+ complex variables can be optimized with ``least_squares()``. Consider the
+ following function:
+
+ >>> def f(z):
+ ... return z - (0.5 + 0.5j)
+
+ We wrap it into a function of real variables that returns real residuals
+ by simply handling the real and imaginary parts as independent variables:
+
+ >>> def f_wrap(x):
+ ... fx = f(x[0] + 1j*x[1])
+ ... return np.array([fx.real, fx.imag])
+
+ Thus, instead of the original m-D complex function of n complex
+ variables we optimize a 2m-D real function of 2n real variables:
+
+ >>> from scipy.optimize import least_squares
+ >>> res_wrapped = least_squares(f_wrap, (0.1, 0.1), bounds=([0, 0], [1, 1]))
+ >>> z = res_wrapped.x[0] + res_wrapped.x[1]*1j
+ >>> z
+ (0.49999999999925893+0.49999999999925893j)
+
+ """
+ if method not in ['trf', 'dogbox', 'lm']:
+ raise ValueError("`method` must be 'trf', 'dogbox' or 'lm'.")
+
+ if jac not in ['2-point', '3-point', 'cs'] and not callable(jac):
+ raise ValueError("`jac` must be '2-point', '3-point', 'cs' or "
+ "callable.")
+
+ if tr_solver not in [None, 'exact', 'lsmr']:
+ raise ValueError("`tr_solver` must be None, 'exact' or 'lsmr'.")
+
+ if loss not in IMPLEMENTED_LOSSES and not callable(loss):
+ raise ValueError(f"`loss` must be one of {IMPLEMENTED_LOSSES.keys()}"
+ " or a callable.")
+
+ if method == 'lm' and loss != 'linear':
+ raise ValueError("method='lm' supports only 'linear' loss function.")
+
+ if verbose not in [0, 1, 2]:
+ raise ValueError("`verbose` must be in [0, 1, 2].")
+
+ if max_nfev is not None and max_nfev <= 0:
+ raise ValueError("`max_nfev` must be None or positive integer.")
+
+ if np.iscomplexobj(x0):
+ raise ValueError("`x0` must be real.")
+
+ x0 = np.atleast_1d(x0).astype(float)
+
+ if x0.ndim > 1:
+ raise ValueError("`x0` must have at most 1 dimension.")
+
+ if isinstance(bounds, Bounds):
+ lb, ub = bounds.lb, bounds.ub
+ bounds = (lb, ub)
+ else:
+ if len(bounds) == 2:
+ lb, ub = prepare_bounds(bounds, x0.shape[0])
+ else:
+ raise ValueError("`bounds` must contain 2 elements.")
+
+ if method == 'lm' and not np.all((lb == -np.inf) & (ub == np.inf)):
+ raise ValueError("Method 'lm' doesn't support bounds.")
+
+ if lb.shape != x0.shape or ub.shape != x0.shape:
+ raise ValueError("Inconsistent shapes between bounds and `x0`.")
+
+ if np.any(lb >= ub):
+ raise ValueError("Each lower bound must be strictly less than each "
+ "upper bound.")
+
+ if not in_bounds(x0, lb, ub):
+ raise ValueError("Initial guess is outside of provided bounds")
+
+ x_scale = check_x_scale(x_scale, x0, method)
+
+ ftol, xtol, gtol = check_tolerance(ftol, xtol, gtol, method)
+
+ if method == 'trf':
+ x0 = make_strictly_feasible(x0, lb, ub)
+
+ if tr_options is None:
+ tr_options = {}
+
+ ###########################################################################
+ # assemble VectorFunction
+ ###########################################################################
+ # first wrap the args/kwargs
+ fun_wrapped = _WrapArgsKwargs(fun, args=args, kwargs=kwargs)
+ jac_wrapped = jac
+ if callable(jac):
+ jac_wrapped = _WrapArgsKwargs(jac, args=args, kwargs=kwargs)
+
+ def _dummy_hess(x, *args):
+ # we don't care about Hessian evaluations
+ return x
+
+ vector_fun = VectorFunction(
+ fun_wrapped,
+ x0,
+ jac_wrapped,
+ _dummy_hess,
+ finite_diff_rel_step=diff_step,
+ finite_diff_jac_sparsity=jac_sparsity,
+ finite_diff_bounds=bounds,
+ workers=workers
+ )
+ ###########################################################################
+
+ f0 = vector_fun.fun(x0)
+ J0 = vector_fun.jac(x0)
+
+ if f0.ndim != 1:
+ raise ValueError("`fun` must return at most 1-d array_like. "
+ f"f0.shape: {f0.shape}")
+
+ if not np.all(np.isfinite(f0)):
+ raise ValueError("Residuals are not finite in the initial point.")
+
+ n = x0.size
+ m = f0.size
+
+ if method == 'lm' and m < n:
+ raise ValueError("Method 'lm' doesn't work when the number of "
+ "residuals is less than the number of variables.")
+
+ loss_function = construct_loss_function(m, loss, f_scale)
+ if callable(loss):
+ rho = loss_function(f0)
+ if rho.shape != (3, m):
+ raise ValueError("The return value of `loss` callable has wrong "
+ "shape.")
+ initial_cost = 0.5 * np.sum(rho[0])
+ elif loss_function is not None:
+ initial_cost = loss_function(f0, cost_only=True)
+ else:
+ initial_cost = 0.5 * np.dot(f0, f0)
+
+ if not callable(jac):
+ # Estimate Jacobian by finite differences.
+ if method == 'lm':
+ if jac_sparsity is not None:
+ raise ValueError("method='lm' does not support "
+ "`jac_sparsity`.")
+ else:
+ # this will raise a ValueError if the jac_sparsity isn't correct
+ _ = check_jac_sparsity(jac_sparsity, m, n)
+
+ if jac_sparsity is not None and tr_solver == 'exact':
+ raise ValueError("tr_solver='exact' is incompatible "
+ "with `jac_sparsity`.")
+
+ if J0.shape != (m, n):
+ raise ValueError(
+ f"The return value of `jac` has wrong shape: expected {(m, n)}, "
+ f"actual {J0.shape}."
+ )
+
+ if not isinstance(J0, np.ndarray):
+ if method == 'lm':
+ raise ValueError("method='lm' works only with dense "
+ "Jacobian matrices.")
+
+ if tr_solver == 'exact':
+ raise ValueError(
+ "tr_solver='exact' works only with dense "
+ "Jacobian matrices.")
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if isinstance(J0, LinearOperator) and jac_scale:
+ raise ValueError("x_scale='jac' can't be used when `jac` "
+ "returns LinearOperator.")
+
+ if tr_solver is None:
+ if isinstance(J0, np.ndarray):
+ tr_solver = 'exact'
+ else:
+ tr_solver = 'lsmr'
+
+ # Wrap callback function. If callback is None, callback_wrapped also is None
+ callback_wrapped = _wrap_callback(callback)
+
+ if method == 'lm':
+ if callback is not None:
+ warn("Callback function specified, but not supported with `lm` method.",
+ stacklevel=2)
+ result = call_minpack(vector_fun.fun, x0, vector_fun.jac, ftol, xtol, gtol,
+ max_nfev, x_scale, jac_method=jac)
+
+ elif method == 'trf':
+ result = trf(vector_fun.fun, vector_fun.jac, x0, f0, J0, lb, ub, ftol, xtol,
+ gtol, max_nfev, x_scale, loss_function, tr_solver,
+ tr_options.copy(), verbose, callback=callback_wrapped)
+
+ elif method == 'dogbox':
+ if tr_solver == 'lsmr' and 'regularize' in tr_options:
+ warn("The keyword 'regularize' in `tr_options` is not relevant "
+ "for 'dogbox' method.",
+ stacklevel=2)
+ tr_options = tr_options.copy()
+ del tr_options['regularize']
+
+ result = dogbox(vector_fun.fun, vector_fun.jac, x0, f0, J0, lb, ub, ftol,
+ xtol, gtol, max_nfev, x_scale, loss_function,
+ tr_solver, tr_options, verbose, callback=callback_wrapped)
+
+ result.message = TERMINATION_MESSAGES[result.status]
+ result.success = result.status > 0
+
+ if verbose >= 1:
+ print(result.message)
+ print(f"Function evaluations {result.nfev}, initial cost {initial_cost:.4e}, "
+ f"final cost {result.cost:.4e}, "
+ f"first-order optimality {result.optimality:.2e}.")
+
+ return result
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/lsq_linear.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..085808502e7a0ab712baba41dfef88503ea916af
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/lsq_linear.py
@@ -0,0 +1,363 @@
+"""Linear least squares with bound constraints on independent variables."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.sparse import issparse, csr_array
+from scipy.sparse.linalg import LinearOperator, lsmr
+from scipy.optimize import OptimizeResult
+from scipy.optimize._minimize import Bounds
+
+from .common import in_bounds, compute_grad
+from .trf_linear import trf_linear
+from .bvls import bvls
+
+
+def prepare_bounds(bounds, n):
+ if len(bounds) != 2:
+ raise ValueError("`bounds` must contain 2 elements.")
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
+
+ if lb.ndim == 0:
+ lb = np.resize(lb, n)
+
+ if ub.ndim == 0:
+ ub = np.resize(ub, n)
+
+ return lb, ub
+
+
+TERMINATION_MESSAGES = {
+ -1: "The algorithm was not able to make progress on the last iteration.",
+ 0: "The maximum number of iterations is exceeded.",
+ 1: "The first-order optimality measure is less than `tol`.",
+ 2: "The relative change of the cost function is less than `tol`.",
+ 3: "The unconstrained solution is optimal."
+}
+
+
+def lsq_linear(A, b, bounds=(-np.inf, np.inf), method='trf', tol=1e-10,
+ lsq_solver=None, lsmr_tol=None, max_iter=None,
+ verbose=0, *, lsmr_maxiter=None,):
+ r"""Solve a linear least-squares problem with bounds on the variables.
+
+ Given an m-by-n design matrix A and a target vector b with m elements,
+ `lsq_linear` solves the following optimization problem::
+
+ minimize 0.5 * ||A x - b||**2
+ subject to lb <= x <= ub
+
+ This optimization problem is convex, hence a found minimum (if iterations
+ have converged) is guaranteed to be global.
+
+ Parameters
+ ----------
+ A : array_like, sparse array or LinearOperator, shape (m, n)
+ Design matrix. Can be `scipy.sparse.linalg.LinearOperator`.
+ b : array_like, shape (m,)
+ Target vector.
+ bounds : 2-tuple of array_like or `Bounds`, optional
+ Lower and upper bounds on parameters. Defaults to no bounds.
+ There are two ways to specify the bounds:
+
+ - Instance of `Bounds` class.
+ - 2-tuple of array_like: Each element of the tuple must be either
+ an array with the length equal to the number of parameters, or a
+ scalar (in which case the bound is taken to be the same for all
+ parameters). Use ``np.inf`` with an appropriate sign to disable
+ bounds on all or some parameters.
+
+ method : 'trf' or 'bvls', optional
+ Method to perform minimization.
+
+ * 'trf' : Trust Region Reflective algorithm adapted for a linear
+ least-squares problem. This is an interior-point-like method
+ and the required number of iterations is weakly correlated with
+ the number of variables.
+ * 'bvls' : Bounded-variable least-squares algorithm. This is
+ an active set method, which requires the number of iterations
+ comparable to the number of variables. Can't be used when `A` is
+ sparse or LinearOperator.
+
+ Default is 'trf'.
+ tol : float, optional
+ Tolerance parameter. The algorithm terminates if a relative change
+ of the cost function is less than `tol` on the last iteration.
+ Additionally, the first-order optimality measure is considered:
+
+ * ``method='trf'`` terminates if the uniform norm of the gradient,
+ scaled to account for the presence of the bounds, is less than
+ `tol`.
+ * ``method='bvls'`` terminates if Karush-Kuhn-Tucker conditions
+ are satisfied within `tol` tolerance.
+
+ lsq_solver : {None, 'exact', 'lsmr'}, optional
+ Method of solving unbounded least-squares problems throughout
+ iterations:
+
+ * 'exact' : Use dense QR or SVD decomposition approach. Can't be
+ used when `A` is sparse or LinearOperator.
+ * 'lsmr' : Use `scipy.sparse.linalg.lsmr` iterative procedure
+ which requires only matrix-vector product evaluations. Can't
+ be used with ``method='bvls'``.
+
+ If None (default), the solver is chosen based on type of `A`.
+ lsmr_tol : None, float or 'auto', optional
+ Tolerance parameters 'atol' and 'btol' for `scipy.sparse.linalg.lsmr`
+ If None (default), it is set to ``1e-2 * tol``. If 'auto', the
+ tolerance will be adjusted based on the optimality of the current
+ iterate, which can speed up the optimization process, but is not always
+ reliable.
+ max_iter : None or int, optional
+ Maximum number of iterations before termination. If None (default), it
+ is set to 100 for ``method='trf'`` or to the number of variables for
+ ``method='bvls'`` (not counting iterations for 'bvls' initialization).
+ verbose : {0, 1, 2}, optional
+ Level of algorithm's verbosity:
+
+ * 0 : work silently (default).
+ * 1 : display a termination report.
+ * 2 : display progress during iterations.
+
+ lsmr_maxiter : None or int, optional
+ Maximum number of iterations for the lsmr least squares solver,
+ if it is used (by setting ``lsq_solver='lsmr'``). If None (default), it
+ uses lsmr's default of ``min(m, n)`` where ``m`` and ``n`` are the
+ number of rows and columns of `A`, respectively. Has no effect if
+ ``lsq_solver='exact'``.
+
+ Returns
+ -------
+ result : OptimizeResult
+ Result object with the following fields defined:
+
+ x : ndarray, shape (n,)
+ Solution found.
+ cost : float
+ Value of the cost function at the solution.
+ fun : ndarray, shape (m,)
+ Vector of residuals at the solution.
+ optimality : float
+ First-order optimality measure. The exact meaning depends on `method`,
+ refer to the description of `tol` parameter.
+ active_mask : ndarray of int, shape (n,)
+ Each component shows whether a corresponding constraint is active
+ (that is, whether a variable is at the bound):
+
+ * 0 : a constraint is not active.
+ * -1 : a lower bound is active.
+ * 1 : an upper bound is active.
+
+ Might be somewhat arbitrary for the `trf` method as it generates a
+ sequence of strictly feasible iterates and active_mask is determined
+ within a tolerance threshold.
+ unbounded_sol : tuple
+ Unbounded least squares solution tuple returned by the least squares
+ solver (set with `lsq_solver` option). If `lsq_solver` is not set or is
+ set to ``'exact'``, the tuple contains an ndarray of shape (n,) with
+ the unbounded solution, an ndarray with the sum of squared residuals,
+ an int with the rank of `A`, and an ndarray with the singular values
+ of `A` (see NumPy's ``linalg.lstsq`` for more information). If
+ `lsq_solver` is set to ``'lsmr'``, the tuple contains an ndarray of
+ shape (n,) with the unbounded solution, an int with the exit code,
+ an int with the number of iterations, and five floats with
+ various norms and the condition number of `A` (see SciPy's
+ ``sparse.linalg.lsmr`` for more information). This output can be
+ useful for determining the convergence of the least squares solver,
+ particularly the iterative ``'lsmr'`` solver. The unbounded least
+ squares problem is to minimize ``0.5 * ||A x - b||**2``.
+ nit : int
+ Number of iterations. Zero if the unconstrained solution is optimal.
+ status : int
+ Reason for algorithm termination:
+
+ * -1 : the algorithm was not able to make progress on the last
+ iteration.
+ * 0 : the maximum number of iterations is exceeded.
+ * 1 : the first-order optimality measure is less than `tol`.
+ * 2 : the relative change of the cost function is less than `tol`.
+ * 3 : the unconstrained solution is optimal.
+
+ message : str
+ Verbal description of the termination reason.
+ success : bool
+ True if one of the convergence criteria is satisfied (`status` > 0).
+
+ See Also
+ --------
+ nnls : Linear least squares with non-negativity constraint.
+ least_squares : Nonlinear least squares with bounds on the variables.
+
+ Notes
+ -----
+ The algorithm first computes the unconstrained least-squares solution by
+ `numpy.linalg.lstsq` or `scipy.sparse.linalg.lsmr` depending on
+ `lsq_solver`. This solution is returned as optimal if it lies within the
+ bounds.
+
+ Method 'trf' runs the adaptation of the algorithm described in [STIR]_ for
+ a linear least-squares problem. The iterations are essentially the same as
+ in the nonlinear least-squares algorithm, but as the quadratic function
+ model is always accurate, we don't need to track or modify the radius of
+ a trust region. The line search (backtracking) is used as a safety net
+ when a selected step does not decrease the cost function. Read more
+ detailed description of the algorithm in `scipy.optimize.least_squares`.
+
+ Method 'bvls' runs a Python implementation of the algorithm described in
+ [BVLS]_. The algorithm maintains active and free sets of variables, on
+ each iteration chooses a new variable to move from the active set to the
+ free set and then solves the unconstrained least-squares problem on free
+ variables. This algorithm is guaranteed to give an accurate solution
+ eventually, but may require up to n iterations for a problem with n
+ variables. Additionally, an ad-hoc initialization procedure is
+ implemented, that determines which variables to set free or active
+ initially. It takes some number of iterations before actual BVLS starts,
+ but can significantly reduce the number of further iterations.
+
+ References
+ ----------
+ .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+ .. [BVLS] P. B. Start and R. L. Parker, "Bounded-Variable Least-Squares:
+ an Algorithm and Applications", Computational Statistics, 10,
+ 129-141, 1995.
+
+ Examples
+ --------
+ In this example, a problem with a large sparse arrays and bounds on the
+ variables is solved.
+
+ >>> import numpy as np
+ >>> from scipy.sparse import random_array
+ >>> from scipy.optimize import lsq_linear
+ >>> rng = np.random.default_rng()
+ ...
+ >>> m = 2000
+ >>> n = 1000
+ ...
+ >>> A = random_array((m, n), density=1e-4, random_state=rng)
+ >>> b = rng.standard_normal(m)
+ ...
+ >>> lb = rng.standard_normal(n)
+ >>> ub = lb + 1
+ ...
+ >>> res = lsq_linear(A, b, bounds=(lb, ub), lsmr_tol='auto', verbose=1)
+ The relative change of the cost function is less than `tol`.
+ Number of iterations 10, initial cost 1.0070e+03, final cost 9.6602e+02,
+ first-order optimality 2.21e-09. # may vary
+ """
+ if method not in ['trf', 'bvls']:
+ raise ValueError("`method` must be 'trf' or 'bvls'")
+
+ if lsq_solver not in [None, 'exact', 'lsmr']:
+ raise ValueError("`solver` must be None, 'exact' or 'lsmr'.")
+
+ if verbose not in [0, 1, 2]:
+ raise ValueError("`verbose` must be in [0, 1, 2].")
+
+ if issparse(A):
+ A = csr_array(A)
+ elif not isinstance(A, LinearOperator):
+ A = np.atleast_2d(np.asarray(A))
+
+ if method == 'bvls':
+ if lsq_solver == 'lsmr':
+ raise ValueError("method='bvls' can't be used with "
+ "lsq_solver='lsmr'")
+
+ if not isinstance(A, np.ndarray):
+ raise ValueError("method='bvls' can't be used with `A` being "
+ "sparse or LinearOperator.")
+
+ if lsq_solver is None:
+ if isinstance(A, np.ndarray):
+ lsq_solver = 'exact'
+ else:
+ lsq_solver = 'lsmr'
+ elif lsq_solver == 'exact' and not isinstance(A, np.ndarray):
+ raise ValueError("`exact` solver can't be used when `A` is "
+ "sparse or LinearOperator.")
+
+ if len(A.shape) != 2: # No ndim for LinearOperator.
+ raise ValueError("`A` must have at most 2 dimensions.")
+
+ if max_iter is not None and max_iter <= 0:
+ raise ValueError("`max_iter` must be None or positive integer.")
+
+ m, n = A.shape
+
+ b = np.atleast_1d(b)
+ if b.ndim != 1:
+ raise ValueError("`b` must have at most 1 dimension.")
+
+ if b.size != m:
+ raise ValueError("Inconsistent shapes between `A` and `b`.")
+
+ if isinstance(bounds, Bounds):
+ lb = bounds.lb
+ ub = bounds.ub
+ else:
+ lb, ub = prepare_bounds(bounds, n)
+
+ if lb.shape != (n,) and ub.shape != (n,):
+ raise ValueError("Bounds have wrong shape.")
+
+ if np.any(lb >= ub):
+ raise ValueError("Each lower bound must be strictly less than each "
+ "upper bound.")
+
+ if lsmr_maxiter is not None and lsmr_maxiter < 1:
+ raise ValueError("`lsmr_maxiter` must be None or positive integer.")
+
+ if not ((isinstance(lsmr_tol, float) and lsmr_tol > 0) or
+ lsmr_tol in ('auto', None)):
+ raise ValueError("`lsmr_tol` must be None, 'auto', or positive float.")
+
+ if lsq_solver == 'exact':
+ unbd_lsq = np.linalg.lstsq(A, b, rcond=-1)
+ elif lsq_solver == 'lsmr':
+ first_lsmr_tol = lsmr_tol # tol of first call to lsmr
+ if lsmr_tol is None or lsmr_tol == 'auto':
+ first_lsmr_tol = 1e-2 * tol # default if lsmr_tol not defined
+ unbd_lsq = lsmr(A, b, maxiter=lsmr_maxiter,
+ atol=first_lsmr_tol, btol=first_lsmr_tol)
+ x_lsq = unbd_lsq[0] # extract the solution from the least squares solver
+
+ if in_bounds(x_lsq, lb, ub):
+ r = A @ x_lsq - b
+ cost = 0.5 * np.dot(r, r)
+ termination_status = 3
+ termination_message = TERMINATION_MESSAGES[termination_status]
+ g = compute_grad(A, r)
+ g_norm = norm(g, ord=np.inf)
+
+ if verbose > 0:
+ print(termination_message)
+ print(f"Final cost {cost:.4e}, first-order optimality {g_norm:.2e}")
+
+ return OptimizeResult(
+ x=x_lsq, fun=r, cost=cost, optimality=g_norm,
+ active_mask=np.zeros(n), unbounded_sol=unbd_lsq,
+ nit=0, status=termination_status,
+ message=termination_message, success=True)
+
+ if method == 'trf':
+ res = trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol,
+ max_iter, verbose, lsmr_maxiter=lsmr_maxiter)
+ elif method == 'bvls':
+ res = bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose)
+
+ res.unbounded_sol = unbd_lsq
+ res.message = TERMINATION_MESSAGES[res.status]
+ res.success = res.status > 0
+
+ if verbose > 0:
+ print(res.message)
+ print(
+ f"Number of iterations {res.nit}, initial cost {res.initial_cost:.4e}, "
+ f"final cost {res.cost:.4e}, first-order optimality {res.optimality:.2e}."
+ )
+
+ del res.initial_cost
+
+ return res
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/trf.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/trf.py
new file mode 100644
index 0000000000000000000000000000000000000000..f17ec17a68fa7de88982dd8287c4fa8be635a14e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/trf.py
@@ -0,0 +1,587 @@
+"""Trust Region Reflective algorithm for least-squares optimization.
+
+The algorithm is based on ideas from paper [STIR]_. The main idea is to
+account for the presence of the bounds by appropriate scaling of the variables (or,
+equivalently, changing a trust-region shape). Let's introduce a vector v:
+
+ | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
+ v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
+ | 1, otherwise
+
+where g is the gradient of a cost function and lb, ub are the bounds. Its
+components are distances to the bounds at which the anti-gradient points (if
+this distance is finite). Define a scaling matrix D = diag(v**0.5).
+First-order optimality conditions can be stated as
+
+ D^2 g(x) = 0.
+
+Meaning that components of the gradient should be zero for strictly interior
+variables, and components must point inside the feasible region for variables
+on the bound.
+
+Now consider this system of equations as a new optimization problem. If the
+point x is strictly interior (not on the bound), then the left-hand side is
+differentiable and the Newton step for it satisfies
+
+ (D^2 H + diag(g) Jv) p = -D^2 g
+
+where H is the Hessian matrix (or its J^T J approximation in least squares),
+Jv is the Jacobian matrix of v with components -1, 1 or 0, such that all
+elements of matrix C = diag(g) Jv are non-negative. Introduce the change
+of the variables x = D x_h (_h would be "hat" in LaTeX). In the new variables,
+we have a Newton step satisfying
+
+ B_h p_h = -g_h,
+
+where B_h = D H D + C, g_h = D g. In least squares B_h = J_h^T J_h, where
+J_h = J D. Note that J_h and g_h are proper Jacobian and gradient with respect
+to "hat" variables. To guarantee global convergence we formulate a
+trust-region problem based on the Newton step in the new variables:
+
+ 0.5 * p_h^T B_h p + g_h^T p_h -> min, ||p_h|| <= Delta
+
+In the original space B = H + D^{-1} C D^{-1}, and the equivalent trust-region
+problem is
+
+ 0.5 * p^T B p + g^T p -> min, ||D^{-1} p|| <= Delta
+
+Here, the meaning of the matrix D becomes more clear: it alters the shape
+of a trust-region, such that large steps towards the bounds are not allowed.
+In the implementation, the trust-region problem is solved in "hat" space,
+but handling of the bounds is done in the original space (see below and read
+the code).
+
+The introduction of the matrix D doesn't allow to ignore bounds, the algorithm
+must keep iterates strictly feasible (to satisfy aforementioned
+differentiability), the parameter theta controls step back from the boundary
+(see the code for details).
+
+The algorithm does another important trick. If the trust-region solution
+doesn't fit into the bounds, then a reflected (from a firstly encountered
+bound) search direction is considered. For motivation and analysis refer to
+[STIR]_ paper (and other papers of the authors). In practice, it doesn't need
+a lot of justifications, the algorithm simply chooses the best step among
+three: a constrained trust-region step, a reflected step and a constrained
+Cauchy step (a minimizer along -g_h in "hat" space, or -D^2 g in the original
+space).
+
+Another feature is that a trust-region radius control strategy is modified to
+account for appearance of the diagonal C matrix (called diag_h in the code).
+
+Note that all described peculiarities are completely gone as we consider
+problems without bounds (the algorithm becomes a standard trust-region type
+algorithm very similar to ones implemented in MINPACK).
+
+The implementation supports two methods of solving the trust-region problem.
+The first, called 'exact', applies SVD on Jacobian and then solves the problem
+very accurately using the algorithm described in [JJMore]_. It is not
+applicable to large problem. The second, called 'lsmr', uses the 2-D subspace
+approach (sometimes called "indefinite dogleg"), where the problem is solved
+in a subspace spanned by the gradient and the approximate Gauss-Newton step
+found by ``scipy.sparse.linalg.lsmr``. A 2-D trust-region problem is
+reformulated as a 4th order algebraic equation and solved very accurately by
+``numpy.roots``. The subspace approach allows to solve very large problems
+(up to couple of millions of residuals on a regular PC), provided the Jacobian
+matrix is sufficiently sparse.
+
+References
+----------
+.. [STIR] Branch, M.A., T.F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+.. [JJMore] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
+"""
+import numpy as np
+from numpy.linalg import norm
+from scipy.linalg import svd, qr
+from scipy.sparse.linalg import lsmr
+from scipy.optimize import OptimizeResult
+
+from .common import (
+ step_size_to_bound, find_active_constraints, in_bounds,
+ make_strictly_feasible, intersect_trust_region, solve_lsq_trust_region,
+ solve_trust_region_2d, minimize_quadratic_1d, build_quadratic_1d,
+ evaluate_quadratic, right_multiplied_operator, regularized_lsq_operator,
+ CL_scaling_vector, compute_grad, compute_jac_scale, check_termination,
+ update_tr_radius, scale_for_robust_loss_function, print_header_nonlinear,
+ print_iteration_nonlinear)
+from scipy._lib._util import _call_callback_maybe_halt
+
+
+def trf(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=None):
+ # For efficiency, it makes sense to run the simplified version of the
+ # algorithm when no bounds are imposed. We decided to write the two
+ # separate functions. It violates the DRY principle, but the individual
+ # functions are kept the most readable.
+ if np.all(lb == -np.inf) and np.all(ub == np.inf):
+ return trf_no_bounds(
+ fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=callback)
+ else:
+ return trf_bounds(
+ fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=callback)
+
+
+def select_step(x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta):
+ """Select the best step according to Trust Region Reflective algorithm."""
+ if in_bounds(x + p, lb, ub):
+ p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
+ return p, p_h, -p_value
+
+ p_stride, hits = step_size_to_bound(x, p, lb, ub)
+
+ # Compute the reflected direction.
+ r_h = np.copy(p_h)
+ r_h[hits.astype(bool)] *= -1
+ r = d * r_h
+
+ # Restrict trust-region step, such that it hits the bound.
+ p *= p_stride
+ p_h *= p_stride
+ x_on_bound = x + p
+
+ # Reflected direction will cross first either feasible region or trust
+ # region boundary.
+ _, to_tr = intersect_trust_region(p_h, r_h, Delta)
+ to_bound, _ = step_size_to_bound(x_on_bound, r, lb, ub)
+
+ # Find lower and upper bounds on a step size along the reflected
+ # direction, considering the strict feasibility requirement. There is no
+ # single correct way to do that, the chosen approach seems to work best
+ # on test problems.
+ r_stride = min(to_bound, to_tr)
+ if r_stride > 0:
+ r_stride_l = (1 - theta) * p_stride / r_stride
+ if r_stride == to_bound:
+ r_stride_u = theta * to_bound
+ else:
+ r_stride_u = to_tr
+ else:
+ r_stride_l = 0
+ r_stride_u = -1
+
+ # Check if reflection step is available.
+ if r_stride_l <= r_stride_u:
+ a, b, c = build_quadratic_1d(J_h, g_h, r_h, s0=p_h, diag=diag_h)
+ r_stride, r_value = minimize_quadratic_1d(
+ a, b, r_stride_l, r_stride_u, c=c)
+ r_h *= r_stride
+ r_h += p_h
+ r = r_h * d
+ else:
+ r_value = np.inf
+
+ # Now correct p_h to make it strictly interior.
+ p *= theta
+ p_h *= theta
+ p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
+
+ ag_h = -g_h
+ ag = d * ag_h
+
+ to_tr = Delta / norm(ag_h)
+ to_bound, _ = step_size_to_bound(x, ag, lb, ub)
+ if to_bound < to_tr:
+ ag_stride = theta * to_bound
+ else:
+ ag_stride = to_tr
+
+ a, b = build_quadratic_1d(J_h, g_h, ag_h, diag=diag_h)
+ ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride)
+ ag_h *= ag_stride
+ ag *= ag_stride
+
+ if p_value < r_value and p_value < ag_value:
+ return p, p_h, -p_value
+ elif r_value < p_value and r_value < ag_value:
+ return r, r_h, -r_value
+ else:
+ return ag, ag_h, -ag_value
+
+
+def trf_bounds(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev,
+ x_scale, loss_function, tr_solver, tr_options, verbose,
+ callback=None):
+ x = x0.copy()
+
+ f = f0
+ f_true = f.copy()
+ nfev = 1
+
+ J = J0
+ njev = 1
+ m, n = J.shape
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ cost = 0.5 * np.sum(rho[0])
+ J, f = scale_for_robust_loss_function(J, f, rho)
+ else:
+ cost = 0.5 * np.dot(f, f)
+
+ g = compute_grad(J, f)
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J)
+ else:
+ scale, scale_inv = x_scale, 1 / x_scale
+
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+ v[dv != 0] *= scale_inv[dv != 0]
+ Delta = norm(x0 * scale_inv / v**0.5)
+ if Delta == 0:
+ Delta = 1.0
+
+ g_norm = norm(g * v, ord=np.inf)
+
+ f_augmented = np.zeros(m + n)
+ if tr_solver == 'exact':
+ J_augmented = np.empty((m + n, n))
+ elif tr_solver == 'lsmr':
+ reg_term = 0.0
+ regularize = tr_options.pop('regularize', True)
+
+ if max_nfev is None:
+ max_nfev = x0.size * 100
+
+ alpha = 0.0 # "Levenberg-Marquardt" parameter
+
+ termination_status = None
+ iteration = 0
+ step_norm = None
+ actual_reduction = None
+
+ if verbose == 2:
+ print_header_nonlinear()
+
+ while True:
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+
+ g_norm = norm(g * v, ord=np.inf)
+ if g_norm < gtol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
+ step_norm, g_norm)
+
+ if termination_status is not None or nfev == max_nfev:
+ break
+
+ # Now compute variables in "hat" space. Here, we also account for
+ # scaling introduced by `x_scale` parameter. This part is a bit tricky,
+ # you have to write down the formulas and see how the trust-region
+ # problem is formulated when the two types of scaling are applied.
+ # The idea is that first we apply `x_scale` and then apply Coleman-Li
+ # approach in the new variables.
+
+ # v is recomputed in the variables after applying `x_scale`, note that
+ # components which were identically 1 not affected.
+ v[dv != 0] *= scale_inv[dv != 0]
+
+ # Here, we apply two types of scaling.
+ d = v**0.5 * scale
+
+ # C = diag(g * scale) Jv
+ diag_h = g * dv * scale
+
+ # After all this has been done, we continue normally.
+
+ # "hat" gradient.
+ g_h = d * g
+
+ f_augmented[:m] = f
+ if tr_solver == 'exact':
+ J_augmented[:m] = J * d
+ J_h = J_augmented[:m] # Memory view.
+ J_augmented[m:] = np.diag(diag_h**0.5)
+ U, s, V = svd(J_augmented, full_matrices=False)
+ V = V.T
+ uf = U.T.dot(f_augmented)
+ elif tr_solver == 'lsmr':
+ J_h = right_multiplied_operator(J, d)
+
+ if regularize:
+ a, b = build_quadratic_1d(J_h, g_h, -g_h, diag=diag_h)
+ to_tr = Delta / norm(g_h)
+ ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
+ reg_term = -ag_value / Delta**2
+
+ lsmr_op = regularized_lsq_operator(J_h, (diag_h + reg_term)**0.5)
+ gn_h = lsmr(lsmr_op, f_augmented, **tr_options)[0]
+ S = np.vstack((g_h, gn_h)).T
+ S, _ = qr(S, mode='economic')
+ JS = J_h.dot(S) # LinearOperator does dot too.
+ B_S = np.dot(JS.T, JS) + np.dot(S.T * diag_h, S)
+ g_S = S.T.dot(g_h)
+
+ # theta controls step back step ratio from the bounds.
+ theta = max(0.995, 1 - g_norm)
+
+ actual_reduction = -1
+ while actual_reduction <= 0 and nfev < max_nfev:
+ if tr_solver == 'exact':
+ p_h, alpha, n_iter = solve_lsq_trust_region(
+ n, m, uf, s, V, Delta, initial_alpha=alpha)
+ elif tr_solver == 'lsmr':
+ p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
+ p_h = S.dot(p_S)
+
+ p = d * p_h # Trust-region solution in the original space.
+ step, step_h, predicted_reduction = select_step(
+ x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta)
+
+ x_new = make_strictly_feasible(x + step, lb, ub, rstep=0)
+ f_new = fun(x_new)
+ nfev += 1
+
+ step_h_norm = norm(step_h)
+
+ if not np.all(np.isfinite(f_new)):
+ Delta = 0.25 * step_h_norm
+ continue
+
+ # Usual trust-region step quality estimation.
+ if loss_function is not None:
+ cost_new = loss_function(f_new, cost_only=True)
+ else:
+ cost_new = 0.5 * np.dot(f_new, f_new)
+ actual_reduction = cost - cost_new
+ Delta_new, ratio = update_tr_radius(
+ Delta, actual_reduction, predicted_reduction,
+ step_h_norm, step_h_norm > 0.95 * Delta)
+
+ step_norm = norm(step)
+ termination_status = check_termination(
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
+ if termination_status is not None:
+ break
+
+ alpha *= Delta / Delta_new
+ Delta = Delta_new
+
+ if actual_reduction > 0:
+ x = x_new
+
+ f = f_new
+ f_true = f.copy()
+
+ cost = cost_new
+
+ J = jac(x)
+ njev += 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ J, f = scale_for_robust_loss_function(J, f, rho)
+
+ g = compute_grad(J, f)
+
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
+ else:
+ step_norm = 0
+ actual_reduction = 0
+
+ iteration += 1
+
+ # Call callback function and possibly stop optimization
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=x, fun=f_true, nit=iteration, nfev=nfev)
+ intermediate_result["cost"] = cost
+
+ if _call_callback_maybe_halt(
+ callback, intermediate_result
+ ):
+ termination_status = -2
+ break
+
+ if termination_status is None:
+ termination_status = 0
+
+ active_mask = find_active_constraints(x, lb, ub, rtol=xtol)
+ return OptimizeResult(
+ x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
+ active_mask=active_mask, nfev=nfev, njev=njev,
+ status=termination_status)
+
+
+def trf_no_bounds(fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev,
+ x_scale, loss_function, tr_solver, tr_options, verbose,
+ callback=None):
+ x = x0.copy()
+
+ f = f0
+ f_true = f.copy()
+ nfev = 1
+
+ J = J0
+ njev = 1
+ m, n = J.shape
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ cost = 0.5 * np.sum(rho[0])
+ J, f = scale_for_robust_loss_function(J, f, rho)
+ else:
+ cost = 0.5 * np.dot(f, f)
+
+ g = compute_grad(J, f)
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J)
+ else:
+ scale, scale_inv = x_scale, 1 / x_scale
+
+ Delta = norm(x0 * scale_inv)
+ if Delta == 0:
+ Delta = 1.0
+
+ if tr_solver == 'lsmr':
+ reg_term = 0
+ damp = tr_options.pop('damp', 0.0)
+ regularize = tr_options.pop('regularize', True)
+
+ if max_nfev is None:
+ max_nfev = x0.size * 100
+
+ alpha = 0.0 # "Levenberg-Marquardt" parameter
+
+ termination_status = None
+ iteration = 0
+ step_norm = None
+ actual_reduction = None
+
+ if verbose == 2:
+ print_header_nonlinear()
+
+ while True:
+ g_norm = norm(g, ord=np.inf)
+ if g_norm < gtol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
+ step_norm, g_norm)
+
+ if termination_status is not None or nfev == max_nfev:
+ break
+
+ d = scale
+ g_h = d * g
+
+ if tr_solver == 'exact':
+ J_h = J * d
+ U, s, V = svd(J_h, full_matrices=False)
+ V = V.T
+ uf = U.T.dot(f)
+ elif tr_solver == 'lsmr':
+ J_h = right_multiplied_operator(J, d)
+
+ if regularize:
+ a, b = build_quadratic_1d(J_h, g_h, -g_h)
+ to_tr = Delta / norm(g_h)
+ ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
+ reg_term = -ag_value / Delta**2
+
+ damp_full = (damp**2 + reg_term)**0.5
+ gn_h = lsmr(J_h, f, damp=damp_full, **tr_options)[0]
+ S = np.vstack((g_h, gn_h)).T
+ S, _ = qr(S, mode='economic')
+ JS = J_h.dot(S)
+ B_S = np.dot(JS.T, JS)
+ g_S = S.T.dot(g_h)
+
+ actual_reduction = -1
+ while actual_reduction <= 0 and nfev < max_nfev:
+ if tr_solver == 'exact':
+ step_h, alpha, n_iter = solve_lsq_trust_region(
+ n, m, uf, s, V, Delta, initial_alpha=alpha)
+ elif tr_solver == 'lsmr':
+ p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
+ step_h = S.dot(p_S)
+
+ predicted_reduction = -evaluate_quadratic(J_h, g_h, step_h)
+ step = d * step_h
+ x_new = x + step
+ f_new = fun(x_new)
+ nfev += 1
+
+ step_h_norm = norm(step_h)
+
+ if not np.all(np.isfinite(f_new)):
+ Delta = 0.25 * step_h_norm
+ continue
+
+ # Usual trust-region step quality estimation.
+ if loss_function is not None:
+ cost_new = loss_function(f_new, cost_only=True)
+ else:
+ cost_new = 0.5 * np.dot(f_new, f_new)
+ actual_reduction = cost - cost_new
+
+ Delta_new, ratio = update_tr_radius(
+ Delta, actual_reduction, predicted_reduction,
+ step_h_norm, step_h_norm > 0.95 * Delta)
+
+ step_norm = norm(step)
+ termination_status = check_termination(
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
+ if termination_status is not None:
+ break
+
+ alpha *= Delta / Delta_new
+ Delta = Delta_new
+
+ if actual_reduction > 0:
+ x = x_new
+
+ f = f_new
+ f_true = f.copy()
+
+ cost = cost_new
+
+ J = jac(x)
+ njev += 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ J, f = scale_for_robust_loss_function(J, f, rho)
+
+ g = compute_grad(J, f)
+
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
+ else:
+ step_norm = 0
+ actual_reduction = 0
+
+ iteration += 1
+
+ # Call callback function and possibly stop optimization
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=x, fun=f_true, nit=iteration, nfev=nfev)
+ intermediate_result["cost"] = cost
+
+ if _call_callback_maybe_halt(
+ callback, intermediate_result
+ ):
+ termination_status = -2
+ break
+
+ if termination_status is None:
+ termination_status = 0
+
+ active_mask = np.zeros_like(x)
+ return OptimizeResult(
+ x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
+ active_mask=active_mask, nfev=nfev, njev=njev,
+ status=termination_status)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/trf_linear.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/trf_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd752763179bcf97945c7f34ce6a9e49e85c819e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_lsq/trf_linear.py
@@ -0,0 +1,249 @@
+"""The adaptation of Trust Region Reflective algorithm for a linear
+least-squares problem."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.linalg import qr, solve_triangular
+from scipy.sparse.linalg import lsmr
+from scipy.optimize import OptimizeResult
+
+from .givens_elimination import givens_elimination
+from .common import (
+ EPS, step_size_to_bound, find_active_constraints, in_bounds,
+ make_strictly_feasible, build_quadratic_1d, evaluate_quadratic,
+ minimize_quadratic_1d, CL_scaling_vector, reflective_transformation,
+ print_header_linear, print_iteration_linear, compute_grad,
+ regularized_lsq_operator, right_multiplied_operator)
+
+
+def regularized_lsq_with_qr(m, n, R, QTb, perm, diag, copy_R=True):
+ """Solve regularized least squares using information from QR-decomposition.
+
+ The initial problem is to solve the following system in a least-squares
+ sense::
+
+ A x = b
+ D x = 0
+
+ where D is diagonal matrix. The method is based on QR decomposition
+ of the form A P = Q R, where P is a column permutation matrix, Q is an
+ orthogonal matrix and R is an upper triangular matrix.
+
+ Parameters
+ ----------
+ m, n : int
+ Initial shape of A.
+ R : ndarray, shape (n, n)
+ Upper triangular matrix from QR decomposition of A.
+ QTb : ndarray, shape (n,)
+ First n components of Q^T b.
+ perm : ndarray, shape (n,)
+ Array defining column permutation of A, such that ith column of
+ P is perm[i]-th column of identity matrix.
+ diag : ndarray, shape (n,)
+ Array containing diagonal elements of D.
+
+ Returns
+ -------
+ x : ndarray, shape (n,)
+ Found least-squares solution.
+ """
+ if copy_R:
+ R = R.copy()
+ v = QTb.copy()
+
+ givens_elimination(R, v, diag[perm])
+
+ abs_diag_R = np.abs(np.diag(R))
+ threshold = EPS * max(m, n) * np.max(abs_diag_R)
+ nns, = np.nonzero(abs_diag_R > threshold)
+
+ R = R[np.ix_(nns, nns)]
+ v = v[nns]
+
+ x = np.zeros(n)
+ x[perm[nns]] = solve_triangular(R, v)
+
+ return x
+
+
+def backtracking(A, g, x, p, theta, p_dot_g, lb, ub):
+ """Find an appropriate step size using backtracking line search."""
+ alpha = 1
+ while True:
+ x_new, _ = reflective_transformation(x + alpha * p, lb, ub)
+ step = x_new - x
+ cost_change = -evaluate_quadratic(A, g, step)
+ if cost_change > -0.1 * alpha * p_dot_g:
+ break
+ alpha *= 0.5
+
+ active = find_active_constraints(x_new, lb, ub)
+ if np.any(active != 0):
+ x_new, _ = reflective_transformation(x + theta * alpha * p, lb, ub)
+ x_new = make_strictly_feasible(x_new, lb, ub, rstep=0)
+ step = x_new - x
+ cost_change = -evaluate_quadratic(A, g, step)
+
+ return x, step, cost_change
+
+
+def select_step(x, A_h, g_h, c_h, p, p_h, d, lb, ub, theta):
+ """Select the best step according to Trust Region Reflective algorithm."""
+ if in_bounds(x + p, lb, ub):
+ return p
+
+ p_stride, hits = step_size_to_bound(x, p, lb, ub)
+ r_h = np.copy(p_h)
+ r_h[hits.astype(bool)] *= -1
+ r = d * r_h
+
+ # Restrict step, such that it hits the bound.
+ p *= p_stride
+ p_h *= p_stride
+ x_on_bound = x + p
+
+ # Find the step size along reflected direction.
+ r_stride_u, _ = step_size_to_bound(x_on_bound, r, lb, ub)
+
+ # Stay interior.
+ r_stride_l = (1 - theta) * r_stride_u
+ r_stride_u *= theta
+
+ if r_stride_u > 0:
+ a, b, c = build_quadratic_1d(A_h, g_h, r_h, s0=p_h, diag=c_h)
+ r_stride, r_value = minimize_quadratic_1d(
+ a, b, r_stride_l, r_stride_u, c=c)
+ r_h = p_h + r_h * r_stride
+ r = d * r_h
+ else:
+ r_value = np.inf
+
+ # Now correct p_h to make it strictly interior.
+ p_h *= theta
+ p *= theta
+ p_value = evaluate_quadratic(A_h, g_h, p_h, diag=c_h)
+
+ ag_h = -g_h
+ ag = d * ag_h
+ ag_stride_u, _ = step_size_to_bound(x, ag, lb, ub)
+ ag_stride_u *= theta
+ a, b = build_quadratic_1d(A_h, g_h, ag_h, diag=c_h)
+ ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride_u)
+ ag *= ag_stride
+
+ if p_value < r_value and p_value < ag_value:
+ return p
+ elif r_value < p_value and r_value < ag_value:
+ return r
+ else:
+ return ag
+
+
+def trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol,
+ max_iter, verbose, *, lsmr_maxiter=None):
+ m, n = A.shape
+ x, _ = reflective_transformation(x_lsq, lb, ub)
+ x = make_strictly_feasible(x, lb, ub, rstep=0.1)
+
+ if lsq_solver == 'exact':
+ QT, R, perm = qr(A, mode='economic', pivoting=True)
+ QT = QT.T
+
+ if m < n:
+ R = np.vstack((R, np.zeros((n - m, n))))
+
+ QTr = np.zeros(n)
+ k = min(m, n)
+ elif lsq_solver == 'lsmr':
+ r_aug = np.zeros(m + n)
+ auto_lsmr_tol = False
+ if lsmr_tol is None:
+ lsmr_tol = 1e-2 * tol
+ elif lsmr_tol == 'auto':
+ auto_lsmr_tol = True
+
+ r = A.dot(x) - b
+ g = compute_grad(A, r)
+ cost = 0.5 * np.dot(r, r)
+ initial_cost = cost
+
+ termination_status = None
+ step_norm = None
+ cost_change = None
+
+ if max_iter is None:
+ max_iter = 100
+
+ if verbose == 2:
+ print_header_linear()
+
+ for iteration in range(max_iter):
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+ g_scaled = g * v
+ g_norm = norm(g_scaled, ord=np.inf)
+ if g_norm < tol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_linear(iteration, cost, cost_change,
+ step_norm, g_norm)
+
+ if termination_status is not None:
+ break
+
+ diag_h = g * dv
+ diag_root_h = diag_h ** 0.5
+ d = v ** 0.5
+ g_h = d * g
+
+ A_h = right_multiplied_operator(A, d)
+ if lsq_solver == 'exact':
+ QTr[:k] = QT.dot(r)
+ p_h = -regularized_lsq_with_qr(m, n, R * d[perm], QTr, perm,
+ diag_root_h, copy_R=False)
+ elif lsq_solver == 'lsmr':
+ lsmr_op = regularized_lsq_operator(A_h, diag_root_h)
+ r_aug[:m] = r
+ if auto_lsmr_tol:
+ eta = 1e-2 * min(0.5, g_norm)
+ lsmr_tol = max(EPS, min(0.1, eta * g_norm))
+ p_h = -lsmr(lsmr_op, r_aug, maxiter=lsmr_maxiter,
+ atol=lsmr_tol, btol=lsmr_tol)[0]
+
+ p = d * p_h
+
+ p_dot_g = np.dot(p, g)
+ if p_dot_g > 0:
+ termination_status = -1
+
+ theta = 1 - min(0.005, g_norm)
+ step = select_step(x, A_h, g_h, diag_h, p, p_h, d, lb, ub, theta)
+ cost_change = -evaluate_quadratic(A, g, step)
+
+ # Perhaps almost never executed, the idea is that `p` is descent
+ # direction thus we must find acceptable cost decrease using simple
+ # "backtracking", otherwise the algorithm's logic would break.
+ if cost_change < 0:
+ x, step, cost_change = backtracking(
+ A, g, x, p, theta, p_dot_g, lb, ub)
+ else:
+ x = make_strictly_feasible(x + step, lb, ub, rstep=0)
+
+ step_norm = norm(step)
+ r = A.dot(x) - b
+ g = compute_grad(A, r)
+
+ if cost_change < tol * cost:
+ termination_status = 2
+
+ cost = 0.5 * np.dot(r, r)
+
+ if termination_status is None:
+ termination_status = 0
+
+ active_mask = find_active_constraints(x, lb, ub, rtol=tol)
+
+ return OptimizeResult(
+ x=x, fun=r, cost=cost, optimality=g_norm, active_mask=active_mask,
+ nit=iteration + 1, status=termination_status,
+ initial_cost=initial_cost)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_milp.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_milp.py
new file mode 100644
index 0000000000000000000000000000000000000000..837e1e46fffd1326242ddbe50e6e678a06a0b18e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_milp.py
@@ -0,0 +1,395 @@
+import warnings
+
+import numpy as np
+from numpy.exceptions import VisibleDeprecationWarning
+
+from scipy.sparse import csc_array, vstack, issparse
+from ._highspy._highs_wrapper import _highs_wrapper # type: ignore[import-not-found,import-untyped]
+from ._constraints import LinearConstraint, Bounds
+from ._optimize import OptimizeResult
+from ._linprog_highs import _highs_to_scipy_status_message
+
+
+def _constraints_to_components(constraints):
+ """
+ Convert sequence of constraints to a single set of components A, b_l, b_u.
+
+ `constraints` could be
+
+ 1. A LinearConstraint
+ 2. A tuple representing a LinearConstraint
+ 3. An invalid object
+ 4. A sequence of composed entirely of objects of type 1/2
+ 5. A sequence containing at least one object of type 3
+
+ We want to accept 1, 2, and 4 and reject 3 and 5.
+ """
+ message = ("`constraints` (or each element within `constraints`) must be "
+ "convertible into an instance of "
+ "`scipy.optimize.LinearConstraint`.")
+ As = []
+ b_ls = []
+ b_us = []
+
+ # Accept case 1 by standardizing as case 4
+ if isinstance(constraints, LinearConstraint):
+ constraints = [constraints]
+ else:
+ # Reject case 3
+ try:
+ iter(constraints)
+ except TypeError as exc:
+ raise ValueError(message) from exc
+
+ # Accept case 2 by standardizing as case 4
+ if len(constraints) == 3:
+ # argument could be a single tuple representing a LinearConstraint
+ try:
+ constraints = [LinearConstraint(*constraints)]
+ except (TypeError, ValueError, VisibleDeprecationWarning):
+ # argument was not a tuple representing a LinearConstraint
+ pass
+
+ # Address cases 4/5
+ for constraint in constraints:
+ # if it's not a LinearConstraint or something that represents a
+ # LinearConstraint at this point, it's invalid
+ if not isinstance(constraint, LinearConstraint):
+ try:
+ constraint = LinearConstraint(*constraint)
+ except TypeError as exc:
+ raise ValueError(message) from exc
+ As.append(csc_array(constraint.A))
+ b_ls.append(np.atleast_1d(constraint.lb).astype(np.float64))
+ b_us.append(np.atleast_1d(constraint.ub).astype(np.float64))
+
+ if len(As) > 1:
+ A = vstack(As, format="csc")
+ b_l = np.concatenate(b_ls)
+ b_u = np.concatenate(b_us)
+ else: # avoid unnecessary copying
+ A = As[0]
+ b_l = b_ls[0]
+ b_u = b_us[0]
+
+ return A, b_l, b_u
+
+
+def _milp_iv(c, integrality, bounds, constraints, options):
+ # objective IV
+ if issparse(c):
+ raise ValueError("`c` must be a dense array.")
+ c = np.atleast_1d(c).astype(np.float64)
+ if c.ndim != 1 or c.size == 0 or not np.all(np.isfinite(c)):
+ message = ("`c` must be a one-dimensional array of finite numbers "
+ "with at least one element.")
+ raise ValueError(message)
+
+ # integrality IV
+ if issparse(integrality):
+ raise ValueError("`integrality` must be a dense array.")
+ message = ("`integrality` must contain integers 0-3 and be broadcastable "
+ "to `c.shape`.")
+ if integrality is None:
+ integrality = 0
+ try:
+ integrality = np.broadcast_to(integrality, c.shape).astype(np.uint8)
+ except ValueError:
+ raise ValueError(message)
+ if integrality.min() < 0 or integrality.max() > 3:
+ raise ValueError(message)
+
+ # bounds IV
+ if bounds is None:
+ bounds = Bounds(0, np.inf)
+ elif not isinstance(bounds, Bounds):
+ message = ("`bounds` must be convertible into an instance of "
+ "`scipy.optimize.Bounds`.")
+ try:
+ bounds = Bounds(*bounds)
+ except TypeError as exc:
+ raise ValueError(message) from exc
+
+ try:
+ lb = np.broadcast_to(bounds.lb, c.shape).astype(np.float64)
+ ub = np.broadcast_to(bounds.ub, c.shape).astype(np.float64)
+ except (ValueError, TypeError) as exc:
+ message = ("`bounds.lb` and `bounds.ub` must contain reals and "
+ "be broadcastable to `c.shape`.")
+ raise ValueError(message) from exc
+
+ # constraints IV
+ if not constraints:
+ constraints = [LinearConstraint(np.empty((0, c.size)),
+ np.empty((0,)), np.empty((0,)))]
+ try:
+ A, b_l, b_u = _constraints_to_components(constraints)
+ except ValueError as exc:
+ message = ("`constraints` (or each element within `constraints`) must "
+ "be convertible into an instance of "
+ "`scipy.optimize.LinearConstraint`.")
+ raise ValueError(message) from exc
+
+ if A.shape != (b_l.size, c.size):
+ message = "The shape of `A` must be (len(b_l), len(c))."
+ raise ValueError(message)
+ indptr, indices, data = A.indptr, A.indices, A.data.astype(np.float64)
+
+ # options IV
+ options = options or {}
+ supported_options = {'disp', 'presolve', 'time_limit', 'node_limit',
+ 'mip_rel_gap'}
+ unsupported_options = set(options).difference(supported_options)
+ if unsupported_options:
+ message = (f"Unrecognized options detected: {unsupported_options}. "
+ "These will be passed to HiGHS verbatim.")
+ warnings.warn(message, RuntimeWarning, stacklevel=3)
+ options_iv = {'log_to_console': options.pop("disp", False),
+ 'mip_max_nodes': options.pop("node_limit", None)}
+ options_iv.update(options)
+
+ return c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options_iv
+
+
+def milp(c, *, integrality=None, bounds=None, constraints=None, options=None):
+ r"""
+ Mixed-integer linear programming.
+
+ Solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & b_l \leq A x \leq b_u,\\
+ & l \leq x \leq u, \\
+ & x_i \in \mathbb{Z}, i \in X_i
+
+ where :math:`x` is a vector of decision variables;
+ :math:`c`, :math:`b_l`, :math:`b_u`, :math:`l`, and :math:`u` are vectors;
+ :math:`A` is a matrix, and :math:`X_i` is the set of indices of
+ decision variables that must be integral. (In this context, a
+ variable that can assume only integer values is said to be "integral";
+ it has an "integrality" constraint.)
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ b_l <= A @ x <= b_u
+ l <= x <= u
+ Specified elements of x must be integers
+
+ By default, ``l = 0`` and ``u = np.inf`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1D dense array_like
+ The coefficients of the linear objective function to be minimized.
+ `c` is converted to a double precision array before the problem is
+ solved.
+ integrality : 1D dense array_like, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or ``0``.
+
+ By default, all variables are continuous. `integrality` is converted
+ to an array of integers before the problem is solved.
+
+ bounds : scipy.optimize.Bounds, optional
+ Bounds on the decision variables. Lower and upper bounds are converted
+ to double precision arrays before the problem is solved. The
+ ``keep_feasible`` parameter of the `Bounds` object is ignored. If
+ not specified, all decision variables are constrained to be
+ non-negative.
+ constraints : sequence of scipy.optimize.LinearConstraint, optional
+ Linear constraints of the optimization problem. Arguments may be
+ one of the following:
+
+ 1. A single `LinearConstraint` object
+ 2. A single tuple that can be converted to a `LinearConstraint` object
+ as ``LinearConstraint(*constraints)``
+ 3. A sequence composed entirely of objects of type 1. and 2.
+
+ Before the problem is solved, all values are converted to double
+ precision, and the matrices of constraint coefficients are converted to
+ instances of `scipy.sparse.csc_array`. The ``keep_feasible`` parameter
+ of `LinearConstraint` objects is ignored.
+ options : dict, optional
+ A dictionary of solver options. The following keys are recognized.
+
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ node_limit : int, optional
+ The maximum number of nodes (linear program relaxations) to solve
+ before stopping. Default is no maximum number of nodes.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver.
+ time_limit : float, optional
+ The maximum number of seconds allotted to solve the problem.
+ Default is no time limit.
+ mip_rel_gap : float, optional
+ Termination criterion for MIP solver: solver will terminate when
+ the gap between the primal objective value and the dual objective
+ bound, scaled by the primal objective value, is <= mip_rel_gap.
+ Default: 0.0001.
+
+ Returns
+ -------
+ res : OptimizeResult
+ An instance of :class:`scipy.optimize.OptimizeResult`. The object
+ is guaranteed to have the following attributes.
+
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimal solution found.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem is infeasible.
+
+ ``3`` : Problem is unbounded.
+
+ ``4`` : Other; see message for details.
+
+ success : bool
+ ``True`` when an optimal solution is found and ``False`` otherwise.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+
+ The following attributes will also be present, but the values may be
+ ``None``, depending on the solution status.
+
+ x : ndarray
+ The values of the decision variables that minimize the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ mip_node_count : int
+ The number of subproblems or "nodes" solved by the MILP solver.
+ mip_dual_bound : float
+ The MILP solver's final estimate of the lower bound on the optimal
+ solution.
+ mip_gap : float
+ The difference between the primal objective value and the dual
+ objective bound, scaled by the primal objective value.
+
+ Notes
+ -----
+ `milp` is a wrapper of the HiGHS linear optimization software [1]_. The
+ algorithm is deterministic, and it typically finds the global optimum of
+ moderately challenging mixed-integer linear programs (when it exists).
+
+ References
+ ----------
+ .. [1] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [2] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. :doi:`10.1007/s12532-017-0130-5`.
+
+ Examples
+ --------
+ Consider the problem at
+ https://en.wikipedia.org/wiki/Integer_programming#Example, which is
+ expressed as a maximization problem of two variables. Since `milp` requires
+ that the problem be expressed as a minimization problem, the objective
+ function coefficients on the decision variables are:
+
+ >>> import numpy as np
+ >>> c = -np.array([0, 1])
+
+ Note the negative sign: we maximize the original objective function
+ by minimizing the negative of the objective function.
+
+ We collect the coefficients of the constraints into arrays like:
+
+ >>> A = np.array([[-1, 1], [3, 2], [2, 3]])
+ >>> b_u = np.array([1, 12, 12])
+ >>> b_l = np.full_like(b_u, -np.inf, dtype=float)
+
+ Because there is no lower limit on these constraints, we have defined a
+ variable ``b_l`` full of values representing negative infinity. This may
+ be unfamiliar to users of `scipy.optimize.linprog`, which only accepts
+ "less than" (or "upper bound") inequality constraints of the form
+ ``A_ub @ x <= b_u``. By accepting both ``b_l`` and ``b_u`` of constraints
+ ``b_l <= A_ub @ x <= b_u``, `milp` makes it easy to specify "greater than"
+ inequality constraints, "less than" inequality constraints, and equality
+ constraints concisely.
+
+ These arrays are collected into a single `LinearConstraint` object like:
+
+ >>> from scipy.optimize import LinearConstraint
+ >>> constraints = LinearConstraint(A, b_l, b_u)
+
+ The non-negativity bounds on the decision variables are enforced by
+ default, so we do not need to provide an argument for `bounds`.
+
+ Finally, the problem states that both decision variables must be integers:
+
+ >>> integrality = np.ones_like(c)
+
+ We solve the problem like:
+
+ >>> from scipy.optimize import milp
+ >>> res = milp(c=c, constraints=constraints, integrality=integrality)
+ >>> res.x
+ array([1., 2.])
+
+ Note that had we solved the relaxed problem (without integrality
+ constraints):
+
+ >>> res = milp(c=c, constraints=constraints) # OR:
+ >>> # from scipy.optimize import linprog; res = linprog(c, A, b_u)
+ >>> res.x
+ array([1.8, 2.8])
+
+ we would not have obtained the correct solution by rounding to the nearest
+ integers.
+
+ Other examples are given :ref:`in the tutorial `.
+
+ """
+ args_iv = _milp_iv(c, integrality, bounds, constraints, options)
+ c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options = args_iv
+
+ highs_res = _highs_wrapper(c, indptr, indices, data, b_l, b_u,
+ lb, ub, integrality, options)
+
+ res = {}
+
+ # Convert to scipy-style status and message
+ highs_status = highs_res.get('status', None)
+ highs_message = highs_res.get('message', None)
+ status, message = _highs_to_scipy_status_message(highs_status,
+ highs_message)
+ res['status'] = status
+ res['message'] = message
+ res['success'] = (status == 0)
+ x = highs_res.get('x', None)
+ res['x'] = np.array(x) if x is not None else None
+ res['fun'] = highs_res.get('fun', None)
+ res['mip_node_count'] = highs_res.get('mip_node_count', None)
+ res['mip_dual_bound'] = highs_res.get('mip_dual_bound', None)
+ res['mip_gap'] = highs_res.get('mip_gap', None)
+
+ return OptimizeResult(res)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_minimize.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_minimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..91d736990aaebe2dc119c26b59782466fa314fde
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_minimize.py
@@ -0,0 +1,1199 @@
+"""
+Unified interfaces to minimization algorithms.
+
+Functions
+---------
+- minimize : minimization of a function of several variables.
+- minimize_scalar : minimization of a function of one variable.
+"""
+
+__all__ = ['minimize', 'minimize_scalar']
+
+
+from warnings import warn
+
+import numpy as np
+from scipy._lib._util import wrapped_inspect_signature
+
+# unconstrained minimization
+from ._optimize import (_minimize_neldermead, _minimize_powell, _minimize_cg,
+ _minimize_bfgs, _minimize_newtoncg,
+ _minimize_scalar_brent, _minimize_scalar_bounded,
+ _minimize_scalar_golden, MemoizeJac, OptimizeResult,
+ _wrap_callback, _recover_from_bracket_error)
+from ._trustregion_dogleg import _minimize_dogleg
+from ._trustregion_ncg import _minimize_trust_ncg
+from ._trustregion_krylov import _minimize_trust_krylov
+from ._trustregion_exact import _minimize_trustregion_exact
+from ._trustregion_constr import _minimize_trustregion_constr
+
+# constrained minimization
+from ._lbfgsb_py import _minimize_lbfgsb
+from ._tnc import _minimize_tnc
+from ._cobyla_py import _minimize_cobyla
+from ._cobyqa_py import _minimize_cobyqa
+from ._slsqp_py import _minimize_slsqp
+from ._constraints import (old_bound_to_new, new_bounds_to_old,
+ old_constraint_to_new, new_constraint_to_old,
+ NonlinearConstraint, LinearConstraint, Bounds,
+ PreparedConstraint)
+from ._differentiable_functions import FD_METHODS
+
+MINIMIZE_METHODS = ['nelder-mead', 'powell', 'cg', 'bfgs', 'newton-cg',
+ 'l-bfgs-b', 'tnc', 'cobyla', 'cobyqa', 'slsqp',
+ 'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov']
+
+# These methods support the new callback interface (passed an OptimizeResult)
+MINIMIZE_METHODS_NEW_CB = ['nelder-mead', 'powell', 'cg', 'bfgs', 'newton-cg',
+ 'l-bfgs-b', 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov', 'cobyqa', 'cobyla', 'slsqp']
+
+MINIMIZE_SCALAR_METHODS = ['brent', 'bounded', 'golden']
+
+def minimize(fun, x0, args=(), method=None, jac=None, hess=None,
+ hessp=None, bounds=None, constraints=(), tol=None,
+ callback=None, options=None):
+ """Minimization of scalar function of one or more variables.
+
+ Parameters
+ ----------
+ fun : callable
+ The objective function to be minimized::
+
+ fun(x, *args) -> float
+
+ where ``x`` is a 1-D array with shape (n,) and ``args``
+ is a tuple of the fixed parameters needed to completely
+ specify the function.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+ x0 : ndarray, shape (n,)
+ Initial guess. Array of real elements of size (n,),
+ where ``n`` is the number of independent variables.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its
+ derivatives (`fun`, `jac` and `hess` functions).
+ method : str or callable, optional
+ Type of solver. Should be one of
+
+ - 'Nelder-Mead' :ref:`(see here) `
+ - 'Powell' :ref:`(see here) `
+ - 'CG' :ref:`(see here) `
+ - 'BFGS' :ref:`(see here) `
+ - 'Newton-CG' :ref:`(see here) `
+ - 'L-BFGS-B' :ref:`(see here) `
+ - 'TNC' :ref:`(see here) `
+ - 'COBYLA' :ref:`(see here) `
+ - 'COBYQA' :ref:`(see here) `
+ - 'SLSQP' :ref:`(see here) `
+ - 'trust-constr':ref:`(see here) `
+ - 'dogleg' :ref:`(see here) `
+ - 'trust-ncg' :ref:`(see here) `
+ - 'trust-exact' :ref:`(see here) `
+ - 'trust-krylov' :ref:`(see here) `
+ - custom - a callable object, see below for description.
+
+ If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``,
+ depending on whether or not the problem has constraints or bounds.
+ jac : {callable, '2-point', '3-point', 'cs', bool}, optional
+ Method for computing the gradient vector. Only for CG, BFGS,
+ Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov,
+ trust-exact and trust-constr.
+ If it is a callable, it should be a function that returns the gradient
+ vector::
+
+ jac(x, *args) -> array_like, shape (n,)
+
+ where ``x`` is an array with shape (n,) and ``args`` is a tuple with
+ the fixed parameters. If `jac` is a Boolean and is True, `fun` is
+ assumed to return a tuple ``(f, g)`` containing the objective
+ function and the gradient.
+ Methods 'Newton-CG', 'trust-ncg', 'dogleg', 'trust-exact', and
+ 'trust-krylov' require that either a callable be supplied, or that
+ `fun` return the objective and gradient.
+ If None or False, the gradient will be estimated using 2-point finite
+ difference estimation with an absolute step size.
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used
+ to select a finite difference scheme for numerical estimation of the
+ gradient with a relative step size. These finite difference schemes
+ obey any specified `bounds`.
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}, optional
+ Method for computing the Hessian matrix. Only for Newton-CG, dogleg,
+ trust-ncg, trust-krylov, trust-exact and trust-constr.
+ If it is callable, it should return the Hessian matrix::
+
+ hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)
+
+ where ``x`` is a (n,) ndarray and ``args`` is a tuple with the fixed
+ parameters.
+ The keywords {'2-point', '3-point', 'cs'} can also be used to select
+ a finite difference scheme for numerical estimation of the hessian.
+ Alternatively, objects implementing the `HessianUpdateStrategy`
+ interface can be used to approximate the Hessian. Available
+ quasi-Newton methods implementing this interface are:
+
+ - `BFGS`
+ - `SR1`
+
+ Not all of the options are available for each of the methods; for
+ availability refer to the notes.
+ hessp : callable, optional
+ Hessian of objective function times an arbitrary vector p. Only for
+ Newton-CG, trust-ncg, trust-krylov, trust-constr.
+ Only one of `hessp` or `hess` needs to be given. If `hess` is
+ provided, then `hessp` will be ignored. `hessp` must compute the
+ Hessian times an arbitrary vector::
+
+ hessp(x, p, *args) -> ndarray shape (n,)
+
+ where ``x`` is a (n,) ndarray, ``p`` is an arbitrary vector with
+ dimension (n,) and ``args`` is a tuple with the fixed
+ parameters.
+ bounds : sequence or `Bounds`, optional
+ Bounds on variables for Nelder-Mead, L-BFGS-B, TNC, SLSQP, Powell,
+ trust-constr, COBYLA, and COBYQA methods. There are two ways to specify
+ the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
+ is used to specify no bound.
+
+ constraints : {Constraint, dict} or List of {Constraint, dict}, optional
+ Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.
+
+ Constraints for 'trust-constr', 'cobyqa', and 'cobyla' are defined as a single
+ object or a list of objects specifying constraints to the optimization problem.
+ Available constraints are:
+
+ - `LinearConstraint`
+ - `NonlinearConstraint`
+
+ Constraints for COBYLA, SLSQP are defined as a list of dictionaries.
+ Each dictionary with fields:
+
+ type : str
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
+ fun : callable
+ The function defining the constraint.
+ jac : callable, optional
+ The Jacobian of `fun` (only for SLSQP).
+ args : sequence, optional
+ Extra arguments to be passed to the function and Jacobian.
+
+ Equality constraint means that the constraint function result is to
+ be zero whereas inequality means that it is to be non-negative.
+
+ tol : float, optional
+ Tolerance for termination. When `tol` is specified, the selected
+ minimization algorithm sets some relevant solver-specific tolerance(s)
+ equal to `tol`. For detailed control, use solver-specific
+ options.
+ callback : callable, optional
+ A callable called after each iteration.
+
+ All methods except TNC support a callable with
+ the signature::
+
+ callback(intermediate_result: OptimizeResult)
+
+ where ``intermediate_result`` is a keyword parameter containing an
+ `OptimizeResult` with attributes ``x`` and ``fun``, the present values
+ of the parameter vector and objective function. Not all attributes of
+ `OptimizeResult` may be present. The name of the parameter must be
+ ``intermediate_result`` for the callback to be passed an `OptimizeResult`.
+ These methods will also terminate if the callback raises ``StopIteration``.
+
+ All methods except trust-constr (also) support a signature like::
+
+ callback(xk)
+
+ where ``xk`` is the current parameter vector.
+
+ Introspection is used to determine which of the signatures above to
+ invoke.
+ options : dict, optional
+ A dictionary of solver options. All methods except `TNC` accept the
+ following generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform. Depending on the
+ method each iteration may use several function evaluations.
+
+ For `TNC` use `maxfun` instead of `maxiter`.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options()`.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ See Also
+ --------
+ minimize_scalar : Interface to minimization algorithms for scalar
+ univariate functions
+ show_options : Additional options accepted by the solvers
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter. The default method is *BFGS*.
+
+ **Unconstrained minimization**
+
+ Method :ref:`CG ` uses a nonlinear conjugate
+ gradient algorithm by Polak and Ribiere, a variant of the
+ Fletcher-Reeves method described in [5]_ pp.120-122. Only the
+ first derivatives are used.
+
+ Method :ref:`BFGS ` uses the quasi-Newton
+ method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [5]_
+ pp. 136. It uses the first derivatives only. BFGS has proven good
+ performance even for non-smooth optimizations. This method also
+ returns an approximation of the Hessian inverse, stored as
+ `hess_inv` in the OptimizeResult object.
+
+ Method :ref:`Newton-CG ` uses a
+ Newton-CG algorithm [5]_ pp. 168 (also known as the truncated
+ Newton method). It uses a CG method to the compute the search
+ direction. See also *TNC* method for a box-constrained
+ minimization with a similar algorithm. Suitable for large-scale
+ problems.
+
+ Method :ref:`dogleg ` uses the dog-leg
+ trust-region algorithm [5]_ for unconstrained minimization. This
+ algorithm requires the gradient and Hessian; furthermore the
+ Hessian is required to be positive definite.
+
+ Method :ref:`trust-ncg ` uses the
+ Newton conjugate gradient trust-region algorithm [5]_ for
+ unconstrained minimization. This algorithm requires the gradient
+ and either the Hessian or a function that computes the product of
+ the Hessian with a given vector. Suitable for large-scale problems.
+
+ Method :ref:`trust-krylov ` uses
+ the Newton GLTR trust-region algorithm [14]_, [15]_ for unconstrained
+ minimization. This algorithm requires the gradient
+ and either the Hessian or a function that computes the product of
+ the Hessian with a given vector. Suitable for large-scale problems.
+ On indefinite problems it requires usually less iterations than the
+ `trust-ncg` method and is recommended for medium and large-scale problems.
+
+ Method :ref:`trust-exact `
+ is a trust-region method for unconstrained minimization in which
+ quadratic subproblems are solved almost exactly [13]_. This
+ algorithm requires the gradient and the Hessian (which is
+ *not* required to be positive definite). It is, in many
+ situations, the Newton method to converge in fewer iterations
+ and the most recommended for small and medium-size problems.
+
+ **Bound-Constrained minimization**
+
+ Method :ref:`Nelder-Mead ` uses the
+ Simplex algorithm [1]_, [2]_. This algorithm is robust in many
+ applications. However, if numerical computation of derivative can be
+ trusted, other algorithms using the first and/or second derivatives
+ information might be preferred for their better performance in
+ general.
+
+ Method :ref:`L-BFGS-B ` uses the L-BFGS-B
+ algorithm [6]_, [7]_ for bound constrained minimization.
+
+ Method :ref:`Powell ` is a modification
+ of Powell's method [3]_, [4]_ which is a conjugate direction
+ method. It performs sequential one-dimensional minimizations along
+ each vector of the directions set (`direc` field in `options` and
+ `info`), which is updated at each iteration of the main
+ minimization loop. The function need not be differentiable, and no
+ derivatives are taken. If bounds are not provided, then an
+ unbounded line search will be used. If bounds are provided and
+ the initial guess is within the bounds, then every function
+ evaluation throughout the minimization procedure will be within
+ the bounds. If bounds are provided, the initial guess is outside
+ the bounds, and `direc` is full rank (default has full rank), then
+ some function evaluations during the first iteration may be
+ outside the bounds, but every function evaluation after the first
+ iteration will be within the bounds. If `direc` is not full rank,
+ then some parameters may not be optimized and the solution is not
+ guaranteed to be within the bounds.
+
+ Method :ref:`TNC ` uses a truncated Newton
+ algorithm [5]_, [8]_ to minimize a function with variables subject
+ to bounds. This algorithm uses gradient information; it is also
+ called Newton Conjugate-Gradient. It differs from the *Newton-CG*
+ method described above as it wraps a C implementation and allows
+ each variable to be given upper and lower bounds.
+
+ **Constrained Minimization**
+
+ Method :ref:`COBYLA ` uses the PRIMA
+ implementation [19]_ of the
+ Constrained Optimization BY Linear Approximation (COBYLA) method
+ [9]_, [10]_, [11]_. The algorithm is based on linear
+ approximations to the objective function and each constraint.
+
+ Method :ref:`COBYQA ` uses the Constrained
+ Optimization BY Quadratic Approximations (COBYQA) method [18]_. The
+ algorithm is a derivative-free trust-region SQP method based on quadratic
+ approximations to the objective function and each nonlinear constraint. The
+ bounds are treated as unrelaxable constraints, in the sense that the
+ algorithm always respects them throughout the optimization process.
+
+ Method :ref:`SLSQP ` uses Sequential
+ Least SQuares Programming to minimize a function of several
+ variables with any combination of bounds, equality and inequality
+ constraints. The method wraps the SLSQP Optimization subroutine
+ originally implemented by Dieter Kraft [12]_. Note that the
+ wrapper handles infinite values in bounds by converting them into
+ large floating values.
+
+ Method :ref:`trust-constr ` is a
+ trust-region algorithm for constrained optimization. It switches
+ between two implementations depending on the problem definition.
+ It is the most versatile constrained minimization algorithm
+ implemented in SciPy and the most appropriate for large-scale problems.
+ For equality constrained problems it is an implementation of Byrd-Omojokun
+ Trust-Region SQP method described in [17]_ and in [5]_, p. 549. When
+ inequality constraints are imposed as well, it switches to the trust-region
+ interior point method described in [16]_. This interior point algorithm,
+ in turn, solves inequality constraints by introducing slack variables
+ and solving a sequence of equality-constrained barrier problems
+ for progressively smaller values of the barrier parameter.
+ The previously described equality constrained SQP method is
+ used to solve the subproblems with increasing levels of accuracy
+ as the iterate gets closer to a solution.
+
+ **Finite-Difference Options**
+
+ For Method :ref:`trust-constr `
+ the gradient and the Hessian may be approximated using
+ three finite-difference schemes: {'2-point', '3-point', 'cs'}.
+ The scheme 'cs' is, potentially, the most accurate but it
+ requires the function to correctly handle complex inputs and to
+ be differentiable in the complex plane. The scheme '3-point' is more
+ accurate than '2-point' but requires twice as many operations. If the
+ gradient is estimated via finite-differences the Hessian must be
+ estimated using one of the quasi-Newton strategies.
+
+ **Method specific options for the** `hess` **keyword**
+
+ +--------------+------+----------+-------------------------+-----+
+ | method/Hess | None | callable | '2-point/'3-point'/'cs' | HUS |
+ +==============+======+==========+=========================+=====+
+ | Newton-CG | x | (n, n) | x | x |
+ | | | LO | | |
+ +--------------+------+----------+-------------------------+-----+
+ | dogleg | | (n, n) | | |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-ncg | | (n, n) | x | x |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-krylov | | (n, n) | x | x |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-exact | | (n, n) | | |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-constr | x | (n, n) | x | x |
+ | | | LO | | |
+ | | | sp | | |
+ +--------------+------+----------+-------------------------+-----+
+
+ where LO=LinearOperator, sp=Sparse matrix, HUS=HessianUpdateStrategy
+
+ **Custom minimizers**
+
+ It may be useful to pass a custom minimization method, for example
+ when using a frontend to this method such as `scipy.optimize.basinhopping`
+ or a different library. You can simply pass a callable as the ``method``
+ parameter.
+
+ The callable is called as ``method(fun, x0, args, **kwargs, **options)``
+ where ``kwargs`` corresponds to any other parameters passed to `minimize`
+ (such as `callback`, `hess`, etc.), except the `options` dict, which has
+ its contents also passed as `method` parameters pair by pair. Also, if
+ `jac` has been passed as a bool type, `jac` and `fun` are mangled so that
+ `fun` returns just the function values and `jac` is converted to a function
+ returning the Jacobian. The method shall return an `OptimizeResult`
+ object.
+
+ The provided `method` callable must be able to accept (and possibly ignore)
+ arbitrary parameters; the set of parameters accepted by `minimize` may
+ expand in future versions and then these parameters will be passed to
+ the method. You can find an example in the scipy.optimize tutorial.
+
+ References
+ ----------
+ .. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function
+ Minimization. The Computer Journal 7: 308-13.
+ .. [2] Wright M H. 1996. Direct search methods: Once scorned, now
+ respectable, in Numerical Analysis 1995: Proceedings of the 1995
+ Dundee Biennial Conference in Numerical Analysis (Eds. D F
+ Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK.
+ 191-208.
+ .. [3] Powell, M J D. 1964. An efficient method for finding the minimum of
+ a function of several variables without calculating derivatives. The
+ Computer Journal 7: 155-162.
+ .. [4] Press W, S A Teukolsky, W T Vetterling and B P Flannery.
+ Numerical Recipes (any edition), Cambridge University Press.
+ .. [5] Nocedal, J, and S J Wright. 2006. Numerical Optimization.
+ Springer New York.
+ .. [6] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory
+ Algorithm for Bound Constrained Optimization. SIAM Journal on
+ Scientific and Statistical Computing 16 (5): 1190-1208.
+ .. [7] Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm
+ 778: L-BFGS-B, FORTRAN routines for large scale bound constrained
+ optimization. ACM Transactions on Mathematical Software 23 (4):
+ 550-560.
+ .. [8] Nash, S G. Newton-Type Minimization Via the Lanczos Method.
+ 1984. SIAM Journal of Numerical Analysis 21: 770-778.
+ .. [9] Powell, M J D. A direct search optimization method that models
+ the objective and constraint functions by linear interpolation.
+ 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez
+ and J-P Hennart, Kluwer Academic (Dordrecht), 51-67.
+ .. [10] Powell M J D. Direct search algorithms for optimization
+ calculations. 1998. Acta Numerica 7: 287-336.
+ .. [11] Powell M J D. A view of algorithms for optimization without
+ derivatives. 2007.Cambridge University Technical Report DAMTP
+ 2007/NA03
+ .. [12] Kraft, D. A software package for sequential quadratic
+ programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace
+ Center -- Institute for Flight Mechanics, Koln, Germany.
+ .. [13] Conn, A. R., Gould, N. I., and Toint, P. L.
+ Trust region methods. 2000. Siam. pp. 169-200.
+ .. [14] F. Lenders, C. Kirches, A. Potschka: "trlib: A vector-free
+ implementation of the GLTR method for iterative solution of
+ the trust region problem", :arxiv:`1611.04718`
+ .. [15] N. Gould, S. Lucidi, M. Roma, P. Toint: "Solving the
+ Trust-Region Subproblem using the Lanczos Method",
+ SIAM J. Optim., 9(2), 504--525, (1999).
+ .. [16] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. 1999.
+ An interior point algorithm for large-scale nonlinear programming.
+ SIAM Journal on Optimization 9.4: 877-900.
+ .. [17] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. 1998. On the
+ implementation of an algorithm for large-scale equality constrained
+ optimization. SIAM Journal on Optimization 8.3: 682-706.
+ .. [18] Ragonneau, T. M. *Model-Based Derivative-Free Optimization Methods
+ and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+ Kong Polytechnic University, Hong Kong, China, 2022. URL:
+ https://theses.lib.polyu.edu.hk/handle/200/12294.
+ .. [19] Zhang, Z. "PRIMA: Reference Implementation for Powell's Methods with
+ Modernization and Amelioration", https://www.libprima.net,
+ :doi:`10.5281/zenodo.8052654`
+ .. [20] Karush-Kuhn-Tucker conditions,
+ https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions
+
+ Examples
+ --------
+ Let us consider the problem of minimizing the Rosenbrock function. This
+ function (and its respective derivatives) is implemented in `rosen`
+ (resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`.
+
+ >>> from scipy.optimize import minimize, rosen, rosen_der
+
+ A simple application of the *Nelder-Mead* method is:
+
+ >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+ >>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6)
+ >>> res.x
+ array([ 1., 1., 1., 1., 1.])
+
+ Now using the *BFGS* algorithm, using the first derivative and a few
+ options:
+
+ >>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der,
+ ... options={'gtol': 1e-6, 'disp': True})
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 26
+ Function evaluations: 31
+ Gradient evaluations: 31
+ >>> res.x
+ array([ 1., 1., 1., 1., 1.])
+ >>> print(res.message)
+ Optimization terminated successfully.
+ >>> res.hess_inv
+ array([
+ [ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary
+ [ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269],
+ [ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151],
+ [ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ],
+ [ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523]
+ ])
+
+ Next, consider a minimization problem with several constraints (namely
+ Example 16.4 from [5]_). The objective function is:
+
+ >>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2
+
+ There are three constraints defined as:
+
+ >>> cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ ... {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
+ ... {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})
+
+ And variables must be positive, hence the following bounds:
+
+ >>> bnds = ((0, None), (0, None))
+
+ The optimization problem is solved using the SLSQP method as:
+
+ >>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, constraints=cons)
+
+ It should converge to the theoretical solution ``[1.4 ,1.7]``. *SLSQP* also
+ returns the multipliers that are used in the solution of the problem. These
+ multipliers, when the problem constraints are linear, can be thought of as the
+ Karush-Kuhn-Tucker (KKT) multipliers, which are a generalization
+ of Lagrange multipliers to inequality-constrained optimization problems ([20]_).
+
+ Notice that at the solution, the first constraint is active. Let's evaluate the
+ function at solution:
+
+ >>> cons[0]['fun'](res.x)
+ np.float64(1.4901224698604665e-09)
+
+ Also, notice that at optimality there is a non-zero multiplier:
+
+ >>> res.multipliers
+ array([0.8, 0. , 0. ])
+
+ This can be understood as the local sensitivity of the optimal value of the
+ objective function with respect to changes in the first constraint. If we
+ tighten the constraint by a small amount ``eps``:
+
+ >>> eps = 0.01
+ >>> cons[0]['fun'] = lambda x: x[0] - 2 * x[1] + 2 - eps
+
+ we expect the optimal value of the objective function to increase by
+ approximately ``eps * res.multipliers[0]``:
+
+ >>> eps * res.multipliers[0] # Expected change in f0
+ np.float64(0.008000000027153205)
+ >>> f0 = res.fun # Keep track of the previous optimal value
+ >>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, constraints=cons)
+ >>> f1 = res.fun # New optimal value
+ >>> f1 - f0
+ np.float64(0.008019998807885509)
+
+ """
+ x0 = np.atleast_1d(np.asarray(x0))
+
+ if x0.ndim != 1:
+ raise ValueError("'x0' must only have one dimension.")
+
+ if x0.dtype.kind in np.typecodes["AllInteger"]:
+ x0 = np.asarray(x0, dtype=float)
+
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ if method is None:
+ # Select automatically
+ if constraints:
+ method = 'SLSQP'
+ elif bounds is not None:
+ method = 'L-BFGS-B'
+ else:
+ method = 'BFGS'
+
+ if callable(method):
+ meth = "_custom"
+ else:
+ meth = method.lower()
+
+ if options is None:
+ options = {}
+ # check if optional parameters are supported by the selected method
+ # - jac
+ if meth in ('nelder-mead', 'powell', 'cobyla', 'cobyqa') and bool(jac):
+ warn(f'Method {method} does not use gradient information (jac).',
+ RuntimeWarning, stacklevel=2)
+ # - hess
+ if meth not in ('newton-cg', 'dogleg', 'trust-ncg', 'trust-constr',
+ 'trust-krylov', 'trust-exact', '_custom') and hess is not None:
+ warn(f'Method {method} does not use Hessian information (hess).',
+ RuntimeWarning, stacklevel=2)
+ # - hessp
+ if meth not in ('newton-cg', 'trust-ncg', 'trust-constr',
+ 'trust-krylov', '_custom') \
+ and hessp is not None:
+ warn(f'Method {method} does not use Hessian-vector product'
+ ' information (hessp).',
+ RuntimeWarning, stacklevel=2)
+ # - constraints or bounds
+ if (meth not in ('cobyla', 'cobyqa', 'slsqp', 'trust-constr', '_custom') and
+ np.any(constraints)):
+ warn(f'Method {method} cannot handle constraints.',
+ RuntimeWarning, stacklevel=2)
+ if meth not in (
+ 'nelder-mead', 'powell', 'l-bfgs-b', 'cobyla', 'cobyqa', 'slsqp',
+ 'tnc', 'trust-constr', '_custom') and bounds is not None:
+ warn(f'Method {method} cannot handle bounds.',
+ RuntimeWarning, stacklevel=2)
+ # - return_all
+ if (meth in ('l-bfgs-b', 'tnc', 'cobyla', 'cobyqa', 'slsqp') and
+ options.get('return_all', False)):
+ warn(f'Method {method} does not support the return_all option.',
+ RuntimeWarning, stacklevel=2)
+
+ # check gradient vector
+ if callable(jac):
+ pass
+ elif jac is True:
+ # fun returns func and grad
+ fun = MemoizeJac(fun)
+ jac = fun.derivative
+ elif (jac in FD_METHODS and
+ meth in ['trust-constr', 'bfgs', 'cg', 'l-bfgs-b', 'tnc', 'slsqp']):
+ # finite differences with relative step
+ pass
+ elif meth in ['trust-constr']:
+ # default jac calculation for this method
+ jac = '2-point'
+ elif jac is None or bool(jac) is False:
+ # this will cause e.g. LBFGS to use forward difference, absolute step
+ jac = None
+ else:
+ # default if jac option is not understood
+ jac = None
+
+ # set default tolerances
+ if tol is not None:
+ options = dict(options)
+ if meth == 'nelder-mead':
+ options.setdefault('xatol', tol)
+ options.setdefault('fatol', tol)
+ if meth in ('newton-cg', 'powell', 'tnc'):
+ options.setdefault('xtol', tol)
+ if meth in ('powell', 'l-bfgs-b', 'tnc', 'slsqp'):
+ options.setdefault('ftol', tol)
+ if meth in ('bfgs', 'cg', 'l-bfgs-b', 'tnc', 'dogleg',
+ 'trust-ncg', 'trust-exact', 'trust-krylov'):
+ options.setdefault('gtol', tol)
+ if meth in ('cobyla', '_custom'):
+ options.setdefault('tol', tol)
+ if meth == 'cobyqa':
+ options.setdefault('final_tr_radius', tol)
+ if meth == 'trust-constr':
+ options.setdefault('xtol', tol)
+ options.setdefault('gtol', tol)
+ options.setdefault('barrier_tol', tol)
+
+ if meth == '_custom':
+ # custom method called before bounds and constraints are 'standardised'
+ # custom method should be able to accept whatever bounds/constraints
+ # are provided to it.
+ return method(fun, x0, args=args, jac=jac, hess=hess, hessp=hessp,
+ bounds=bounds, constraints=constraints,
+ callback=callback, **options)
+
+ constraints = standardize_constraints(constraints, x0, meth)
+
+ remove_vars = False
+ if bounds is not None:
+ # convert to new-style bounds so we only have to consider one case
+ bounds = standardize_bounds(bounds, x0, 'new')
+ bounds = _validate_bounds(bounds, x0, meth)
+
+ if meth in {"tnc", "slsqp", "l-bfgs-b"}:
+ # These methods can't take the finite-difference derivatives they
+ # need when a variable is fixed by the bounds. To avoid this issue,
+ # remove fixed variables from the problem.
+ # NOTE: if this list is expanded, then be sure to update the
+ # accompanying tests and test_optimize.eb_data. Consider also if
+ # default OptimizeResult will need updating.
+
+ # determine whether any variables are fixed
+ i_fixed = (bounds.lb == bounds.ub)
+
+ if np.all(i_fixed):
+ # all the parameters are fixed, a minimizer is not able to do
+ # anything
+ return _optimize_result_for_equal_bounds(
+ fun, bounds, meth, args=args, constraints=constraints
+ )
+
+ # determine whether finite differences are needed for any grad/jac
+ fd_needed = (not callable(jac))
+ for con in constraints:
+ if not callable(con.get('jac', None)):
+ fd_needed = True
+
+ # If finite differences are ever used, remove all fixed variables
+ # Always remove fixed variables for TNC; see gh-14565
+ remove_vars = i_fixed.any() and (fd_needed or meth == "tnc")
+ if remove_vars:
+ x_fixed = (bounds.lb)[i_fixed]
+ x0 = x0[~i_fixed]
+ bounds = _remove_from_bounds(bounds, i_fixed)
+ fun = _Remove_From_Func(fun, i_fixed, x_fixed)
+
+ if callable(callback):
+ sig = wrapped_inspect_signature(callback)
+ if set(sig.parameters) == {'intermediate_result'}:
+ # callback(intermediate_result)
+ print(callback)
+ callback = _Patch_Callback_Equal_Variables(
+ callback, i_fixed, x_fixed
+ )
+ else:
+ # callback(x)
+ callback = _Remove_From_Func(callback, i_fixed, x_fixed)
+
+ if callable(jac):
+ jac = _Remove_From_Func(jac, i_fixed, x_fixed, remove=1)
+
+ # make a copy of the constraints so the user's version doesn't
+ # get changed. (Shallow copy is ok)
+ constraints = [con.copy() for con in constraints]
+ for con in constraints: # yes, guaranteed to be a list
+ con['fun'] = _Remove_From_Func(con['fun'], i_fixed,
+ x_fixed, min_dim=1,
+ remove=0)
+ if callable(con.get('jac', None)):
+ con['jac'] = _Remove_From_Func(con['jac'], i_fixed,
+ x_fixed, min_dim=2,
+ remove=1)
+ bounds = standardize_bounds(bounds, x0, meth)
+
+ # selects whether to use callback(x) or callback(intermediate_result)
+ callback = _wrap_callback(callback, meth)
+
+ if meth == 'nelder-mead':
+ res = _minimize_neldermead(fun, x0, args, callback, bounds=bounds,
+ **options)
+ elif meth == 'powell':
+ res = _minimize_powell(fun, x0, args, callback, bounds, **options)
+ elif meth == 'cg':
+ res = _minimize_cg(fun, x0, args, jac, callback, **options)
+ elif meth == 'bfgs':
+ res = _minimize_bfgs(fun, x0, args, jac, callback, **options)
+ elif meth == 'newton-cg':
+ res = _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
+ **options)
+ elif meth == 'l-bfgs-b':
+ res = _minimize_lbfgsb(fun, x0, args, jac, bounds,
+ callback=callback, **options)
+ elif meth == 'tnc':
+ res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback,
+ **options)
+ elif meth == 'cobyla':
+ res = _minimize_cobyla(fun, x0, args, constraints, callback=callback,
+ bounds=bounds, **options)
+ elif meth == 'cobyqa':
+ res = _minimize_cobyqa(fun, x0, args, bounds, constraints, callback,
+ **options)
+ elif meth == 'slsqp':
+ res = _minimize_slsqp(fun, x0, args, jac, bounds,
+ constraints, callback=callback, **options)
+ elif meth == 'trust-constr':
+ res = _minimize_trustregion_constr(fun, x0, args, jac, hess, hessp,
+ bounds, constraints,
+ callback=callback, **options)
+ elif meth == 'dogleg':
+ res = _minimize_dogleg(fun, x0, args, jac, hess,
+ callback=callback, **options)
+ elif meth == 'trust-ncg':
+ res = _minimize_trust_ncg(fun, x0, args, jac, hess, hessp,
+ callback=callback, **options)
+ elif meth == 'trust-krylov':
+ res = _minimize_trust_krylov(fun, x0, args, jac, hess, hessp,
+ callback=callback, **options)
+ elif meth == 'trust-exact':
+ res = _minimize_trustregion_exact(fun, x0, args, jac, hess,
+ callback=callback, **options)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ if remove_vars:
+ res.x = _add_to_array(res.x, i_fixed, x_fixed)
+ res.jac = _add_to_array(res.jac, i_fixed, np.nan)
+ if "hess_inv" in res:
+ res.hess_inv = None # unknown
+
+ if getattr(callback, 'stop_iteration', False):
+ res.success = False
+ res.status = 99
+ res.message = "`callback` raised `StopIteration`."
+
+ return res
+
+
+def minimize_scalar(fun, bracket=None, bounds=None, args=(),
+ method=None, tol=None, options=None):
+ """Local minimization of scalar function of one variable.
+
+ Parameters
+ ----------
+ fun : callable
+ Objective function.
+ Scalar function, must return a scalar.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+
+ bracket : sequence, optional
+ For methods 'brent' and 'golden', `bracket` defines the bracketing
+ interval and is required.
+ Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair
+ ``(xa, xb)`` to be used as initial points for a downhill bracket search
+ (see `scipy.optimize.bracket`).
+ The minimizer ``res.x`` will not necessarily satisfy
+ ``xa <= res.x <= xb``.
+ bounds : sequence, optional
+ For method 'bounded', `bounds` is mandatory and must have two finite
+ items corresponding to the optimization bounds.
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ method : str or callable, optional
+ Type of solver. Should be one of:
+
+ - :ref:`Brent `
+ - :ref:`Bounded `
+ - :ref:`Golden `
+ - custom - a callable object (added in version 0.14.0), see below
+
+ Default is "Bounded" if bounds are provided and "Brent" otherwise.
+ See the 'Notes' section for details of each solver.
+
+ tol : float, optional
+ Tolerance for termination. For detailed control, use solver-specific
+ options.
+ options : dict, optional
+ A dictionary of solver options.
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ See :func:`show_options()` for solver-specific options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ See Also
+ --------
+ minimize : Interface to minimization algorithms for scalar multivariate
+ functions
+ show_options : Additional options accepted by the solvers
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter. The default method is the ``"Bounded"`` Brent method if
+ `bounds` are passed and unbounded ``"Brent"`` otherwise.
+
+ Method :ref:`Brent ` uses Brent's
+ algorithm [1]_ to find a local minimum. The algorithm uses inverse
+ parabolic interpolation when possible to speed up convergence of
+ the golden section method.
+
+ Method :ref:`Golden ` uses the
+ golden section search technique [1]_. It uses analog of the bisection
+ method to decrease the bracketed interval. It is usually
+ preferable to use the *Brent* method.
+
+ Method :ref:`Bounded ` can
+ perform bounded minimization [2]_ [3]_. It uses the Brent method to find a
+ local minimum in the interval x1 < xopt < x2.
+
+ Note that the Brent and Golden methods do not guarantee success unless a
+ valid ``bracket`` triple is provided. If a three-point bracket cannot be
+ found, consider `scipy.optimize.minimize`. Also, all methods are intended
+ only for local minimization. When the function of interest has more than
+ one local minimum, consider :ref:`global_optimization`.
+
+ **Custom minimizers**
+
+ It may be useful to pass a custom minimization method, for example
+ when using some library frontend to minimize_scalar. You can simply
+ pass a callable as the ``method`` parameter.
+
+ The callable is called as ``method(fun, args, **kwargs, **options)``
+ where ``kwargs`` corresponds to any other parameters passed to `minimize`
+ (such as `bracket`, `tol`, etc.), except the `options` dict, which has
+ its contents also passed as `method` parameters pair by pair. The method
+ shall return an `OptimizeResult` object.
+
+ The provided `method` callable must be able to accept (and possibly ignore)
+ arbitrary parameters; the set of parameters accepted by `minimize` may
+ expand in future versions and then these parameters will be passed to
+ the method. You can find an example in the scipy.optimize tutorial.
+
+ .. versionadded:: 0.11.0
+
+ References
+ ----------
+ .. [1] Press, W., S.A. Teukolsky, W.T. Vetterling, and B.P. Flannery.
+ Numerical Recipes in C. Cambridge University Press.
+ .. [2] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods
+ for Mathematical Computations." Prentice-Hall Series in Automatic
+ Computation 259 (1977).
+ .. [3] Brent, Richard P. Algorithms for Minimization Without Derivatives.
+ Courier Corporation, 2013.
+
+ Examples
+ --------
+ Consider the problem of minimizing the following function.
+
+ >>> def f(x):
+ ... return (x - 2) * x * (x + 2)**2
+
+ Using the *Brent* method, we find the local minimum as:
+
+ >>> from scipy.optimize import minimize_scalar
+ >>> res = minimize_scalar(f)
+ >>> res.fun
+ -9.9149495908
+
+ The minimizer is:
+
+ >>> res.x
+ 1.28077640403
+
+ Using the *Bounded* method, we find a local minimum with specified
+ bounds as:
+
+ >>> res = minimize_scalar(f, bounds=(-3, -1), method='bounded')
+ >>> res.fun # minimum
+ 3.28365179850e-13
+ >>> res.x # minimizer
+ -2.0000002026
+
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ if callable(method):
+ meth = "_custom"
+ elif method is None:
+ meth = 'brent' if bounds is None else 'bounded'
+ else:
+ meth = method.lower()
+ if options is None:
+ options = {}
+
+ if bounds is not None and meth in {'brent', 'golden'}:
+ message = f"Use of `bounds` is incompatible with 'method={method}'."
+ raise ValueError(message)
+
+ if tol is not None:
+ options = dict(options)
+ if meth == 'bounded' and 'xatol' not in options:
+ warn("Method 'bounded' does not support relative tolerance in x; "
+ "defaulting to absolute tolerance.",
+ RuntimeWarning, stacklevel=2)
+ options['xatol'] = tol
+ elif meth == '_custom':
+ options.setdefault('tol', tol)
+ else:
+ options.setdefault('xtol', tol)
+
+ # replace boolean "disp" option, if specified, by an integer value.
+ disp = options.get('disp')
+ if isinstance(disp, bool):
+ options['disp'] = 2 * int(disp)
+
+ if meth == '_custom':
+ res = method(fun, args=args, bracket=bracket, bounds=bounds, **options)
+ elif meth == 'brent':
+ res = _recover_from_bracket_error(_minimize_scalar_brent,
+ fun, bracket, args, **options)
+ elif meth == 'bounded':
+ if bounds is None:
+ raise ValueError('The `bounds` parameter is mandatory for '
+ 'method `bounded`.')
+ res = _minimize_scalar_bounded(fun, bounds, args, **options)
+ elif meth == 'golden':
+ res = _recover_from_bracket_error(_minimize_scalar_golden,
+ fun, bracket, args, **options)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ # gh-16196 reported inconsistencies in the output shape of `res.x`. While
+ # fixing this, future-proof it for when the function is vectorized:
+ # the shape of `res.x` should match that of `res.fun`.
+ res.fun = np.asarray(res.fun)[()]
+ res.x = np.reshape(res.x, res.fun.shape)[()]
+ return res
+
+
+def _remove_from_bounds(bounds, i_fixed):
+ """Removes fixed variables from a `Bounds` instance"""
+ lb = bounds.lb[~i_fixed]
+ ub = bounds.ub[~i_fixed]
+ return Bounds(lb, ub) # don't mutate original Bounds object
+
+
+class _Patch_Callback_Equal_Variables:
+ # Patches a callback that accepts an intermediate_result
+ def __init__(self, callback, i_fixed, x_fixed):
+ self.callback = callback
+ self.i_fixed = i_fixed
+ self.x_fixed = x_fixed
+
+ def __call__(self, intermediate_result):
+ x_in = intermediate_result.x
+ x_out = np.zeros_like(self.i_fixed, dtype=x_in.dtype)
+ x_out[self.i_fixed] = self.x_fixed
+ x_out[~self.i_fixed] = x_in
+ intermediate_result.x = x_out
+ return self.callback(intermediate_result)
+
+
+class _Remove_From_Func:
+ """Wraps a function such that fixed variables need not be passed in"""
+ def __init__(self, fun_in, i_fixed, x_fixed, min_dim=None, remove=0):
+ self.fun_in = fun_in
+ self.i_fixed = i_fixed
+ self.x_fixed = x_fixed
+ self.min_dim = min_dim
+ self.remove = remove
+
+ def __call__(self, x_in, *args, **kwargs):
+ x_out = np.zeros_like(self.i_fixed, dtype=x_in.dtype)
+ x_out[self.i_fixed] = self.x_fixed
+ x_out[~self.i_fixed] = x_in
+ y_out = self.fun_in(x_out, *args, **kwargs)
+ y_out = np.array(y_out)
+
+ if self.min_dim == 1:
+ y_out = np.atleast_1d(y_out)
+ elif self.min_dim == 2:
+ y_out = np.atleast_2d(y_out)
+
+ if self.remove == 1:
+ y_out = y_out[..., ~self.i_fixed]
+ elif self.remove == 2:
+ y_out = y_out[~self.i_fixed, ~self.i_fixed]
+
+ return y_out
+
+
+def _add_to_array(x_in, i_fixed, x_fixed):
+ """Adds fixed variables back to an array"""
+ i_free = ~i_fixed
+ if x_in.ndim == 2:
+ i_free = i_free[:, None] @ i_free[None, :]
+ x_out = np.zeros_like(i_free, dtype=x_in.dtype)
+ x_out[~i_free] = x_fixed
+ x_out[i_free] = x_in.ravel()
+ return x_out
+
+
+def _validate_bounds(bounds, x0, meth):
+ """Check that bounds are valid."""
+
+ msg = "An upper bound is less than the corresponding lower bound."
+ if np.any(bounds.ub < bounds.lb):
+ raise ValueError(msg)
+
+ msg = "The number of bounds is not compatible with the length of `x0`."
+ try:
+ bounds.lb = np.broadcast_to(bounds.lb, x0.shape)
+ bounds.ub = np.broadcast_to(bounds.ub, x0.shape)
+ except Exception as e:
+ raise ValueError(msg) from e
+
+ return bounds
+
+def standardize_bounds(bounds, x0, meth):
+ """Converts bounds to the form required by the solver."""
+ if meth in {'trust-constr', 'powell', 'nelder-mead', 'cobyla', 'cobyqa',
+ 'new'}:
+ if not isinstance(bounds, Bounds):
+ lb, ub = old_bound_to_new(bounds)
+ bounds = Bounds(lb, ub)
+ elif meth in ('l-bfgs-b', 'tnc', 'slsqp', 'old'):
+ if isinstance(bounds, Bounds):
+ bounds = new_bounds_to_old(bounds.lb, bounds.ub, x0.shape[0])
+ return bounds
+
+
+def standardize_constraints(constraints, x0, meth):
+ """Converts constraints to the form required by the solver."""
+ all_constraint_types = (NonlinearConstraint, LinearConstraint, dict)
+ new_constraint_types = all_constraint_types[:-1]
+ if constraints is None:
+ constraints = []
+ elif isinstance(constraints, all_constraint_types):
+ constraints = [constraints]
+ else:
+ constraints = list(constraints) # ensure it's a mutable sequence
+
+ if meth in ['trust-constr', 'cobyqa', 'new', 'cobyla']:
+ for i, con in enumerate(constraints):
+ if not isinstance(con, new_constraint_types):
+ constraints[i] = old_constraint_to_new(i, con)
+ else:
+ # iterate over copy, changing original
+ for i, con in enumerate(list(constraints)):
+ if isinstance(con, new_constraint_types):
+ old_constraints = new_constraint_to_old(con, x0)
+ constraints[i] = old_constraints[0]
+ constraints.extend(old_constraints[1:]) # appends 1 if present
+
+ return constraints
+
+
+def _optimize_result_for_equal_bounds(
+ fun, bounds, method, args=(), constraints=()
+):
+ """
+ Provides a default OptimizeResult for when a bounded minimization method
+ has (lb == ub).all().
+
+ Parameters
+ ----------
+ fun: callable
+ bounds: Bounds
+ method: str
+ constraints: Constraint
+ """
+ success = True
+ message = 'All independent variables were fixed by bounds.'
+
+ # bounds is new-style
+ x0 = bounds.lb
+
+ if constraints:
+ message = ("All independent variables were fixed by bounds at values"
+ " that satisfy the constraints.")
+ constraints = standardize_constraints(constraints, x0, 'new')
+
+ maxcv = 0
+ for c in constraints:
+ pc = PreparedConstraint(c, x0)
+ violation = pc.violation(x0)
+ if np.sum(violation):
+ maxcv = max(maxcv, np.max(violation))
+ success = False
+ message = (f"All independent variables were fixed by bounds, but "
+ f"the independent variables do not satisfy the "
+ f"constraints exactly. (Maximum violation: {maxcv}).")
+
+ return OptimizeResult(
+ x=x0, fun=fun(x0, *args), success=success, message=message, nfev=1,
+ njev=0, nhev=0,
+ )
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..4b18a5a649d87c5085519514516cb255aa5118c4
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:88bb938afe7b847da09817c03d0a655930f6430b745f63e2ba24775f8019bf60
+size 104416
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_minpack_py.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_minpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ea6d4fa5038be229a26f0047857295a56e8d789
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_minpack_py.py
@@ -0,0 +1,1186 @@
+import warnings
+from . import _minpack
+
+import numpy as np
+from numpy import (atleast_1d, triu, shape, transpose, zeros, prod, greater,
+ asarray, inf,
+ finfo, inexact, issubdtype, dtype)
+from scipy import linalg
+from scipy.linalg import svd, cholesky, solve_triangular, LinAlgError
+from scipy._lib._util import _asarray_validated, _contains_nan
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+import scipy._external.array_api_extra as xpx
+from ._optimize import OptimizeResult, _check_unknown_options, OptimizeWarning
+from ._lsq import least_squares
+# from ._lsq.common import make_strictly_feasible
+from ._lsq.least_squares import prepare_bounds
+from scipy.optimize._minimize import Bounds
+
+__all__ = ['fsolve', 'leastsq', 'fixed_point', 'curve_fit']
+
+
+def _check_func(checker, argname, thefunc, x0, args, numinputs,
+ output_shape=None):
+ res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
+ if (output_shape is not None) and (shape(res) != output_shape):
+ if (output_shape[0] != 1):
+ if len(output_shape) > 1:
+ if output_shape[1] == 1:
+ return shape(res)
+ msg = f"{checker}: there is a mismatch between the input and output " \
+ f"shape of the '{argname}' argument"
+ func_name = getattr(thefunc, '__name__', None)
+ if func_name:
+ msg += f" '{func_name}'."
+ else:
+ msg += "."
+ msg += f' Shape should be {output_shape} but it is {shape(res)}.'
+ raise TypeError(msg)
+ if issubdtype(res.dtype, inexact):
+ dt = res.dtype
+ else:
+ dt = dtype(float)
+ return shape(res), dt
+
+
+def fsolve(func, x0, args=(), fprime=None, full_output=False,
+ col_deriv=False, xtol=1.49012e-8, maxfev=0, band=None,
+ epsfcn=None, factor=100, diag=None):
+ """
+ Find the roots of a function.
+
+ Return the roots of the (non-linear) equations defined by
+ ``func(x) = 0`` given a starting estimate.
+
+ Parameters
+ ----------
+ func : callable ``f(x, *args)``
+ A function that takes at least one (possibly vector) argument,
+ and returns a value of the same length.
+ x0 : ndarray
+ The starting estimate for the roots of ``func(x) = 0``.
+ args : tuple, optional
+ Any extra arguments to `func`.
+ fprime : callable ``f(x, *args)``, optional
+ A function to compute the Jacobian of `func` with derivatives
+ across the rows. By default, the Jacobian will be estimated.
+ full_output : bool, optional
+ If True, return optional outputs.
+ col_deriv : bool, optional
+ Specify whether the Jacobian function computes derivatives down
+ the columns (faster, because there is no transpose operation).
+ xtol : float, optional
+ The calculation will terminate if the relative error between two
+ consecutive iterates is at most `xtol`.
+ maxfev : int, optional
+ The maximum number of calls to the function. If zero, then
+ ``100*(N+1)`` is the maximum where N is the number of elements
+ in `x0`.
+ band : tuple, optional
+ If set to a two-sequence containing the number of sub- and
+ super-diagonals within the band of the Jacobi matrix, the
+ Jacobi matrix is considered banded (only for ``fprime=None``).
+ epsfcn : float, optional
+ A suitable step length for the forward-difference
+ approximation of the Jacobian (for ``fprime=None``). If
+ `epsfcn` is less than the machine precision, it is assumed
+ that the relative errors in the functions are of the order of
+ the machine precision.
+ factor : float, optional
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in the interval
+ ``(0.1, 100)``.
+ diag : sequence, optional
+ N positive entries that serve as a scale factors for the
+ variables.
+
+ Returns
+ -------
+ x : ndarray
+ The solution (or the result of the last iteration for
+ an unsuccessful call).
+ infodict : dict
+ A dictionary of optional outputs with the keys:
+
+ ``nfev``
+ number of function calls
+ ``njev``
+ number of Jacobian calls
+ ``fvec``
+ function evaluated at the output
+ ``fjac``
+ the orthogonal matrix, q, produced by the QR
+ factorization of the final approximate Jacobian
+ matrix, stored column wise
+ ``r``
+ upper triangular matrix produced by QR factorization
+ of the same matrix
+ ``qtf``
+ the vector ``(transpose(q) * fvec)``
+
+ ier : int
+ An integer flag. Set to 1 if a solution was found, otherwise refer
+ to `mesg` for more information.
+ mesg : str
+ If no solution is found, `mesg` details the cause of failure.
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See the ``method='hybr'`` in particular.
+
+ Notes
+ -----
+ ``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms.
+
+ Examples
+ --------
+ Find a solution to the system of equations:
+ ``x0*cos(x1) = 4, x1*x0 - x1 = 5``.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import fsolve
+ >>> def func(x):
+ ... return [x[0] * np.cos(x[1]) - 4,
+ ... x[1] * x[0] - x[1] - 5]
+ >>> root = fsolve(func, [1, 1])
+ >>> root
+ array([6.50409711, 0.90841421])
+ >>> np.isclose(func(root), [0.0, 0.0]) # func(root) should be almost 0.0.
+ array([ True, True])
+
+ """
+ def _wrapped_func(*fargs):
+ """
+ Wrapped `func` to track the number of times
+ the function has been called.
+ """
+ _wrapped_func.nfev += 1
+ return func(*fargs)
+
+ _wrapped_func.nfev = 0
+
+ options = {'col_deriv': col_deriv,
+ 'xtol': xtol,
+ 'maxfev': maxfev,
+ 'band': band,
+ 'eps': epsfcn,
+ 'factor': factor,
+ 'diag': diag}
+
+ res = _root_hybr(_wrapped_func, x0, args, jac=fprime, **options)
+ res.nfev = _wrapped_func.nfev
+
+ if full_output:
+ x = res['x']
+ info = {k: res.get(k)
+ for k in ('nfev', 'njev', 'fjac', 'r', 'qtf') if k in res}
+ info['fvec'] = res['fun']
+ return x, info, res['status'], res['message']
+ else:
+ status = res['status']
+ msg = res['message']
+ if status == 0:
+ raise TypeError(msg)
+ elif status == 1:
+ pass
+ elif status in [2, 3, 4, 5]:
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
+ else:
+ raise TypeError(msg)
+ return res['x']
+
+
+def _root_hybr(func, x0, args=(), jac=None,
+ col_deriv=False, xtol=1.49012e-08, maxfev=0, band=None, eps=None,
+ factor=100, diag=None, **unknown_options):
+ """
+ Find the roots of a multivariate function using MINPACK's hybrd and
+ hybrj routines (modified Powell method).
+
+ Options
+ -------
+ col_deriv : bool
+ Specify whether the Jacobian function computes derivatives down
+ the columns (faster, because there is no transpose operation).
+ xtol : float
+ The calculation will terminate if the relative error between two
+ consecutive iterates is at most `xtol`.
+ maxfev : int
+ The maximum number of calls to the function. If zero, then
+ ``100*(N+1)`` is the maximum where N is the number of elements
+ in `x0`.
+ band : tuple
+ If set to a two-sequence containing the number of sub- and
+ super-diagonals within the band of the Jacobi matrix, the
+ Jacobi matrix is considered banded (only for ``jac=None``).
+ eps : float
+ A suitable step length for the forward-difference
+ approximation of the Jacobian (for ``jac=None``). If
+ `eps` is less than the machine precision, it is assumed
+ that the relative errors in the functions are of the order of
+ the machine precision.
+ factor : float
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in the interval
+ ``(0.1, 100)``.
+ diag : sequence
+ N positive entries that serve as a scale factors for the
+ variables.
+
+ """
+ _check_unknown_options(unknown_options)
+ epsfcn = eps
+
+ x0 = asarray(x0).flatten()
+ n = len(x0)
+ if not isinstance(args, tuple):
+ args = (args,)
+ shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
+ if epsfcn is None:
+ epsfcn = finfo(dtype).eps
+ Dfun = jac
+ if Dfun is None:
+ if band is None:
+ ml, mu = -10, -10
+ else:
+ ml, mu = band[:2]
+ if maxfev == 0:
+ maxfev = 200 * (n + 1)
+ retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev,
+ ml, mu, epsfcn, factor, diag)
+ else:
+ _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n))
+ if (maxfev == 0):
+ maxfev = 100 * (n + 1)
+ retval = _minpack._hybrj(func, Dfun, x0, args, 1,
+ col_deriv, xtol, maxfev, factor, diag)
+
+ x, status = retval[0], retval[-1]
+
+ errors = {0: "Improper input parameters were entered.",
+ 1: "The solution converged.",
+ 2: "The number of calls to function has "
+ f"reached maxfev = {maxfev}.",
+ 3: f"xtol={xtol:f} is too small, no further improvement "
+ "in the approximate\n solution is possible.",
+ 4: "The iteration is not making good progress, as measured "
+ "by the \n improvement from the last five "
+ "Jacobian evaluations.",
+ 5: "The iteration is not making good progress, "
+ "as measured by the \n improvement from the last "
+ "ten iterations.",
+ 'unknown': "An error occurred."}
+
+ info = retval[1]
+ info['fun'] = info.pop('fvec')
+ sol = OptimizeResult(x=x, success=(status == 1), status=status,
+ method="hybr")
+ sol.update(info)
+ try:
+ sol['message'] = errors[status]
+ except KeyError:
+ sol['message'] = errors['unknown']
+
+ return sol
+
+
+LEASTSQ_SUCCESS = [1, 2, 3, 4]
+LEASTSQ_FAILURE = [5, 6, 7, 8]
+
+
+def leastsq(func, x0, args=(), Dfun=None, full_output=False,
+ col_deriv=False, ftol=1.49012e-8, xtol=1.49012e-8,
+ gtol=0.0, maxfev=0, epsfcn=None, factor=100, diag=None):
+ """
+ Minimize the sum of squares of a set of equations.
+
+ ::
+
+ x = arg min(sum(func(y)**2,axis=0))
+ y
+
+ Parameters
+ ----------
+ func : callable
+ Should take at least one (possibly length ``N`` vector) argument and
+ returns ``M`` floating point numbers. It must not return NaNs or
+ fitting might fail. ``M`` must be greater than or equal to ``N``.
+ x0 : ndarray
+ The starting estimate for the minimization.
+ args : tuple, optional
+ Any extra arguments to func are placed in this tuple.
+ Dfun : callable, optional
+ A function or method to compute the Jacobian of func with derivatives
+ across the rows. If this is None, the Jacobian will be estimated.
+ full_output : bool, optional
+ If ``True``, return all optional outputs (not just `x` and `ier`).
+ col_deriv : bool, optional
+ If ``True``, specify that the Jacobian function computes derivatives
+ down the columns (faster, because there is no transpose operation).
+ ftol : float, optional
+ Relative error desired in the sum of squares.
+ xtol : float, optional
+ Relative error desired in the approximate solution.
+ gtol : float, optional
+ Orthogonality desired between the function vector and the columns of
+ the Jacobian.
+ maxfev : int, optional
+ The maximum number of calls to the function. If `Dfun` is provided,
+ then the default `maxfev` is 100*(N+1) where N is the number of elements
+ in x0, otherwise the default `maxfev` is 200*(N+1).
+ epsfcn : float, optional
+ A variable used in determining a suitable step length for the forward-
+ difference approximation of the Jacobian (for Dfun=None).
+ Normally the actual step length will be sqrt(epsfcn)*x
+ If epsfcn is less than the machine precision, it is assumed that the
+ relative errors are of the order of the machine precision.
+ factor : float, optional
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
+ diag : sequence, optional
+ N positive entries that serve as a scale factors for the variables.
+
+ Returns
+ -------
+ x : ndarray
+ The solution (or the result of the last iteration for an unsuccessful
+ call).
+ cov_x : ndarray
+ The inverse of the Hessian. `fjac` and `ipvt` are used to construct an
+ estimate of the Hessian. A value of None indicates a singular matrix,
+ which means the curvature in parameters `x` is numerically flat. To
+ obtain the covariance matrix of the parameters `x`, `cov_x` must be
+ multiplied by the variance of the residuals -- see curve_fit. Only
+ returned if `full_output` is ``True``.
+ infodict : dict
+ a dictionary of optional outputs with the keys:
+
+ ``nfev``
+ The number of function calls
+ ``fvec``
+ The function evaluated at the output
+ ``fjac``
+ A permutation of the R matrix of a QR
+ factorization of the final approximate
+ Jacobian matrix, stored column wise.
+ Together with ipvt, the covariance of the
+ estimate can be approximated.
+ ``ipvt``
+ An integer array of length N which defines
+ a permutation matrix, p, such that
+ fjac*p = q*r, where r is upper triangular
+ with diagonal elements of nonincreasing
+ magnitude. Column j of p is column ipvt(j)
+ of the identity matrix.
+ ``qtf``
+ The vector (transpose(q) * fvec).
+
+ Only returned if `full_output` is ``True``.
+ mesg : str
+ A string message giving information about the cause of failure.
+ Only returned if `full_output` is ``True``.
+ ier : int
+ An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
+ found. Otherwise, the solution was not found. In either case, the
+ optional output variable 'mesg' gives more information.
+
+ See Also
+ --------
+ least_squares : Newer interface to solve nonlinear least-squares problems
+ with bounds on the variables. See ``method='lm'`` in particular.
+
+ Notes
+ -----
+ "leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms.
+
+ cov_x is a Jacobian approximation to the Hessian of the least squares
+ objective function.
+ This approximation assumes that the objective function is based on the
+ difference between some observed target data (ydata) and a (non-linear)
+ function of the parameters `f(xdata, params)` ::
+
+ func(params) = ydata - f(xdata, params)
+
+ so that the objective function is ::
+
+ min sum((ydata - f(xdata, params))**2, axis=0)
+ params
+
+ The solution, `x`, is always a 1-D array, regardless of the shape of `x0`,
+ or whether `x0` is a scalar.
+
+ Examples
+ --------
+ >>> from scipy.optimize import leastsq
+ >>> def func(x):
+ ... return 2*(x-3)**2+1
+ >>> leastsq(func, 0)
+ (array([2.99999999]), 1)
+
+ """
+ x0 = asarray(x0).flatten()
+ n = len(x0)
+ if not isinstance(args, tuple):
+ args = (args,)
+ shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
+ m = shape[0]
+
+ if n > m:
+ raise TypeError(f"Improper input: func input vector length N={n} must"
+ f" not exceed func output vector length M={m}")
+
+ if epsfcn is None:
+ epsfcn = finfo(dtype).eps
+
+ if Dfun is None:
+ if maxfev == 0:
+ maxfev = 200*(n + 1)
+ retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
+ gtol, maxfev, epsfcn, factor, diag)
+ else:
+ if col_deriv:
+ _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (n, m))
+ else:
+ _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (m, n))
+ if maxfev == 0:
+ maxfev = 100 * (n + 1)
+ retval = _minpack._lmder(func, Dfun, x0, args, full_output,
+ col_deriv, ftol, xtol, gtol, maxfev,
+ factor, diag)
+
+ errors = {0: ["Improper input parameters.", TypeError],
+ 1: ["Both actual and predicted relative reductions "
+ f"in the sum of squares\n are at most {ftol:f}", None],
+ 2: ["The relative error between two consecutive "
+ f"iterates is at most {xtol:f}", None],
+ 3: ["Both actual and predicted relative reductions in "
+ f"the sum of squares\n are at most {ftol:f} and the "
+ "relative error between two consecutive "
+ f"iterates is at \n most {xtol:f}", None],
+ 4: ["The cosine of the angle between func(x) and any "
+ f"column of the\n Jacobian is at most {gtol:f} in "
+ "absolute value", None],
+ 5: ["Number of calls to function has reached "
+ f"maxfev = {maxfev}.", ValueError],
+ 6: [f"ftol={ftol:f} is too small, no further reduction "
+ "in the sum of squares\n is possible.",
+ ValueError],
+ 7: [f"xtol={xtol:f} is too small, no further improvement in "
+ "the approximate\n solution is possible.",
+ ValueError],
+ 8: [f"gtol={gtol:f} is too small, func(x) is orthogonal to the "
+ "columns of\n the Jacobian to machine precision.", ValueError]}
+
+ # The FORTRAN return value (possible return values are >= 0 and <= 8)
+ info = retval[-1]
+
+ if full_output:
+ cov_x = None
+ if info in LEASTSQ_SUCCESS:
+ # This was
+ # perm = take(eye(n), retval[1]['ipvt'] - 1, 0)
+ # r = triu(transpose(retval[1]['fjac'])[:n, :])
+ # R = dot(r, perm)
+ # cov_x = inv(dot(transpose(R), R))
+ # but the explicit dot product was not necessary and sometimes
+ # the result was not symmetric positive definite. See gh-4555.
+ perm = retval[1]['ipvt']
+ n = len(perm)
+ r = triu(transpose(retval[1]['fjac'])[:n, :])
+ inv_triu = linalg.get_lapack_funcs('trtri', (r,))
+ try:
+ # inverse of permuted matrix is a permutation of matrix inverse
+ invR, trtri_info = inv_triu(r) # default: upper, non-unit diag
+ if trtri_info != 0: # explicit comparison for readability
+ raise LinAlgError(f'trtri returned info {trtri_info}')
+ invR[perm] = invR.copy()
+ cov_x = invR @ invR.T
+ except (LinAlgError, ValueError):
+ pass
+ return (retval[0], cov_x) + retval[1:-1] + (errors[info][0], info)
+ else:
+ if info in LEASTSQ_FAILURE:
+ warnings.warn(errors[info][0], RuntimeWarning, stacklevel=2)
+ elif info == 0:
+ raise errors[info][1](errors[info][0])
+ return retval[0], info
+
+
+def _lightweight_memoizer(f):
+ # very shallow memoization to address gh-13670: only remember the first set
+ # of parameters and corresponding function value, and only attempt to use
+ # them twice (the number of times the function is evaluated at x0).
+ def _memoized_func(params):
+ if _memoized_func.skip_lookup:
+ return f(params)
+
+ if np.all(_memoized_func.last_params == params):
+ return _memoized_func.last_val
+ elif _memoized_func.last_params is not None:
+ _memoized_func.skip_lookup = True
+
+ val = f(params)
+
+ if _memoized_func.last_params is None:
+ _memoized_func.last_params = np.copy(params)
+ _memoized_func.last_val = val
+
+ return val
+
+ _memoized_func.last_params = None
+ _memoized_func.last_val = None
+ _memoized_func.skip_lookup = False
+ return _memoized_func
+
+
+def _wrap_func(func, xdata, ydata, transform):
+ if transform is None:
+ def func_wrapped(params):
+ return func(xdata, *params) - ydata
+ elif transform.size == 1 or transform.ndim == 1:
+ def func_wrapped(params):
+ return transform * (func(xdata, *params) - ydata)
+ else:
+ # Chisq = (y - yd)^T C^{-1} (y-yd)
+ # transform = L such that C = L L^T
+ # C^{-1} = L^{-T} L^{-1}
+ # Chisq = (y - yd)^T L^{-T} L^{-1} (y-yd)
+ # Define (y-yd)' = L^{-1} (y-yd)
+ # by solving
+ # L (y-yd)' = (y-yd)
+ # and minimize (y-yd)'^T (y-yd)'
+ def func_wrapped(params):
+ return solve_triangular(transform, func(xdata, *params) - ydata, lower=True)
+ return func_wrapped
+
+
+def _wrap_jac(jac, xdata, transform):
+ if transform is None:
+ def jac_wrapped(params):
+ return jac(xdata, *params)
+ elif transform.ndim == 1:
+ def jac_wrapped(params):
+ return transform[:, np.newaxis] * np.asarray(jac(xdata, *params))
+ else:
+ def jac_wrapped(params):
+ return solve_triangular(transform,
+ np.asarray(jac(xdata, *params)),
+ lower=True)
+ return jac_wrapped
+
+
+def _initialize_feasible(lb, ub):
+ p0 = np.ones_like(lb)
+ lb_finite = np.isfinite(lb)
+ ub_finite = np.isfinite(ub)
+
+ mask = lb_finite & ub_finite
+ p0[mask] = 0.5 * (lb[mask] + ub[mask])
+
+ mask = lb_finite & ~ub_finite
+ p0[mask] = lb[mask] + 1
+
+ mask = ~lb_finite & ub_finite
+ p0[mask] = ub[mask] - 1
+
+ return p0
+
+
+def curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False,
+ check_finite=None, bounds=(-np.inf, np.inf), method=None,
+ jac=None, *, full_output=False, nan_policy=None,
+ **kwargs):
+ """
+ Use non-linear least squares to fit a function, f, to data.
+
+ Assumes ``ydata = f(xdata, *params) + eps``.
+
+ Parameters
+ ----------
+ f : callable
+ The model function, f(x, ...). It must take the independent
+ variable as the first argument and the parameters to fit as
+ separate remaining arguments.
+ xdata : array_like
+ The independent variable where the data is measured.
+ Should usually be an M-length sequence or an (k,M)-shaped array for
+ functions with k predictors, and each element should be float
+ convertible if it is an array like object.
+ ydata : array_like
+ The dependent data, a length M array - nominally ``f(xdata, ...)``.
+ p0 : array_like, optional
+ Initial guess for the parameters (length N). If None, then the
+ initial values will all be 1 (if the number of parameters for the
+ function can be determined using introspection, otherwise a
+ ValueError is raised).
+ sigma : None or scalar or M-length sequence or MxM array, optional
+ Determines the uncertainty in `ydata`. If we define residuals as
+ ``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma`
+ depends on its number of dimensions:
+
+ - A scalar or 1-D `sigma` should contain values of standard deviations of
+ errors in `ydata`. In this case, the optimized function is
+ ``chisq = sum((r / sigma) ** 2)``.
+
+ - A 2-D `sigma` should contain the covariance matrix of
+ errors in `ydata`. In this case, the optimized function is
+ ``chisq = r.T @ inv(sigma) @ r``.
+
+ .. versionadded:: 0.19
+
+ None (default) is equivalent of 1-D `sigma` filled with ones.
+ absolute_sigma : bool, optional
+ If True, `sigma` is used in an absolute sense and the estimated parameter
+ covariance `pcov` reflects these absolute values.
+
+ If False (default), only the relative magnitudes of the `sigma` values matter.
+ The returned parameter covariance matrix `pcov` is based on scaling
+ `sigma` by a constant factor. This constant is set by demanding that the
+ reduced `chisq` for the optimal parameters `popt` when using the
+ *scaled* `sigma` equals unity. In other words, `sigma` is scaled to
+ match the sample variance of the residuals after the fit. Default is False.
+ Mathematically,
+ ``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)``
+ check_finite : bool, optional
+ If True, check that the input arrays do not contain nans of infs,
+ and raise a ValueError if they do. Setting this parameter to
+ False may silently produce nonsensical results if the input arrays
+ do contain nans. Default is True if `nan_policy` is not specified
+ explicitly and False otherwise.
+ bounds : 2-tuple of array_like or `Bounds`, optional
+ Lower and upper bounds on parameters. Defaults to no bounds.
+ There are two ways to specify the bounds:
+
+ - Instance of `Bounds` class.
+
+ - 2-tuple of array_like: Each element of the tuple must be either
+ an array with the length equal to the number of parameters, or a
+ scalar (in which case the bound is taken to be the same for all
+ parameters). Use ``np.inf`` with an appropriate sign to disable
+ bounds on all or some parameters.
+
+ method : {'lm', 'trf', 'dogbox'}, optional
+ Method to use for optimization. See `least_squares` for more details.
+ Default is 'lm' for unconstrained problems and 'trf' if `bounds` are
+ provided. The method 'lm' won't work when the number of observations
+ is less than the number of variables, use 'trf' or 'dogbox' in this
+ case.
+
+ .. versionadded:: 0.17
+ jac : callable, str or None, optional
+ Function with signature ``jac(x, ...)`` which computes the Jacobian
+ matrix of the model function with respect to parameters as a dense
+ array_like structure. It will be scaled according to provided `sigma`.
+ If None (default), the Jacobian will be estimated numerically.
+ String keywords for 'trf' and 'dogbox' methods can be used to select
+ a finite difference scheme, see `least_squares`.
+
+ .. versionadded:: 0.18
+ full_output : bool, optional
+ If True, this function returns additional information: `infodict`,
+ `mesg`, and `ier`.
+
+ .. versionadded:: 1.9
+ nan_policy : {'raise', 'omit', None}, optional
+ Defines how to handle when input contains nan.
+ The following options are available (default is None):
+
+ * 'raise': throws an error
+ * 'omit': performs the calculations ignoring nan values
+ * None: no special handling of NaNs is performed
+ (except what is done by check_finite); the behavior when NaNs
+ are present is implementation-dependent and may change.
+
+ Note that if this value is specified explicitly (not None),
+ `check_finite` will be set as False.
+
+ .. versionadded:: 1.11
+ **kwargs
+ Keyword arguments passed to `leastsq` for ``method='lm'`` or
+ `least_squares` otherwise.
+
+ Returns
+ -------
+ popt : array
+ Optimal values for the parameters so that the sum of the squared
+ residuals of ``f(xdata, *popt) - ydata`` is minimized.
+ pcov : 2-D array
+ The estimated approximate covariance of popt. The diagonals provide
+ the variance of the parameter estimate. To compute one standard
+ deviation errors on the parameters, use
+ ``perr = np.sqrt(np.diag(pcov))``. Note that the relationship between
+ `cov` and parameter error estimates is derived based on a linear
+ approximation to the model function around the optimum [1]_.
+ When this approximation becomes inaccurate, `cov` may not provide an
+ accurate measure of uncertainty.
+
+ How the `sigma` parameter affects the estimated covariance
+ depends on `absolute_sigma` argument, as described above.
+
+ If the Jacobian matrix at the solution doesn't have a full rank, then
+ 'lm' method returns a matrix filled with ``np.inf``, on the other hand
+ 'trf' and 'dogbox' methods use Moore-Penrose pseudoinverse to compute
+ the covariance matrix. Covariance matrices with large condition numbers
+ (e.g. computed with `numpy.linalg.cond`) may indicate that results are
+ unreliable.
+ infodict : dict (returned only if `full_output` is True)
+ a dictionary of optional outputs with the keys:
+
+ ``nfev``
+ The number of function calls. Methods 'trf' and 'dogbox' do not
+ count function calls for numerical Jacobian approximation,
+ as opposed to 'lm' method.
+ ``fvec``
+ The residual values evaluated at the solution, for a 1-D `sigma`
+ this is ``(f(x, *popt) - ydata)/sigma``.
+ ``fjac``
+ A permutation of the R matrix of a QR
+ factorization of the final approximate
+ Jacobian matrix, stored column wise.
+ Together with ipvt, the covariance of the
+ estimate can be approximated.
+ Method 'lm' only provides this information.
+ ``ipvt``
+ An integer array of length N which defines
+ a permutation matrix, p, such that
+ fjac*p = q*r, where r is upper triangular
+ with diagonal elements of nonincreasing
+ magnitude. Column j of p is column ipvt(j)
+ of the identity matrix.
+ Method 'lm' only provides this information.
+ ``qtf``
+ The vector (transpose(q) * fvec).
+ Method 'lm' only provides this information.
+
+ .. versionadded:: 1.9
+ mesg : str (returned only if `full_output` is True)
+ A string message giving information about the solution.
+
+ .. versionadded:: 1.9
+ ier : int (returned only if `full_output` is True)
+ An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
+ found. Otherwise, the solution was not found. In either case, the
+ optional output variable `mesg` gives more information.
+
+ .. versionadded:: 1.9
+
+ Raises
+ ------
+ ValueError
+ if either `ydata` or `xdata` contain NaNs, or if incompatible options
+ are used.
+
+ RuntimeError
+ if the least-squares minimization fails.
+
+ TypeError
+ if the number of data points is fewer than the number of parameters
+
+ OptimizeWarning
+ if covariance of the parameters can not be estimated.
+
+ See Also
+ --------
+ least_squares : Minimize the sum of squares of nonlinear functions.
+ scipy.stats.linregress : Calculate a linear least squares regression for
+ two sets of measurements.
+
+ Notes
+ -----
+ Users should ensure that inputs `xdata`, `ydata`, and the output of `f`
+ are ``float64``, or else the optimization may return incorrect results.
+
+ With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm
+ through `leastsq`. Note that this algorithm can only deal with
+ unconstrained problems.
+
+ Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to
+ the docstring of `least_squares` for more information.
+
+ Parameters to be fitted must have similar scale. Differences of multiple
+ orders of magnitude can lead to incorrect results. For the 'trf' and
+ 'dogbox' methods, the `x_scale` keyword argument can be used to scale
+ the parameters.
+
+ `curve_fit` is for local optimization of parameters to minimize the sum of squares
+ of residuals. For global optimization, other choices of objective function, and
+ other advanced features, consider using SciPy's :ref:`tutorial_optimize_global`
+ tools or the `LMFIT `_ package.
+
+ References
+ ----------
+ .. [1] K. Vugrin et al. Confidence region estimation techniques for nonlinear
+ regression in groundwater flow: Three case studies. Water Resources
+ Research, Vol. 43, W03423, :doi:`10.1029/2005WR004804`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.optimize import curve_fit
+
+ >>> def func(x, a, b, c):
+ ... return a * np.exp(-b * x) + c
+
+ Define the data to be fit with some noise:
+
+ >>> xdata = np.linspace(0, 4, 50)
+ >>> y = func(xdata, 2.5, 1.3, 0.5)
+ >>> rng = np.random.default_rng()
+ >>> y_noise = 0.2 * rng.normal(size=xdata.size)
+ >>> ydata = y + y_noise
+ >>> plt.plot(xdata, ydata, 'b-', label='data')
+
+ Fit for the parameters a, b, c of the function `func`:
+
+ >>> popt, pcov = curve_fit(func, xdata, ydata)
+ >>> popt
+ array([2.56274217, 1.37268521, 0.47427475])
+ >>> plt.plot(xdata, func(xdata, *popt), 'r-',
+ ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
+
+ Constrain the optimization to the region of ``0 <= a <= 3``,
+ ``0 <= b <= 1`` and ``0 <= c <= 0.5``:
+
+ >>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
+ >>> popt
+ array([2.43736712, 1. , 0.34463856])
+ >>> plt.plot(xdata, func(xdata, *popt), 'g--',
+ ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
+
+ >>> plt.xlabel('x')
+ >>> plt.ylabel('y')
+ >>> plt.legend()
+ >>> plt.show()
+
+ For reliable results, the model `func` should not be overparametrized;
+ redundant parameters can cause unreliable covariance matrices and, in some
+ cases, poorer quality fits. As a quick check of whether the model may be
+ overparameterized, calculate the condition number of the covariance matrix:
+
+ >>> np.linalg.cond(pcov)
+ 34.571092161547405 # may vary
+
+ The value is small, so it does not raise much concern. If, however, we were
+ to add a fourth parameter ``d`` to `func` with the same effect as ``a``:
+
+ >>> def func2(x, a, b, c, d):
+ ... return a * d * np.exp(-b * x) + c # a and d are redundant
+ >>> popt, pcov = curve_fit(func2, xdata, ydata)
+ >>> np.linalg.cond(pcov)
+ 1.13250718925596e+32 # may vary
+
+ Such a large value is cause for concern. The diagonal elements of the
+ covariance matrix, which is related to uncertainty of the fit, gives more
+ information:
+
+ >>> np.diag(pcov)
+ array([1.48814742e+29, 3.78596560e-02, 5.39253738e-03, 2.76417220e+28]) # may vary
+
+ Note that the first and last terms are much larger than the other elements,
+ suggesting that the optimal values of these parameters are ambiguous and
+ that only one of these parameters is needed in the model.
+
+ If the optimal parameters of `f` differ by multiple orders of magnitude, the
+ resulting fit can be inaccurate. Sometimes, `curve_fit` can fail to find any
+ results:
+
+ >>> ydata = func(xdata, 500000, 0.01, 15)
+ >>> try:
+ ... popt, pcov = curve_fit(func, xdata, ydata, method = 'trf')
+ ... except RuntimeError as e:
+ ... print(e)
+ Optimal parameters not found: The maximum number of function evaluations is
+ exceeded.
+
+ If parameter scale is roughly known beforehand, it can be defined in
+ `x_scale` argument:
+
+ >>> popt, pcov = curve_fit(func, xdata, ydata, method = 'trf',
+ ... x_scale = [1000, 1, 1])
+ >>> popt
+ array([5.00000000e+05, 1.00000000e-02, 1.49999999e+01])
+ """
+ if p0 is None:
+ # determine number of parameters by inspecting the function
+ sig = _getfullargspec(f)
+ args = sig.args
+ if len(args) < 2:
+ raise ValueError("Unable to determine number of fit parameters.")
+ n = len(args) - 1
+ else:
+ p0 = np.atleast_1d(p0)
+ n = p0.size
+
+ if isinstance(bounds, Bounds):
+ lb, ub = bounds.lb, bounds.ub
+ else:
+ lb, ub = prepare_bounds(bounds, n)
+ if p0 is None:
+ p0 = _initialize_feasible(lb, ub)
+
+ bounded_problem = np.any((lb > -np.inf) | (ub < np.inf))
+ if method is None:
+ if bounded_problem:
+ method = 'trf'
+ else:
+ method = 'lm'
+
+ if method == 'lm' and bounded_problem:
+ raise ValueError("Method 'lm' only works for unconstrained problems. "
+ "Use 'trf' or 'dogbox' instead.")
+
+ if check_finite is None:
+ check_finite = True if nan_policy is None else False
+
+ # optimization may produce garbage for float32 inputs, cast them to float64
+ if check_finite:
+ ydata = np.asarray_chkfinite(ydata, float)
+ else:
+ ydata = np.asarray(ydata, float)
+
+ if isinstance(xdata, list | tuple | np.ndarray):
+ # `xdata` is passed straight to the user-defined `f`, so allow
+ # non-array_like `xdata`.
+ if check_finite:
+ xdata = np.asarray_chkfinite(xdata, float)
+ else:
+ xdata = np.asarray(xdata, float)
+
+ if ydata.size == 0:
+ raise ValueError("`ydata` must not be empty!")
+
+ # nan handling is needed only if check_finite is False because if True,
+ # the x-y data are already checked, and they don't contain nans.
+ if not check_finite and nan_policy is not None:
+ if nan_policy == "propagate":
+ msg = "`nan_policy='propagate'` is not supported by this function."
+ raise ValueError(msg)
+ if nan_policy not in ("raise", "omit"):
+ # Override error message raised by _contains_nan
+ msg = "nan_policy must be one of {None, 'raise', 'omit'}"
+ raise ValueError(msg)
+
+ x_contains_nan = _contains_nan(xdata, nan_policy)
+ y_contains_nan = _contains_nan(ydata, nan_policy)
+
+ if (x_contains_nan or y_contains_nan) and nan_policy == 'omit':
+ # ignore NaNs for N dimensional arrays
+ has_nan = np.isnan(xdata)
+ has_nan = has_nan.any(axis=tuple(range(has_nan.ndim-1)))
+ has_nan |= np.isnan(ydata)
+
+ xdata = xdata[..., ~has_nan]
+ ydata = ydata[~has_nan]
+
+ # Also omit the corresponding entries from sigma
+ if sigma is not None:
+ sigma = np.asarray(sigma)
+ if sigma.ndim == 1:
+ sigma = sigma[~has_nan]
+ elif sigma.ndim == 2:
+ sigma = sigma[~has_nan, :]
+ sigma = sigma[:, ~has_nan]
+
+ # Determine type of sigma
+ if sigma is not None:
+ sigma = np.asarray(sigma)
+
+ # if 1-D or a scalar, sigma are errors, define transform = 1/sigma
+ if sigma.size == 1 or sigma.shape == (ydata.size,):
+ transform = 1.0 / sigma
+ # if 2-D, sigma is the covariance matrix,
+ # define transform = L such that L L^T = C
+ elif sigma.shape == (ydata.size, ydata.size):
+ try:
+ # scipy.linalg.cholesky requires lower=True to return L L^T = A
+ transform = cholesky(sigma, lower=True)
+ except LinAlgError as e:
+ raise ValueError("`sigma` must be positive definite.") from e
+ else:
+ raise ValueError("`sigma` has incorrect shape.")
+ else:
+ transform = None
+
+ func = _lightweight_memoizer(_wrap_func(f, xdata, ydata, transform))
+
+ if callable(jac):
+ jac = _lightweight_memoizer(_wrap_jac(jac, xdata, transform))
+ elif jac is None and method != 'lm':
+ jac = '2-point'
+
+ if 'args' in kwargs:
+ # The specification for the model function `f` does not support
+ # additional arguments. Refer to the `curve_fit` docstring for
+ # acceptable call signatures of `f`.
+ raise ValueError("'args' is not a supported keyword argument.")
+
+ if method == 'lm':
+ # if ydata.size == 1, this might be used for broadcast.
+ if ydata.size != 1 and n > ydata.size:
+ raise TypeError(f"The number of func parameters={n} must not"
+ f" exceed the number of data points={ydata.size}")
+ res = leastsq(func, p0, Dfun=jac, full_output=True, **kwargs)
+ popt, pcov, infodict, errmsg, ier = res
+ ysize = len(infodict['fvec'])
+ cost = np.sum(infodict['fvec'] ** 2)
+ if ier not in [1, 2, 3, 4]:
+ raise RuntimeError("Optimal parameters not found: " + errmsg)
+ else:
+ # Rename maxfev (leastsq) to max_nfev (least_squares), if specified.
+ if 'max_nfev' not in kwargs:
+ kwargs['max_nfev'] = kwargs.pop('maxfev', None)
+
+ res = least_squares(func, p0, jac=jac, bounds=bounds, method=method,
+ **kwargs)
+
+ if not res.success:
+ raise RuntimeError("Optimal parameters not found: " + res.message)
+
+ infodict = dict(nfev=res.nfev, fvec=res.fun)
+ ier = res.status
+ errmsg = res.message
+
+ ysize = len(res.fun)
+ cost = 2 * res.cost # res.cost is half sum of squares!
+ popt = res.x
+
+ # Do Moore-Penrose inverse discarding zero singular values.
+ _, s, VT = svd(res.jac, full_matrices=False)
+ threshold = np.finfo(float).eps * max(res.jac.shape) * s[0]
+ s = s[s > threshold]
+ VT = VT[:s.size]
+ pcov = np.dot(VT.T / s**2, VT)
+
+ warn_cov = False
+ if pcov is None or np.isnan(pcov).any():
+ # indeterminate covariance
+ pcov = zeros((len(popt), len(popt)), dtype=float)
+ pcov.fill(inf)
+ warn_cov = True
+ elif not absolute_sigma:
+ if ysize > p0.size:
+ s_sq = cost / (ysize - p0.size)
+ pcov = pcov * s_sq
+ else:
+ pcov.fill(inf)
+ warn_cov = True
+
+ if warn_cov:
+ warnings.warn('Covariance of the parameters could not be estimated',
+ category=OptimizeWarning, stacklevel=2)
+
+ if full_output:
+ return popt, pcov, infodict, errmsg, ier
+ else:
+ return popt, pcov
+
+
+def check_gradient(fcn, Dfcn, x0, args=(), col_deriv=False):
+ """Perform a simple check on the gradient for correctness.
+
+ """
+
+ x = atleast_1d(x0)
+ n = len(x)
+ x = x.reshape((n,))
+ fvec = atleast_1d(fcn(x, *args))
+ m = len(fvec)
+ fvec = fvec.reshape((m,))
+ ldfjac = m
+ fjac = atleast_1d(Dfcn(x, *args))
+ fjac = fjac.reshape((m, n))
+ if not col_deriv:
+ fjac = transpose(fjac)
+
+ xp = zeros((n,), float)
+ err = zeros((m,), float)
+ fvecp = None
+ _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 1, err)
+
+ fvecp = atleast_1d(fcn(xp, *args))
+ fvecp = fvecp.reshape((m,))
+ _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 2, err)
+
+ good = (prod(greater(err, 0.5), axis=0))
+
+ return (good, err)
+
+
+def _del2(p0, p1, d):
+ return p0 - np.square(p1 - p0) / d
+
+
+def _relerr(actual, desired):
+ return (actual - desired) / desired
+
+
+def _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel):
+ p0 = x0
+ for i in range(maxiter):
+ p1 = func(p0, *args)
+ if use_accel:
+ p2 = func(p1, *args)
+ d = p2 - 2.0 * p1 + p0
+ p = xpx.apply_where(d != 0, (p0, p1, d), _del2, fill_value=p2)
+ else:
+ p = p1
+ relerr = xpx.apply_where(p0 != 0, (p, p0), _relerr, fill_value=p)
+ if np.all(np.abs(relerr) < xtol):
+ return p
+ p0 = p
+ msg = f"Failed to converge after {maxiter} iterations, value is {p}"
+ raise RuntimeError(msg)
+
+
+def fixed_point(func, x0, args=(), xtol=1e-8, maxiter=500, method='del2'):
+ """
+ Find a fixed point of the function.
+
+ Given a function of one or more variables and a starting point, find a
+ fixed point of the function: i.e., where ``func(xf) == xf``.
+
+ Parameters
+ ----------
+ func : function
+ Function to evaluate.
+ x0 : array_like
+ Guess of fixed point of function.
+ args : tuple, optional
+ Extra arguments to `func`.
+ xtol : float, optional
+ Convergence tolerance, defaults to 1e-08.
+ maxiter : int, optional
+ Maximum number of iterations, defaults to 500.
+ method : {"del2", "iteration"}, optional
+ Method of finding the fixed-point, defaults to "del2",
+ which uses Steffensen's Method with Aitken's ``Del^2``
+ convergence acceleration [1]_. The "iteration" method simply iterates
+ the function until convergence is detected, without attempting to
+ accelerate the convergence.
+
+ Returns
+ -------
+ xf : array
+ Fixed point of function.
+
+ References
+ ----------
+ .. [1] Burden, Faires, "Numerical Analysis", 5th edition, pg. 80
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import optimize
+ >>> def func(x, c1, c2):
+ ... return np.sqrt(c1/(x+c2))
+ >>> c1 = np.array([10,12.])
+ >>> c2 = np.array([3, 5.])
+ >>> optimize.fixed_point(func, [1.2, 1.3], args=(c1,c2))
+ array([ 1.4920333 , 1.37228132])
+
+ """
+ use_accel = {'del2': True, 'iteration': False}[method]
+ x0 = _asarray_validated(x0, as_inexact=True)
+ return _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..eb7d2044dd85526378a3a4237e2c9d058f06a1ed
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:97ff75823ff461f05f7fe0d696dfd5dc27f4f06beec1f9545e03cc135788acea
+size 147560
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_nnls.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..81cf703a72587eeb83ac498c4fa18db8402c7109
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_nnls.py
@@ -0,0 +1,92 @@
+import numpy as np
+from ._slsqplib import nnls as _nnls
+
+
+__all__ = ['nnls']
+
+
+def nnls(A, b, *, maxiter=None):
+ """
+ Solve ``argmin_x || Ax - b ||_2^2`` for ``x>=0``.
+
+ This problem, often called as NonNegative Least Squares, is a convex
+ optimization problem with convex constraints. It typically arises when
+ the ``x`` models quantities for which only nonnegative values are
+ attainable; weight of ingredients, component costs and so on.
+
+ Parameters
+ ----------
+ A : (m, n) ndarray
+ Coefficient array
+ b : (m,) ndarray, float
+ Right-hand side vector.
+ maxiter : int, optional
+ Maximum number of iterations, optional. Default value is ``3 * n``.
+
+ Returns
+ -------
+ x : ndarray
+ Solution vector.
+ rnorm : float
+ The 2-norm of the residual, ``|| Ax-b ||_2``.
+
+ See Also
+ --------
+ lsq_linear : Linear least squares with bounds on the variables
+
+ Notes
+ -----
+ The code is based on the classical algorithm of [1]_. It utilizes an active
+ set method and solves the KKT (Karush-Kuhn-Tucker) conditions for the
+ non-negative least squares problem.
+
+ References
+ ----------
+ .. [1] : Lawson C., Hanson R.J., "Solving Least Squares Problems", SIAM,
+ 1995, :doi:`10.1137/1.9781611971217`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import nnls
+ ...
+ >>> A = np.array([[1, 0], [1, 0], [0, 1]])
+ >>> b = np.array([2, 1, 1])
+ >>> nnls(A, b)
+ (array([1.5, 1. ]), 0.7071067811865475)
+
+ >>> b = np.array([-1, -1, -1])
+ >>> nnls(A, b)
+ (array([0., 0.]), 1.7320508075688772)
+
+ """
+
+ A = np.asarray_chkfinite(A, dtype=np.float64, order='C')
+ b = np.asarray_chkfinite(b, dtype=np.float64)
+
+ if len(A.shape) != 2:
+ raise ValueError(f"Expected a 2D array, but the shape of A is {A.shape}")
+
+ if (b.ndim > 2) or ((b.ndim == 2) and (b.shape[1] != 1)):
+ raise ValueError("Expected a 1D array,(or 2D with one column), but the,"
+ f" shape of b is {b.shape}")
+ elif (b.ndim == 2) and (b.shape[1] == 1):
+ b = b.ravel()
+
+ m, n = A.shape
+
+ if m != b.shape[0]:
+ raise ValueError(
+ "Incompatible dimensions. The first dimension of " +
+ f"A is {m}, while the shape of b is {(b.shape[0], )}")
+
+ if n == 0:
+ return (np.empty(0), np.linalg.norm(b))
+
+ if not maxiter:
+ maxiter = 3*n
+ x, rnorm, info = _nnls(A, b, maxiter)
+ if info == 3:
+ raise RuntimeError("Maximum number of iterations reached.")
+
+ return x, rnorm
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_nonlin.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9a6aedb15a002d50a31ccb502a400be12bfc1a8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_nonlin.py
@@ -0,0 +1,1657 @@
+# Copyright (C) 2009, Pauli Virtanen
+# Distributed under the same license as SciPy.
+
+import inspect
+import os
+import sys
+import warnings
+
+import numpy as np
+from numpy import asarray, dot, vdot
+
+from scipy.linalg import norm, solve, inv, qr, svd, LinAlgError
+import scipy.sparse.linalg
+import scipy.sparse
+from scipy.linalg import get_blas_funcs
+from scipy._lib._util import copy_if_needed, _dedent_for_py313
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+from ._linesearch import scalar_search_wolfe1, scalar_search_armijo
+from inspect import signature
+from difflib import get_close_matches
+from types import GenericAlias
+
+
+__all__ = [
+ 'broyden1', 'broyden2', 'anderson', 'linearmixing',
+ 'diagbroyden', 'excitingmixing', 'newton_krylov',
+ 'BroydenFirst', 'KrylovJacobian', 'InverseJacobian', 'NoConvergence']
+
+#------------------------------------------------------------------------------
+# Utility functions
+#------------------------------------------------------------------------------
+
+
+class NoConvergence(Exception):
+ """Exception raised when nonlinear solver fails to converge within the specified
+ `maxiter`."""
+ pass
+
+
+def maxnorm(x):
+ return np.absolute(x).max()
+
+
+def _as_inexact(x):
+ """Return `x` as an array, of either floats or complex floats"""
+ x = asarray(x)
+ if not np.issubdtype(x.dtype, np.inexact):
+ return asarray(x, dtype=np.float64)
+ return x
+
+
+def _array_like(x, x0):
+ """Return ndarray `x` as same array subclass and shape as `x0`"""
+ x = np.reshape(x, np.shape(x0))
+ wrap = getattr(x0, '__array_wrap__', x.__array_wrap__)
+ return wrap(x)
+
+
+def _safe_norm(v):
+ if not np.isfinite(v).all():
+ return np.array(np.inf)
+ return norm(v)
+
+#------------------------------------------------------------------------------
+# Generic nonlinear solver machinery
+#------------------------------------------------------------------------------
+
+
+_doc_parts = dict(
+ params_basic=_dedent_for_py313("""
+ F : function(x) -> f
+ Function whose root to find; should take and return an array-like
+ object.
+ xin : array_like
+ Initial guess for the solution
+ """).strip(),
+ params_extra=_dedent_for_py313("""
+ iter : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ verbose : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make. If more are needed to
+ meet convergence, `NoConvergence` is raised.
+ f_tol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ f_rtol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ x_tol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ x_rtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in the
+ direction given by the Jacobian approximation. Defaults to 'armijo'.
+ callback : function, optional
+ Optional callback function. It is called on every iteration as
+ ``callback(x, f)`` where `x` is the current solution and `f`
+ the corresponding residual.
+
+ Returns
+ -------
+ sol : ndarray
+ An array (of similar array type as `x0`) containing the final solution.
+
+ Raises
+ ------
+ NoConvergence
+ When a solution was not found.
+
+ """).strip()
+)
+
+
+def _set_doc(obj):
+ if obj.__doc__:
+ obj.__doc__ = obj.__doc__ % _doc_parts
+
+
+def _set_doc_class(obj):
+ if obj.__doc__:
+ doc_parts = _doc_parts.copy()
+ doc_parts["params_basic"] = ""
+ doc_parts["params_extra"] = ""
+ obj.__doc__ = obj.__doc__ % doc_parts
+
+
+def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False,
+ maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
+ tol_norm=None, line_search='armijo', callback=None,
+ full_output=False, raise_exception=True):
+ """
+ Find a root of a function, in a way suitable for large-scale problems.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ jacobian : Jacobian
+ A Jacobian approximation: `Jacobian` object or something that
+ `asjacobian` can transform to one. Alternatively, a string specifying
+ which of the builtin Jacobian approximations to use:
+
+ krylov, broyden1, broyden2, anderson
+ diagbroyden, linearmixing, excitingmixing
+
+ %(params_extra)s
+ full_output : bool
+ If true, returns a dictionary `info` containing convergence
+ information.
+ raise_exception : bool
+ If True, a `NoConvergence` exception is raise if no solution is found.
+
+ See Also
+ --------
+ asjacobian, Jacobian
+
+ Notes
+ -----
+ This algorithm implements the inexact Newton method, with
+ backtracking or full line searches. Several Jacobian
+ approximations are available, including Krylov and Quasi-Newton
+ methods.
+
+ References
+ ----------
+ .. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear
+ Equations\". Society for Industrial and Applied Mathematics. (1995)
+ https://archive.siam.org/books/kelley/fr16/
+
+ """
+ # Can't use default parameters because it's being explicitly passed as None
+ # from the calling function, so we need to set it here.
+ tol_norm = maxnorm if tol_norm is None else tol_norm
+ condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol,
+ x_tol=x_tol, x_rtol=x_rtol,
+ iter=iter, norm=tol_norm)
+
+ x0 = _as_inexact(x0)
+ def func(z):
+ return _as_inexact(F(_array_like(z, x0))).flatten()
+ x = x0.flatten()
+
+ dx = np.full_like(x, np.inf)
+ Fx = func(x)
+ Fx_norm = norm(Fx)
+
+ jacobian = asjacobian(jacobian)
+ jacobian.setup(x.copy(), Fx, func)
+
+ if maxiter is None:
+ if iter is not None:
+ maxiter = iter + 1
+ else:
+ maxiter = 100*(x.size+1)
+
+ if line_search is True:
+ line_search = 'armijo'
+ elif line_search is False:
+ line_search = None
+
+ if line_search not in (None, 'armijo', 'wolfe'):
+ raise ValueError("Invalid line search")
+
+ # Solver tolerance selection
+ gamma = 0.9
+ eta_max = 0.9999
+ eta_treshold = 0.1
+ eta = 1e-3
+
+ for n in range(maxiter):
+ status = condition.check(Fx, x, dx)
+ if status:
+ break
+
+ # The tolerance, as computed for scipy.sparse.linalg.* routines
+ tol = min(eta, eta*Fx_norm)
+ dx = -jacobian.solve(Fx, tol=tol)
+
+ if norm(dx) == 0:
+ raise ValueError("Jacobian inversion yielded zero vector. "
+ "This indicates a bug in the Jacobian "
+ "approximation.")
+
+ # Line search, or Newton step
+ if line_search:
+ s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx,
+ line_search)
+ else:
+ s = 1.0
+ x = x + dx
+ Fx = func(x)
+ Fx_norm_new = norm(Fx)
+
+ jacobian.update(x.copy(), Fx)
+
+ if callback:
+ callback(x, Fx)
+
+ # Adjust forcing parameters for inexact methods
+ eta_A = gamma * Fx_norm_new**2 / Fx_norm**2
+ if gamma * eta**2 < eta_treshold:
+ eta = min(eta_max, eta_A)
+ else:
+ eta = min(eta_max, max(eta_A, gamma*eta**2))
+
+ Fx_norm = Fx_norm_new
+
+ # Print status
+ if verbose:
+ sys.stdout.write(f"{n}: |F(x)| = {tol_norm(Fx):g}; step {s:g}\n")
+ sys.stdout.flush()
+ else:
+ if raise_exception:
+ raise NoConvergence(_array_like(x, x0))
+ else:
+ status = 2
+
+ if full_output:
+ info = {'nit': condition.iteration,
+ 'fun': Fx,
+ 'status': status,
+ 'success': status == 1,
+ 'message': {1: 'A solution was found at the specified '
+ 'tolerance.',
+ 2: 'The maximum number of iterations allowed '
+ 'has been reached.'
+ }[status]
+ }
+ return _array_like(x, x0), info
+ else:
+ return _array_like(x, x0)
+
+
+_set_doc(nonlin_solve)
+
+
+def _nonlin_line_search(func, x, Fx, dx, search_type='armijo', rdiff=1e-8,
+ smin=1e-2):
+ tmp_s = [0]
+ tmp_Fx = [Fx]
+ tmp_phi = [norm(Fx)**2]
+ s_norm = norm(x) / norm(dx)
+
+ def phi(s, store=True):
+ if s == tmp_s[0]:
+ return tmp_phi[0]
+ xt = x + s*dx
+ v = func(xt)
+ p = _safe_norm(v)**2
+ if store:
+ tmp_s[0] = s
+ tmp_phi[0] = p
+ tmp_Fx[0] = v
+ return p
+
+ def derphi(s):
+ ds = (abs(s) + s_norm + 1) * rdiff
+ return (phi(s+ds, store=False) - phi(s)) / ds
+
+ if search_type == 'wolfe':
+ s, phi1, phi0 = scalar_search_wolfe1(phi, derphi, tmp_phi[0],
+ xtol=1e-2, amin=smin)
+ elif search_type == 'armijo':
+ s, phi1 = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0],
+ amin=smin)
+
+ if s is None:
+ # XXX: No suitable step length found. Take the full Newton step,
+ # and hope for the best.
+ s = 1.0
+
+ x = x + s*dx
+ if s == tmp_s[0]:
+ Fx = tmp_Fx[0]
+ else:
+ Fx = func(x)
+ Fx_norm = norm(Fx)
+
+ return s, x, Fx, Fx_norm
+
+
+class TerminationCondition:
+ """
+ Termination condition for an iteration. It is terminated if
+
+ - |F| < f_rtol*|F_0|, AND
+ - |F| < f_tol
+
+ AND
+
+ - |dx| < x_rtol*|x|, AND
+ - |dx| < x_tol
+
+ """
+ def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
+ iter=None, norm=maxnorm):
+
+ if f_tol is None:
+ f_tol = np.finfo(np.float64).eps ** (1./3)
+ if f_rtol is None:
+ f_rtol = np.inf
+ if x_tol is None:
+ x_tol = np.inf
+ if x_rtol is None:
+ x_rtol = np.inf
+
+ self.x_tol = x_tol
+ self.x_rtol = x_rtol
+ self.f_tol = f_tol
+ self.f_rtol = f_rtol
+
+ self.norm = norm
+
+ self.iter = iter
+
+ self.f0_norm = None
+ self.iteration = 0
+
+ def check(self, f, x, dx):
+ self.iteration += 1
+ f_norm = self.norm(f)
+ x_norm = self.norm(x)
+ dx_norm = self.norm(dx)
+
+ if self.f0_norm is None:
+ self.f0_norm = f_norm
+
+ if f_norm == 0:
+ return 1
+
+ if self.iter is not None:
+ # backwards compatibility with SciPy 0.6.0
+ return 2 * (self.iteration > self.iter)
+
+ # NB: condition must succeed for rtol=inf even if norm == 0
+ return int((f_norm <= self.f_tol
+ and f_norm/self.f_rtol <= self.f0_norm)
+ and (dx_norm <= self.x_tol
+ and dx_norm/self.x_rtol <= x_norm))
+
+
+#------------------------------------------------------------------------------
+# Generic Jacobian approximation
+#------------------------------------------------------------------------------
+
+class Jacobian:
+ """
+ Common interface for Jacobians or Jacobian approximations.
+
+ The optional methods come useful when implementing trust region
+ etc., algorithms that often require evaluating transposes of the
+ Jacobian.
+
+ Methods
+ -------
+ solve
+ Returns J^-1 * v
+ update
+ Updates Jacobian to point `x` (where the function has residual `Fx`)
+
+ matvec : optional
+ Returns J * v
+ rmatvec : optional
+ Returns A^H * v
+ rsolve : optional
+ Returns A^-H * v
+ matmat : optional
+ Returns A * V, where V is a dense matrix with dimensions (N,K).
+ todense : optional
+ Form the dense Jacobian matrix. Necessary for dense trust region
+ algorithms, and useful for testing.
+
+ Attributes
+ ----------
+ shape
+ Matrix dimensions (M, N)
+ dtype
+ Data type of the matrix.
+ func : callable, optional
+ Function the Jacobian corresponds to
+
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def __init__(self, **kw):
+ names = ["solve", "update", "matvec", "rmatvec", "rsolve",
+ "matmat", "todense", "shape", "dtype"]
+ for name, value in kw.items():
+ if name not in names:
+ raise ValueError(f"Unknown keyword argument {name}")
+ if value is not None:
+ setattr(self, name, kw[name])
+
+
+ if hasattr(self, "todense"):
+ def __array__(self, dtype=None, copy=None):
+ if dtype is not None:
+ raise ValueError(f"`dtype` must be None, was {dtype}")
+ return self.todense()
+
+ def aspreconditioner(self):
+ return InverseJacobian(self)
+
+ def solve(self, v, /, tol=0):
+ raise NotImplementedError
+
+ def update(self, x, F, /):
+ pass
+
+ def setup(self, x, F, func, /):
+ self.func = func
+ self.shape = (F.size, x.size)
+ self.dtype = F.dtype
+ if self.__class__.setup is Jacobian.setup:
+ # Call on the first point unless overridden
+ self.update(x, F)
+
+
+class InverseJacobian:
+ """
+ A simple wrapper that inverts the Jacobian using the `solve` method.
+
+ .. legacy:: class
+
+ See the newer, more consistent interfaces in :mod:`scipy.optimize`.
+
+ Parameters
+ ----------
+ jacobian : Jacobian
+ The Jacobian to invert.
+
+ Attributes
+ ----------
+ shape
+ Matrix dimensions (M, N)
+ dtype
+ Data type of the matrix.
+
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def __init__(self, jacobian):
+ self.jacobian = jacobian
+ self.matvec = jacobian.solve
+ self.update = jacobian.update
+ if hasattr(jacobian, 'setup'):
+ self.setup = jacobian.setup
+ if hasattr(jacobian, 'rsolve'):
+ self.rmatvec = jacobian.rsolve
+
+ @property
+ def shape(self):
+ return self.jacobian.shape
+
+ @property
+ def dtype(self):
+ return self.jacobian.dtype
+
+
+def asjacobian(J):
+ """
+ Convert given object to one suitable for use as a Jacobian.
+ """
+ spsolve = scipy.sparse.linalg.spsolve
+ if isinstance(J, Jacobian):
+ return J
+ elif inspect.isclass(J) and issubclass(J, Jacobian):
+ return J()
+ elif isinstance(J, np.ndarray):
+ if J.ndim > 2:
+ raise ValueError('array must have rank <= 2')
+ J = np.atleast_2d(np.asarray(J))
+ if J.shape[0] != J.shape[1]:
+ raise ValueError('array must be square')
+
+ return Jacobian(matvec=lambda v: dot(J, v),
+ rmatvec=lambda v: dot(J.conj().T, v),
+ solve=lambda v, tol=0: solve(J, v),
+ rsolve=lambda v, tol=0: solve(J.conj().T, v),
+ dtype=J.dtype, shape=J.shape)
+ elif scipy.sparse.issparse(J):
+ if J.shape[0] != J.shape[1]:
+ raise ValueError('matrix must be square')
+ return Jacobian(matvec=lambda v: J @ v,
+ rmatvec=lambda v: J.conj().T @ v,
+ solve=lambda v, tol=0: spsolve(J, v),
+ rsolve=lambda v, tol=0: spsolve(J.conj().T, v),
+ dtype=J.dtype, shape=J.shape)
+ elif hasattr(J, 'shape') and hasattr(J, 'dtype') and hasattr(J, 'solve'):
+ return Jacobian(matvec=getattr(J, 'matvec'),
+ rmatvec=getattr(J, 'rmatvec'),
+ solve=J.solve,
+ rsolve=getattr(J, 'rsolve'),
+ update=getattr(J, 'update'),
+ setup=getattr(J, 'setup'),
+ dtype=J.dtype,
+ shape=J.shape)
+ elif callable(J):
+ # Assume it's a function J(x) that returns the Jacobian
+ class Jac(Jacobian):
+ def update(self, x, F):
+ self.x = x
+
+ def solve(self, v, tol=0):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return solve(m, v)
+ elif scipy.sparse.issparse(m):
+ return spsolve(m, v)
+ else:
+ raise ValueError("Unknown matrix type")
+
+ def matvec(self, v):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return dot(m, v)
+ elif scipy.sparse.issparse(m):
+ return m @ v
+ else:
+ raise ValueError("Unknown matrix type")
+
+ def rsolve(self, v, tol=0):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return solve(m.conj().T, v)
+ elif scipy.sparse.issparse(m):
+ return spsolve(m.conj().T, v)
+ else:
+ raise ValueError("Unknown matrix type")
+
+ def rmatvec(self, v):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return dot(m.conj().T, v)
+ elif scipy.sparse.issparse(m):
+ return m.conj().T @ v
+ else:
+ raise ValueError("Unknown matrix type")
+ return Jac()
+ elif isinstance(J, str):
+ return dict(broyden1=BroydenFirst,
+ broyden2=BroydenSecond,
+ anderson=Anderson,
+ diagbroyden=DiagBroyden,
+ linearmixing=LinearMixing,
+ excitingmixing=ExcitingMixing,
+ krylov=KrylovJacobian)[J]()
+ else:
+ raise TypeError('Cannot convert object to a Jacobian')
+
+
+#------------------------------------------------------------------------------
+# Broyden
+#------------------------------------------------------------------------------
+
+class GenericBroyden(Jacobian):
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def setup(self, x0, f0, func, /):
+ Jacobian.setup(self, x0, f0, func)
+ self.last_f = f0
+ self.last_x = x0
+
+ if hasattr(self, 'alpha') and self.alpha is None:
+ # Autoscale the initial Jacobian parameter
+ # unless we have already guessed the solution.
+ normf0 = norm(f0)
+ if normf0:
+ self.alpha = 0.5*max(norm(x0), 1) / normf0
+ else:
+ self.alpha = 1.0
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ raise NotImplementedError
+
+ def update(self, x, f):
+ df = f - self.last_f
+ dx = x - self.last_x
+ self._update(x, f, dx, df, norm(dx), norm(df))
+ self.last_f = f
+ self.last_x = x
+
+
+class LowRankMatrix:
+ r"""
+ A matrix represented as
+
+ .. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger
+
+ However, if the rank of the matrix reaches the dimension of the vectors,
+ full matrix representation will be used thereon.
+
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def __init__(self, alpha, n, dtype):
+ self.alpha = alpha
+ self.cs = []
+ self.ds = []
+ self.n = n
+ self.dtype = dtype
+ self.collapsed = None
+
+ @staticmethod
+ def _matvec(v, alpha, cs, ds):
+ axpy, scal, dotc = get_blas_funcs(['axpy', 'scal', 'dotc'],
+ cs[:1] + [v])
+ w = alpha * v
+ for c, d in zip(cs, ds):
+ a = dotc(d, v)
+ w = axpy(c, w, w.size, a)
+ return w
+
+ @staticmethod
+ def _solve(v, alpha, cs, ds):
+ """Evaluate w = M^-1 v"""
+ if len(cs) == 0:
+ return v/alpha
+
+ # (B + C D^H)^-1 = B^-1 - B^-1 C (I + D^H B^-1 C)^-1 D^H B^-1
+
+ axpy, dotc = get_blas_funcs(['axpy', 'dotc'], cs[:1] + [v])
+
+ c0 = cs[0]
+ A = alpha * np.identity(len(cs), dtype=c0.dtype)
+ for i, d in enumerate(ds):
+ for j, c in enumerate(cs):
+ A[i,j] += dotc(d, c)
+
+ q = np.zeros(len(cs), dtype=c0.dtype)
+ for j, d in enumerate(ds):
+ q[j] = dotc(d, v)
+ q /= alpha
+ q = solve(A, q)
+
+ w = v/alpha
+ for c, qc in zip(cs, q):
+ w = axpy(c, w, w.size, -qc)
+
+ return w
+
+ def matvec(self, v):
+ """Evaluate w = M v"""
+ if self.collapsed is not None:
+ return np.dot(self.collapsed, v)
+ return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds)
+
+ def rmatvec(self, v):
+ """Evaluate w = M^H v"""
+ if self.collapsed is not None:
+ return np.dot(self.collapsed.T.conj(), v)
+ return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs)
+
+ def solve(self, v, tol=0):
+ """Evaluate w = M^-1 v"""
+ if self.collapsed is not None:
+ return solve(self.collapsed, v)
+ return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds)
+
+ def rsolve(self, v, tol=0):
+ """Evaluate w = M^-H v"""
+ if self.collapsed is not None:
+ return solve(self.collapsed.T.conj(), v)
+ return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs)
+
+ def append(self, c, d):
+ if self.collapsed is not None:
+ self.collapsed += c[:,None] * d[None,:].conj()
+ return
+
+ self.cs.append(c)
+ self.ds.append(d)
+
+ if len(self.cs) > c.size:
+ self.collapse()
+
+ def __array__(self, dtype=None, copy=None):
+ if dtype is not None:
+ warnings.warn("LowRankMatrix is scipy-internal code, `dtype` "
+ f"should only be None but was {dtype} (not handled)",
+ stacklevel=3)
+ if copy is not None:
+ warnings.warn("LowRankMatrix is scipy-internal code, `copy` "
+ f"should only be None but was {copy} (not handled)",
+ stacklevel=3)
+ if self.collapsed is not None:
+ return self.collapsed
+
+ Gm = self.alpha*np.identity(self.n, dtype=self.dtype)
+ for c, d in zip(self.cs, self.ds):
+ Gm += c[:,None]*d[None,:].conj()
+ return Gm
+
+ def collapse(self):
+ """Collapse the low-rank matrix to a full-rank one."""
+ self.collapsed = np.array(self, copy=copy_if_needed)
+ self.cs = None
+ self.ds = None
+ self.alpha = None
+
+ def restart_reduce(self, rank):
+ """
+ Reduce the rank of the matrix by dropping all vectors.
+ """
+ if self.collapsed is not None:
+ return
+ assert rank > 0
+ if len(self.cs) > rank:
+ del self.cs[:]
+ del self.ds[:]
+
+ def simple_reduce(self, rank):
+ """
+ Reduce the rank of the matrix by dropping oldest vectors.
+ """
+ if self.collapsed is not None:
+ return
+ assert rank > 0
+ while len(self.cs) > rank:
+ del self.cs[0]
+ del self.ds[0]
+
+ def svd_reduce(self, max_rank, to_retain=None):
+ """
+ Reduce the rank of the matrix by retaining some SVD components.
+
+ This corresponds to the \"Broyden Rank Reduction Inverse\"
+ algorithm described in [1]_.
+
+ Note that the SVD decomposition can be done by solving only a
+ problem whose size is the effective rank of this matrix, which
+ is viable even for large problems.
+
+ Parameters
+ ----------
+ max_rank : int
+ Maximum rank of this matrix after reduction.
+ to_retain : int, optional
+ Number of SVD components to retain when reduction is done
+ (ie. rank > max_rank). Default is ``max_rank - 2``.
+
+ References
+ ----------
+ .. [1] B.A. van der Rotten, PhD thesis,
+ \"A limited memory Broyden method to solve high-dimensional
+ systems of nonlinear equations\". Mathematisch Instituut,
+ Universiteit Leiden, The Netherlands (2003).
+
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
+
+ """
+ if self.collapsed is not None:
+ return
+
+ p = max_rank
+ if to_retain is not None:
+ q = to_retain
+ else:
+ q = p - 2
+
+ if self.cs:
+ p = min(p, len(self.cs[0]))
+ q = max(0, min(q, p-1))
+
+ m = len(self.cs)
+ if m < p:
+ # nothing to do
+ return
+
+ C = np.array(self.cs).T
+ D = np.array(self.ds).T
+
+ D, R = qr(D, mode='economic')
+ C = dot(C, R.T.conj())
+
+ U, S, WH = svd(C, full_matrices=False)
+
+ C = dot(C, inv(WH))
+ D = dot(D, WH.T.conj())
+
+ for k in range(q):
+ self.cs[k] = C[:,k].copy()
+ self.ds[k] = D[:,k].copy()
+
+ del self.cs[q:]
+ del self.ds[q:]
+
+
+_doc_parts['broyden_params'] = _dedent_for_py313("""
+ alpha : float, optional
+ Initial guess for the Jacobian is ``(-1/alpha)``.
+ reduction_method : str or tuple, optional
+ Method used in ensuring that the rank of the Broyden matrix
+ stays low. Can either be a string giving the name of the method,
+ or a tuple of the form ``(method, param1, param2, ...)``
+ that gives the name of the method and values for additional parameters.
+
+ Methods available:
+
+ - ``restart``: drop all matrix columns. Has no extra parameters.
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
+ - ``svd``: keep only the most significant SVD components.
+ Takes an extra parameter, ``to_retain``, which determines the
+ number of SVD components to retain when rank reduction is done.
+ Default is ``max_rank - 2``.
+
+ max_rank : int, optional
+ Maximum rank for the Broyden matrix.
+ Default is infinity (i.e., no rank reduction).
+ """).strip()
+
+
+class BroydenFirst(GenericBroyden):
+ """
+ Find a root of a function, using Broyden's first Jacobian approximation.
+
+ This method is also known as "Broyden's good method".
+
+ Parameters
+ ----------
+ %(params_basic)s
+ %(broyden_params)s
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='broyden1'`` in particular.
+
+ Notes
+ -----
+ This algorithm implements the inverse Jacobian Quasi-Newton update
+
+ .. math:: H_+ = H + (dx - H df) dx^\\dagger H / ( dx^\\dagger H df)
+
+ which corresponds to Broyden's first Jacobian update
+
+ .. math:: J_+ = J + (df - J dx) dx^\\dagger / dx^\\dagger dx
+
+
+ References
+ ----------
+ .. [1] B.A. van der Rotten, PhD thesis,
+ "A limited memory Broyden method to solve high-dimensional
+ systems of nonlinear equations". Mathematisch Instituut,
+ Universiteit Leiden, The Netherlands (2003).
+ https://math.leidenuniv.nl/scripties/Rotten.pdf
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.broyden1(fun, [0, 0])
+ >>> sol
+ array([0.84116396, 0.15883641])
+
+ """
+
+ def __init__(self, alpha=None, reduction_method='restart', max_rank=None):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+ self.Gm = None
+
+ if max_rank is None:
+ max_rank = np.inf
+ self.max_rank = max_rank
+
+ if isinstance(reduction_method, str):
+ reduce_params = ()
+ else:
+ reduce_params = reduction_method[1:]
+ reduction_method = reduction_method[0]
+ reduce_params = (max_rank - 1,) + reduce_params
+
+ if reduction_method == 'svd':
+ self._reduce = lambda: self.Gm.svd_reduce(*reduce_params)
+ elif reduction_method == 'simple':
+ self._reduce = lambda: self.Gm.simple_reduce(*reduce_params)
+ elif reduction_method == 'restart':
+ self._reduce = lambda: self.Gm.restart_reduce(*reduce_params)
+ else:
+ raise ValueError(f"Unknown rank reduction method '{reduction_method}'")
+
+ def setup(self, x, F, func):
+ GenericBroyden.setup(self, x, F, func)
+ self.Gm = LowRankMatrix(-self.alpha, self.shape[0], self.dtype)
+
+ def todense(self):
+ return inv(self.Gm)
+
+ def solve(self, f, tol=0):
+ r = self.Gm.matvec(f)
+ if not np.isfinite(r).all():
+ # singular; reset the Jacobian approximation
+ self.setup(self.last_x, self.last_f, self.func)
+ return self.Gm.matvec(f)
+ return r
+
+ def matvec(self, f):
+ return self.Gm.solve(f)
+
+ def rsolve(self, f, tol=0):
+ return self.Gm.rmatvec(f)
+
+ def rmatvec(self, f):
+ return self.Gm.rsolve(f)
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ self._reduce() # reduce first to preserve secant condition
+
+ v = self.Gm.rmatvec(dx)
+ c = dx - self.Gm.matvec(df)
+ d = v / vdot(df, v)
+
+ self.Gm.append(c, d)
+
+
+class BroydenSecond(BroydenFirst):
+ """
+ Find a root of a function, using Broyden\'s second Jacobian approximation.
+
+ This method is also known as \"Broyden's bad method\".
+
+ Parameters
+ ----------
+ %(params_basic)s
+ %(broyden_params)s
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='broyden2'`` in particular.
+
+ Notes
+ -----
+ This algorithm implements the inverse Jacobian Quasi-Newton update
+
+ .. math:: H_+ = H + (dx - H df) df^\\dagger / ( df^\\dagger df)
+
+ corresponding to Broyden's second method.
+
+ References
+ ----------
+ .. [1] B.A. van der Rotten, PhD thesis,
+ \"A limited memory Broyden method to solve high-dimensional
+ systems of nonlinear equations\". Mathematisch Instituut,
+ Universiteit Leiden, The Netherlands (2003).
+
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.broyden2(fun, [0, 0])
+ >>> sol
+ array([0.84116365, 0.15883529])
+
+ """
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ self._reduce() # reduce first to preserve secant condition
+
+ v = df
+ c = dx - self.Gm.matvec(df)
+ d = v / df_norm**2
+ self.Gm.append(c, d)
+
+
+#------------------------------------------------------------------------------
+# Broyden-like (restricted memory)
+#------------------------------------------------------------------------------
+
+class Anderson(GenericBroyden):
+ """
+ Find a root of a function, using (extended) Anderson mixing.
+
+ The Jacobian is formed by for a 'best' solution in the space
+ spanned by last `M` vectors. As a result, only a MxM matrix
+ inversions and MxN multiplications are required. [Ey]_
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ M : float, optional
+ Number of previous vectors to retain. Defaults to 5.
+ w0 : float, optional
+ Regularization parameter for numerical stability.
+ Compared to unity, good values of the order of 0.01.
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='anderson'`` in particular.
+
+ References
+ ----------
+ .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.anderson(fun, [0, 0])
+ >>> sol
+ array([0.84116588, 0.15883789])
+
+ """
+
+ # Note:
+ #
+ # Anderson method maintains a rank M approximation of the inverse Jacobian,
+ #
+ # J^-1 v ~ -v*alpha + (dX + alpha dF) A^-1 dF^H v
+ # A = W + dF^H dF
+ # W = w0^2 diag(dF^H dF)
+ #
+ # so that for w0 = 0 the secant condition applies for last M iterates, i.e.,
+ #
+ # J^-1 df_j = dx_j
+ #
+ # for all j = 0 ... M-1.
+ #
+ # Moreover, (from Sherman-Morrison-Woodbury formula)
+ #
+ # J v ~ [ b I - b^2 C (I + b dF^H A^-1 C)^-1 dF^H ] v
+ # C = (dX + alpha dF) A^-1
+ # b = -1/alpha
+ #
+ # and after simplification
+ #
+ # J v ~ -v/alpha + (dX/alpha + dF) (dF^H dX - alpha W)^-1 dF^H v
+ #
+
+ def __init__(self, alpha=None, w0=0.01, M=5):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+ self.M = M
+ self.dx = []
+ self.df = []
+ self.gamma = None
+ self.w0 = w0
+
+ def solve(self, f, tol=0):
+ dx = -self.alpha*f
+
+ n = len(self.dx)
+ if n == 0:
+ return dx
+
+ df_f = np.empty(n, dtype=f.dtype)
+ for k in range(n):
+ df_f[k] = vdot(self.df[k], f)
+
+ try:
+ gamma = solve(self.a, df_f)
+ except LinAlgError:
+ # singular; reset the Jacobian approximation
+ del self.dx[:]
+ del self.df[:]
+ return dx
+
+ for m in range(n):
+ dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
+ return dx
+
+ def matvec(self, f):
+ dx = -f/self.alpha
+
+ n = len(self.dx)
+ if n == 0:
+ return dx
+
+ df_f = np.empty(n, dtype=f.dtype)
+ for k in range(n):
+ df_f[k] = vdot(self.df[k], f)
+
+ b = np.empty((n, n), dtype=f.dtype)
+ for i in range(n):
+ for j in range(n):
+ b[i,j] = vdot(self.df[i], self.dx[j])
+ if i == j and self.w0 != 0:
+ b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha
+ gamma = solve(b, df_f)
+
+ for m in range(n):
+ dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha)
+ return dx
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ if self.M == 0:
+ return
+
+ self.dx.append(dx)
+ self.df.append(df)
+
+ while len(self.dx) > self.M:
+ self.dx.pop(0)
+ self.df.pop(0)
+
+ n = len(self.dx)
+ a = np.zeros((n, n), dtype=f.dtype)
+
+ for i in range(n):
+ for j in range(i, n):
+ if i == j:
+ wd = self.w0**2
+ else:
+ wd = 0
+ a[i,j] = (1+wd)*vdot(self.df[i], self.df[j])
+
+ a += np.triu(a, 1).T.conj()
+ self.a = a
+
+#------------------------------------------------------------------------------
+# Simple iterations
+#------------------------------------------------------------------------------
+
+
+class DiagBroyden(GenericBroyden):
+ """
+ Find a root of a function, using diagonal Broyden Jacobian approximation.
+
+ The Jacobian approximation is derived from previous iterations, by
+ retaining only the diagonal of Broyden matrices.
+
+ .. warning::
+
+ This algorithm may be useful for specific problems, but whether
+ it will work may depend strongly on the problem.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='diagbroyden'`` in particular.
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.diagbroyden(fun, [0, 0])
+ >>> sol
+ array([0.84116403, 0.15883384])
+
+ """
+
+ def __init__(self, alpha=None):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+
+ def setup(self, x, F, func):
+ GenericBroyden.setup(self, x, F, func)
+ self.d = np.full((self.shape[0],), 1 / self.alpha, dtype=self.dtype)
+
+ def solve(self, f, tol=0):
+ return -f / self.d
+
+ def matvec(self, f):
+ return -f * self.d
+
+ def rsolve(self, f, tol=0):
+ return -f / self.d.conj()
+
+ def rmatvec(self, f):
+ return -f * self.d.conj()
+
+ def todense(self):
+ return np.diag(-self.d)
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ self.d -= (df + self.d*dx)*dx/dx_norm**2
+
+
+class LinearMixing(GenericBroyden):
+ """
+ Find a root of a function, using a scalar Jacobian approximation.
+
+ .. warning::
+
+ This algorithm may be useful for specific problems, but whether
+ it will work may depend strongly on the problem.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ The Jacobian approximation is (-1/alpha).
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='linearmixing'`` in particular.
+
+ """
+
+ def __init__(self, alpha=None):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+
+ def solve(self, f, tol=0):
+ return -f*self.alpha
+
+ def matvec(self, f):
+ return -f/self.alpha
+
+ def rsolve(self, f, tol=0):
+ return -f*np.conj(self.alpha)
+
+ def rmatvec(self, f):
+ return -f/np.conj(self.alpha)
+
+ def todense(self):
+ return np.diag(np.full(self.shape[0], -1/self.alpha))
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ pass
+
+
+class ExcitingMixing(GenericBroyden):
+ """
+ Find a root of a function, using a tuned diagonal Jacobian approximation.
+
+ The Jacobian matrix is diagonal and is tuned on each iteration.
+
+ .. warning::
+
+ This algorithm may be useful for specific problems, but whether
+ it will work may depend strongly on the problem.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ Initial Jacobian approximation is (-1/alpha).
+ alphamax : float, optional
+ The entries of the diagonal Jacobian are kept in the range
+ ``[alpha, alphamax]``.
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='excitingmixing'`` in particular.
+ """
+
+ def __init__(self, alpha=None, alphamax=1.0):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+ self.alphamax = alphamax
+ self.beta = None
+
+ def setup(self, x, F, func):
+ GenericBroyden.setup(self, x, F, func)
+ self.beta = np.full((self.shape[0],), self.alpha, dtype=self.dtype)
+
+ def solve(self, f, tol=0):
+ return -f*self.beta
+
+ def matvec(self, f):
+ return -f/self.beta
+
+ def rsolve(self, f, tol=0):
+ return -f*self.beta.conj()
+
+ def rmatvec(self, f):
+ return -f/self.beta.conj()
+
+ def todense(self):
+ return np.diag(-1/self.beta)
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ incr = f*self.last_f > 0
+ self.beta[incr] += self.alpha
+ self.beta[~incr] = self.alpha
+ np.clip(self.beta, 0, self.alphamax, out=self.beta)
+
+
+#------------------------------------------------------------------------------
+# Iterative/Krylov approximated Jacobians
+#------------------------------------------------------------------------------
+
+class KrylovJacobian(Jacobian):
+ """
+ Find a root of a function, using Krylov approximation for inverse Jacobian.
+
+ This method is suitable for solving large-scale problems.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ rdiff : float, optional
+ Relative step size to use in numerical differentiation.
+ method : str or callable, optional
+ Krylov method to use to approximate the Jacobian. Can be a string,
+ or a function implementing the same interface as the iterative
+ solvers in `scipy.sparse.linalg`. If a string, needs to be one of:
+ ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``,
+ ``'tfqmr'``.
+
+ The default is `scipy.sparse.linalg.lgmres`.
+ inner_maxiter : int, optional
+ Parameter to pass to the "inner" Krylov solver: maximum number of
+ iterations. Iteration will stop after maxiter steps even if the
+ specified tolerance has not been achieved.
+ inner_M : LinearOperator or InverseJacobian
+ Preconditioner for the inner Krylov iteration.
+ Note that you can use also inverse Jacobians as (adaptive)
+ preconditioners. For example,
+
+ >>> from scipy.optimize import BroydenFirst, KrylovJacobian
+ >>> from scipy.optimize import InverseJacobian
+ >>> jac = BroydenFirst()
+ >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac))
+
+ If the preconditioner has a method named 'update', it will be called
+ as ``update(x, f)`` after each nonlinear step, with ``x`` giving
+ the current point, and ``f`` the current function value.
+ outer_k : int, optional
+ Size of the subspace kept across LGMRES nonlinear iterations.
+ See `scipy.sparse.linalg.lgmres` for details.
+ kw : kwargs
+ Keyword parameters for the "inner" Krylov solver
+ (defined with `method`). Parameter names must start with
+ the `inner_` prefix which will be stripped before passing on
+ the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details.
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='krylov'`` in particular.
+ scipy.sparse.linalg.gmres
+ scipy.sparse.linalg.lgmres
+
+ Notes
+ -----
+ This function implements a Newton-Krylov solver. The basic idea is
+ to compute the inverse of the Jacobian with an iterative Krylov
+ method. These methods require only evaluating the Jacobian-vector
+ products, which are conveniently approximated by a finite difference:
+
+ .. math:: J v \\approx (f(x + \\omega*v/|v|) - f(x)) / \\omega
+
+ Due to the use of iterative matrix inverses, these methods can
+ deal with large nonlinear problems.
+
+ SciPy's `scipy.sparse.linalg` module offers a selection of Krylov
+ solvers to choose from. The default here is `lgmres`, which is a
+ variant of restarted GMRES iteration that reuses some of the
+ information obtained in the previous Newton steps to invert
+ Jacobians in subsequent steps.
+
+ For a review on Newton-Krylov methods, see for example [1]_,
+ and for the LGMRES sparse inverse method, see [2]_.
+
+ References
+ ----------
+ .. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method,
+ SIAM, pp.57-83, 2003.
+ :doi:`10.1137/1.9780898718898.ch3`
+ .. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004).
+ :doi:`10.1016/j.jcp.2003.08.010`
+ .. [3] A.H. Baker and E.R. Jessup and T. Manteuffel,
+ SIAM J. Matrix Anal. Appl. 26, 962 (2005).
+ :doi:`10.1137/S0895479803422014`
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * x[1] - 1.0,
+ ... 0.5 * (x[1] - x[0]) ** 2]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.newton_krylov(fun, [0, 0])
+ >>> sol
+ array([0.66731771, 0.66536458])
+
+ """
+
+ def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20,
+ inner_M=None, outer_k=10, **kw):
+ self.preconditioner = inner_M
+ self.rdiff = rdiff
+ # Note that this retrieves one of the named functions, or otherwise
+ # uses `method` as is (i.e., for a user-provided callable).
+ self.method = dict(
+ bicgstab=scipy.sparse.linalg.bicgstab,
+ gmres=scipy.sparse.linalg.gmres,
+ lgmres=scipy.sparse.linalg.lgmres,
+ cgs=scipy.sparse.linalg.cgs,
+ minres=scipy.sparse.linalg.minres,
+ tfqmr=scipy.sparse.linalg.tfqmr,
+ ).get(method, method)
+
+ self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner)
+
+ if self.method is scipy.sparse.linalg.gmres:
+ # Replace GMRES's outer iteration with Newton steps
+ self.method_kw['restart'] = inner_maxiter
+ self.method_kw['maxiter'] = 1
+ self.method_kw.setdefault('atol', 0)
+ elif self.method in (scipy.sparse.linalg.gcrotmk,
+ scipy.sparse.linalg.bicgstab,
+ scipy.sparse.linalg.cgs):
+ self.method_kw.setdefault('atol', 0)
+ elif self.method is scipy.sparse.linalg.lgmres:
+ self.method_kw['outer_k'] = outer_k
+ # Replace LGMRES's outer iteration with Newton steps
+ self.method_kw['maxiter'] = 1
+ # Carry LGMRES's `outer_v` vectors across nonlinear iterations
+ self.method_kw.setdefault('outer_v', [])
+ self.method_kw.setdefault('prepend_outer_v', True)
+ # But don't carry the corresponding Jacobian*v products, in case
+ # the Jacobian changes a lot in the nonlinear step
+ #
+ # XXX: some trust-region inspired ideas might be more efficient...
+ # See e.g., Brown & Saad. But needs to be implemented separately
+ # since it's not an inexact Newton method.
+ self.method_kw.setdefault('store_outer_Av', False)
+ self.method_kw.setdefault('atol', 0)
+
+ # Retrieve the signature of the method to find the valid parameters
+ valid_inner_params = [
+ k for k in signature(self.method).parameters
+ if k not in ('self', 'args', 'kwargs')
+ ]
+
+ for key, value in kw.items():
+ if not key.startswith("inner_"):
+ raise ValueError(f"Unknown parameter {key}")
+ if key[6:] not in valid_inner_params:
+ # Use difflib to find close matches to the invalid key
+ inner_param_suggestions = get_close_matches(key[6:],
+ valid_inner_params,
+ n=1)
+ if inner_param_suggestions:
+ suggestion_msg = (f" Did you mean '"
+ f"{inner_param_suggestions[0]}'?")
+ else:
+ suggestion_msg = ""
+
+ # warn user that the parameter is not valid for the inner method
+ warnings.warn(
+ f"Option '{key}' is invalid for the inner method: {method}."
+ " It will be ignored."
+ "Please check inner method documentation for valid options."
+ + suggestion_msg,
+ category=UserWarning,
+ skip_file_prefixes=(os.path.dirname(__file__),)
+ )
+ # ignore this parameter and continue
+ continue
+ self.method_kw[key[6:]] = value
+
+ def _update_diff_step(self):
+ mx = abs(self.x0).max()
+ mf = abs(self.f0).max()
+ self.omega = self.rdiff * max(1, mx) / max(1, mf)
+
+ def matvec(self, v):
+ nv = norm(v)
+ if nv == 0:
+ return 0*v
+ sc = self.omega / nv
+ r = (self.func(self.x0 + sc*v) - self.f0) / sc
+ if not np.all(np.isfinite(r)) and np.all(np.isfinite(v)):
+ raise ValueError('Function returned non-finite results')
+ return r
+
+ def solve(self, rhs, tol=0):
+ if 'rtol' in self.method_kw:
+ sol, info = self.method(self.op, rhs, **self.method_kw)
+ else:
+ sol, info = self.method(self.op, rhs, rtol=tol, **self.method_kw)
+ return sol
+
+ def update(self, x, f):
+ self.x0 = x
+ self.f0 = f
+ self._update_diff_step()
+
+ # Update also the preconditioner, if possible
+ if self.preconditioner is not None:
+ if hasattr(self.preconditioner, 'update'):
+ self.preconditioner.update(x, f)
+
+ def setup(self, x, f, func):
+ Jacobian.setup(self, x, f, func)
+ self.x0 = x
+ self.f0 = f
+ self.op = scipy.sparse.linalg.aslinearoperator(self)
+
+ if self.rdiff is None:
+ self.rdiff = np.finfo(x.dtype).eps ** (1./2)
+
+ self._update_diff_step()
+
+ # Setup also the preconditioner, if possible
+ if self.preconditioner is not None:
+ if hasattr(self.preconditioner, 'setup'):
+ self.preconditioner.setup(x, f, func)
+
+
+#------------------------------------------------------------------------------
+# Wrapper functions
+#------------------------------------------------------------------------------
+
+def _nonlin_wrapper(name, jac):
+ """
+ Construct a solver wrapper with given name and Jacobian approx.
+
+ It inspects the keyword arguments of ``jac.__init__``, and allows to
+ use the same arguments in the wrapper function, in addition to the
+ keyword arguments of `nonlin_solve`
+
+ """
+ signature = _getfullargspec(jac.__init__)
+ args, varargs, varkw, defaults, kwonlyargs, kwdefaults, _ = signature
+ kwargs = list(zip(args[-len(defaults):], defaults))
+ kw_str = ", ".join([f"{k}={v!r}" for k, v in kwargs])
+ if kw_str:
+ kw_str = ", " + kw_str
+ kwkw_str = ", ".join([f"{k}={k}" for k, v in kwargs])
+ if kwkw_str:
+ kwkw_str = kwkw_str + ", "
+ if kwonlyargs:
+ raise ValueError(f'Unexpected signature {signature}')
+
+ # Construct the wrapper function so that its keyword arguments
+ # are visible in pydoc.help etc.
+ wrapper = """
+def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None,
+ f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
+ tol_norm=None, line_search='armijo', callback=None, **kw):
+ jac = %(jac)s(%(kwkw)s **kw)
+ return nonlin_solve(F, xin, jac, iter, verbose, maxiter,
+ f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search,
+ callback)
+"""
+
+ wrapper = wrapper % dict(name=name, kw=kw_str, jac=jac.__name__,
+ kwkw=kwkw_str)
+ ns = {}
+ ns.update(globals())
+ exec(wrapper, ns)
+ func = ns[name]
+ func.__doc__ = jac.__doc__
+ _set_doc(func)
+ return func
+
+
+broyden1 = _nonlin_wrapper('broyden1', BroydenFirst)
+broyden2 = _nonlin_wrapper('broyden2', BroydenSecond)
+anderson = _nonlin_wrapper('anderson', Anderson)
+linearmixing = _nonlin_wrapper('linearmixing', LinearMixing)
+diagbroyden = _nonlin_wrapper('diagbroyden', DiagBroyden)
+excitingmixing = _nonlin_wrapper('excitingmixing', ExcitingMixing)
+newton_krylov = _nonlin_wrapper('newton_krylov', KrylovJacobian)
+_set_doc_class(BroydenFirst)
+_set_doc_class(KrylovJacobian)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_numdiff.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_numdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bb01740e9a3773afa3edeab7975db890d47408d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_numdiff.py
@@ -0,0 +1,996 @@
+"""Routines for numerical differentiation."""
+import functools
+import numpy as np
+from numpy.linalg import norm
+
+from scipy.sparse.linalg import LinearOperator
+from ..sparse import issparse, spmatrix, find, csc_array, csr_array, csr_matrix
+from ._group_columns import group_dense, group_sparse
+from scipy._lib._array_api import array_namespace, xp_result_type
+from scipy._lib._util import MapWrapper
+from scipy._external import array_api_extra as xpx
+
+
+def _adjust_scheme_to_bounds(x0, h, num_steps, scheme, lb, ub):
+ """Adjust final difference scheme to the presence of bounds.
+
+ Parameters
+ ----------
+ x0 : ndarray, shape (n,)
+ Point at which we wish to estimate derivative.
+ h : ndarray, shape (n,)
+ Desired absolute finite difference steps.
+ num_steps : int
+ Number of `h` steps in one direction required to implement finite
+ difference scheme. For example, 2 means that we need to evaluate
+ f(x0 + 2 * h) or f(x0 - 2 * h)
+ scheme : {'1-sided', '2-sided'}
+ Whether steps in one or both directions are required. In other
+ words '1-sided' applies to forward and backward schemes, '2-sided'
+ applies to center schemes.
+ lb : ndarray, shape (n,)
+ Lower bounds on independent variables.
+ ub : ndarray, shape (n,)
+ Upper bounds on independent variables.
+
+ Returns
+ -------
+ h_adjusted : ndarray, shape (n,)
+ Adjusted absolute step sizes. Step size decreases only if a sign flip
+ or switching to one-sided scheme doesn't allow to take a full step.
+ use_one_sided : ndarray of bool, shape (n,)
+ Whether to switch to one-sided scheme. Informative only for
+ ``scheme='2-sided'``.
+ """
+ if scheme == '1-sided':
+ use_one_sided = np.ones_like(h, dtype=bool)
+ elif scheme == '2-sided':
+ h = np.abs(h)
+ use_one_sided = np.zeros_like(h, dtype=bool)
+ else:
+ raise ValueError("`scheme` must be '1-sided' or '2-sided'.")
+
+ if np.all((lb == -np.inf) & (ub == np.inf)):
+ return h, use_one_sided
+
+ h_total = h * num_steps
+ h_adjusted = h.copy()
+
+ lower_dist = x0 - lb
+ upper_dist = ub - x0
+
+ if scheme == '1-sided':
+ x = x0 + h_total
+ violated = (x < lb) | (x > ub)
+ fitting = np.abs(h_total) <= np.maximum(lower_dist, upper_dist)
+ h_adjusted[violated & fitting] *= -1
+
+ forward = (upper_dist >= lower_dist) & ~fitting
+ h_adjusted[forward] = upper_dist[forward] / num_steps
+ backward = (upper_dist < lower_dist) & ~fitting
+ h_adjusted[backward] = -lower_dist[backward] / num_steps
+ elif scheme == '2-sided':
+ central = (lower_dist >= h_total) & (upper_dist >= h_total)
+
+ forward = (upper_dist >= lower_dist) & ~central
+ h_adjusted[forward] = np.minimum(
+ h[forward], 0.5 * upper_dist[forward] / num_steps)
+ use_one_sided[forward] = True
+
+ backward = (upper_dist < lower_dist) & ~central
+ h_adjusted[backward] = -np.minimum(
+ h[backward], 0.5 * lower_dist[backward] / num_steps)
+ use_one_sided[backward] = True
+
+ min_dist = np.minimum(upper_dist, lower_dist) / num_steps
+ adjusted_central = (~central & (np.abs(h_adjusted) <= min_dist))
+ h_adjusted[adjusted_central] = min_dist[adjusted_central]
+ use_one_sided[adjusted_central] = False
+
+ return h_adjusted, use_one_sided
+
+
+@functools.lru_cache
+def _eps_for_method(x0_dtype, f0_dtype, method):
+ """
+ Calculates relative EPS step to use for a given data type
+ and numdiff step method.
+
+ Progressively smaller steps are used for larger floating point types.
+
+ Parameters
+ ----------
+ f0_dtype: np.dtype
+ dtype of function evaluation
+
+ x0_dtype: np.dtype
+ dtype of parameter vector
+
+ method: {'2-point', '3-point', 'cs'}
+
+ Returns
+ -------
+ EPS: float
+ relative step size. May be np.float16, np.float32, np.float64
+
+ Notes
+ -----
+ The default relative step will be np.float64. However, if x0 or f0 are
+ smaller floating point types (np.float16, np.float32), then the smallest
+ floating point type is chosen.
+ """
+ # the default EPS value
+ EPS = np.finfo(np.float64).eps
+
+ x0_is_fp = False
+ if np.issubdtype(x0_dtype, np.inexact):
+ # if you're a floating point type then over-ride the default EPS
+ EPS = np.finfo(x0_dtype).eps
+ x0_itemsize = np.dtype(x0_dtype).itemsize
+ x0_is_fp = True
+
+ if np.issubdtype(f0_dtype, np.inexact):
+ f0_itemsize = np.dtype(f0_dtype).itemsize
+ # choose the smallest itemsize between x0 and f0
+ if x0_is_fp and f0_itemsize < x0_itemsize:
+ EPS = np.finfo(f0_dtype).eps
+
+ if method in ["2-point", "cs"]:
+ return EPS**0.5
+ elif method in ["3-point"]:
+ return EPS**(1/3)
+ else:
+ raise RuntimeError("Unknown step method, should be one of "
+ "{'2-point', '3-point', 'cs'}")
+
+
+def _compute_absolute_step(rel_step, x0, f0, method):
+ """
+ Computes an absolute step from a relative step for finite difference
+ calculation.
+
+ Parameters
+ ----------
+ rel_step: None or array-like
+ Relative step for the finite difference calculation
+ x0 : np.ndarray
+ Parameter vector
+ f0 : np.ndarray or scalar
+ method : {'2-point', '3-point', 'cs'}
+
+ Returns
+ -------
+ h : np.array
+ The absolute step size, ``h.dtype==x0.dtype``.
+
+ Notes
+ -----
+ `h` has the same dtype as `x0` because dx is later calculated
+ as ``(x0 + h) - x0``, and problems would occur if ``x0.dtype==np.float16``
+ with ``h.dtype==np.float64``.
+ If `rel_step is None`, then a default relative step is calculated using the
+ smallest floating point type of `x0` and `f0`, see _eps_for_method.
+
+ """
+ # this is used instead of np.sign(x0) because we need
+ # sign_x0 to be 1 when x0 == 0.
+ sign_x0 = (x0 >= 0).astype(x0.dtype) * 2 - 1
+
+ rstep = _eps_for_method(x0.dtype, f0.dtype, method)
+ default_abs_step = (
+ rstep * sign_x0 * np.maximum(1.0, np.abs(x0))
+ ).astype(x0.dtype)
+
+ if rel_step is None:
+ abs_step = default_abs_step
+ else:
+ # User has requested specific relative steps.
+ # Don't multiply by max(1, abs(x0) because if x0 < 1 then their
+ # requested step is not used.
+ abs_step = (
+ rel_step * sign_x0 * np.abs(x0)
+ ).astype(x0.dtype)
+
+ # however we don't want an abs_step of 0, which can happen if
+ # rel_step is 0, or x0 is 0. Instead, substitute a realistic step
+ dx = ((x0 + abs_step) - x0)
+ abs_step = np.where(
+ dx == 0,
+ default_abs_step,
+ abs_step
+ )
+
+ return abs_step
+
+
+def _prepare_bounds(bounds, x0):
+ """
+ Prepares new-style bounds from a two-tuple specifying the lower and upper
+ limits for values in x0. If a value is not bound then the lower/upper bound
+ will be expected to be -np.inf/np.inf.
+
+ Examples
+ --------
+ >>> _prepare_bounds([(0, 1, 2), (1, 2, np.inf)], [0.5, 1.5, 2.5])
+ (array([0., 1., 2.]), array([ 1., 2., inf]))
+ """
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
+ if lb.ndim == 0:
+ lb = np.resize(lb, x0.shape)
+
+ if ub.ndim == 0:
+ ub = np.resize(ub, x0.shape)
+
+ return lb, ub
+
+
+def group_columns(A, order=0):
+ """Group columns of a 2-D matrix for sparse finite differencing [1]_.
+
+ Two columns are in the same group if in each row at least one of them
+ has zero. A greedy sequential algorithm is used to construct groups.
+
+ Parameters
+ ----------
+ A : array_like or sparse array, shape (m, n)
+ Matrix of which to group columns.
+ order : int, iterable of int with shape (n,) or None
+ Permutation array which defines the order of columns enumeration.
+ If int or None, a random permutation is used with `order` used as
+ a random seed. Default is 0, that is use a random permutation but
+ guarantee repeatability.
+
+ Returns
+ -------
+ groups : ndarray of int, shape (n,)
+ Contains values from 0 to n_groups-1, where n_groups is the number
+ of found groups. Each value ``groups[i]`` is an index of a group to
+ which ith column assigned. The procedure was helpful only if
+ n_groups is significantly less than n.
+
+ References
+ ----------
+ .. [1] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
+ and its Applications, 13 (1974), pp. 117-120.
+ """
+ if issparse(A):
+ A = csc_array(A)
+ else:
+ A = np.atleast_2d(A)
+ A = (A != 0).astype(np.int32)
+
+ if A.ndim != 2:
+ raise ValueError("`A` must be 2-dimensional.")
+
+ m, n = A.shape
+
+ if order is None or np.isscalar(order):
+ rng = np.random.RandomState(order)
+ order = rng.permutation(n)
+ else:
+ order = np.asarray(order)
+ if order.shape != (n,):
+ raise ValueError("`order` has incorrect shape.")
+
+ A = A[:, order]
+
+ if issparse(A):
+ groups = group_sparse(m, n, A.indices, A.indptr)
+ else:
+ groups = group_dense(m, n, A)
+
+ groups[order] = groups.copy()
+
+ return groups
+
+
+def approx_derivative(fun, x0, method='3-point', rel_step=None, abs_step=None,
+ f0=None, bounds=(-np.inf, np.inf), sparsity=None,
+ as_linear_operator=False, args=(), kwargs=None,
+ full_output=False, workers=None):
+ """Compute finite difference approximation of the derivatives of a
+ vector-valued function.
+
+ If a function maps from R^n to R^m, its derivatives form m-by-n matrix
+ called the Jacobian, where an element (i, j) is a partial derivative of
+ f[i] with respect to x[j].
+
+ Parameters
+ ----------
+ fun : callable
+ Function of which to estimate the derivatives. The argument x
+ passed to this function is ndarray of shape (n,) (never a scalar
+ even if n=1). It must return 1-D array_like of shape (m,) or a scalar.
+ x0 : array_like of shape (n,) or float
+ Point at which to estimate the derivatives. Float will be converted
+ to a 1-D array.
+ method : {'3-point', '2-point', 'cs'}, optional
+ Finite difference method to use:
+ - '2-point' - use the first order accuracy forward or backward
+ difference.
+ - '3-point' - use central difference in interior points and the
+ second order accuracy forward or backward difference
+ near the boundary.
+ - 'cs' - use a complex-step finite difference scheme. This assumes
+ that the user function is real-valued and can be
+ analytically continued to the complex plane. Otherwise,
+ produces bogus results.
+ rel_step : None or array_like, optional
+ Relative step size to use. If None (default) the absolute step size is
+ computed as ``h = (rel_step * sign(x0) * max(1, abs(x0))).astype(x0.dtype)``,
+ with `rel_step` being selected automatically, see Notes. Otherwise
+ ``h = (rel_step * sign(x0) * abs(x0)).astype(x0.dtype)``. For
+ ``method='3-point'`` the sign of `h` is ignored. The calculated step size
+ is possibly adjusted to fit into the bounds.
+ abs_step : array_like, optional
+ Absolute step size to use, possibly adjusted to fit into the bounds.
+ For ``method='3-point'`` the sign of `abs_step` is ignored. By default
+ relative steps are used, only if ``abs_step is not None`` are absolute
+ steps used. `abs_step` is coerced to the dtype of `x0` during calculation.
+ f0 : None or array_like, optional
+ If not None it is assumed to be equal to ``fun(x0)``, in this case
+ the ``fun(x0)`` is not called. Default is None.
+ bounds : tuple of array_like, optional
+ Lower and upper bounds on independent variables. Defaults to no bounds.
+ Each bound must match the size of `x0` or be a scalar, in the latter
+ case the bound will be the same for all variables. Use it to limit the
+ range of function evaluation. Bounds checking is not implemented
+ when `as_linear_operator` is True.
+ sparsity : {None, array_like, sparse array, 2-tuple}, optional
+ Defines a sparsity structure of the Jacobian matrix. If the Jacobian
+ matrix is known to have only few non-zero elements in each row, then
+ it's possible to estimate its several columns by a single function
+ evaluation [3]_. To perform such economic computations two ingredients
+ are required:
+
+ * structure : array_like or sparse array of shape (m, n). A zero
+ element means that a corresponding element of the Jacobian
+ identically equals to zero.
+ * groups : array_like of shape (n,). A column grouping for a given
+ sparsity structure, use `group_columns` to obtain it.
+
+ A single array or a sparse array is interpreted as a sparsity
+ structure, and groups are computed inside the function. A tuple is
+ interpreted as (structure, groups). If None (default), a standard
+ dense differencing will be used.
+
+ Note, that sparse differencing makes sense only for large Jacobian
+ matrices where each row contains few non-zero elements.
+ as_linear_operator : bool, optional
+ When True the function returns an `scipy.sparse.linalg.LinearOperator`.
+ Otherwise it returns a dense array or a sparse array depending on
+ `sparsity`. The linear operator provides an efficient way of computing
+ ``J.dot(p)`` for any vector ``p`` of shape (n,), but does not allow
+ direct access to individual elements of the matrix. By default
+ `as_linear_operator` is False.
+ args, kwargs : tuple and dict, optional
+ Additional arguments passed to `fun`. Both empty by default.
+ The calling signature is ``fun(x, *args, **kwargs)``.
+ full_output : bool, optional
+ If True then the function also returns a dictionary with extra information
+ about the calculation.
+ workers : int or map-like callable, optional
+ Supply a map-like callable, such as
+ `multiprocessing.Pool.map` for evaluating the population in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+ Alternatively, if `workers` is an int the task is subdivided into `workers`
+ sections and the fun evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ It is recommended that a map-like be used instead of int, as repeated
+ calls to `approx_derivative` will incur large overhead from setting up
+ new processes.
+
+ Returns
+ -------
+ J : {ndarray, sparse array, LinearOperator}
+ Finite difference approximation of the Jacobian matrix.
+ If `as_linear_operator` is True returns a LinearOperator
+ with shape (m, n). Otherwise it returns a dense array or sparse
+ array depending on how `sparsity` is defined. If `sparsity`
+ is None then an ndarray with shape (m, n) is returned. If
+ `sparsity` is not None returns a csr_array or csr_matrix with
+ shape (m, n) following the array/matrix type of the incoming structure.
+ For sparse arrays and linear operators it is always returned as
+ a 2-D structure. For ndarrays, if m=1 it is returned
+ as a 1-D gradient array with shape (n,).
+ `J.dtype` is the promoted type of ``fun(x0)`` and `x0`.
+
+ info_dict : dict
+ Dictionary containing extra information about the calculation. The
+ keys include:
+
+ - `nfev`, number of function evaluations. If `as_linear_operator` is True
+ then `fun` is expected to track the number of evaluations itself.
+ This is because multiple calls may be made to the linear operator which
+ are not trackable here.
+
+ See Also
+ --------
+ check_derivative : Check correctness of a function computing derivatives.
+
+ Notes
+ -----
+ If `rel_step` is not provided, it is assigned as ``EPS**(1/s)``, where EPS is
+ determined from the smallest floating point dtype of `x0` or ``fun(x0)``,
+ ``np.finfo(x0.dtype).eps``, s=2 for '2-point' method and
+ s=3 for '3-point' method. This relative step approximately minimizes a sum
+ of truncation and round-off errors, see [1]_. Relative steps are used by
+ default. However, absolute steps are used when ``abs_step is not None``.
+ If any of the absolute or relative steps produces an indistinguishable
+ difference from the original `x0`, ``(x0 + dx) - x0 == 0``, then a
+ automatic step size is substituted for that particular entry.
+ The calculated absolute step size, `h`, is coerced to have the same dtype as `x0`.
+
+ The floating point precision of `J` is the promoted type of ``fun(x0)``
+ and `x0`. If `rel_step` and `abs_step` are None, then the overall accuracy of
+ `J` depends on the smallest floating point dtype of `x0` and ``fun(x0)``,
+ as that dtype is used to calculate the default step size.
+
+ A finite difference scheme for '3-point' method is selected automatically.
+ The well-known central difference scheme is used for points sufficiently
+ far from the boundary, and 3-point forward or backward scheme is used for
+ points near the boundary. Both schemes have the second-order accuracy in
+ terms of Taylor expansion. Refer to [2]_ for the formulas of 3-point
+ forward and backward difference schemes.
+
+ For dense differencing when m=1 Jacobian is returned with a shape (n,),
+ on the other hand when n=1 Jacobian is returned with a shape (m, 1).
+ Our motivation is the following: a) It handles a case of gradient
+ computation (m=1) in a conventional way. b) It clearly separates these two
+ different cases. b) In all cases np.atleast_2d can be called to get 2-D
+ Jacobian with correct dimensions.
+
+ References
+ ----------
+ .. [1] W. H. Press et. al. "Numerical Recipes. The Art of Scientific
+ Computing. 3rd edition", sec. 5.7.
+
+ .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
+ and its Applications, 13 (1974), pp. 117-120.
+
+ .. [3] B. Fornberg, "Generation of Finite Difference Formulas on
+ Arbitrarily Spaced Grids", Mathematics of Computation 51, 1988.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize._numdiff import approx_derivative
+ >>>
+ >>> def f(x, c1, c2):
+ ... return np.array([x[0] * np.sin(c1 * x[1]),
+ ... x[0] * np.cos(c2 * x[1])])
+ ...
+ >>> x0 = np.array([1.0, 0.5 * np.pi])
+ >>> approx_derivative(f, x0, args=(1, 2))
+ array([[ 1., 0.],
+ [-1., 0.]])
+
+ Bounds can be used to limit the region of function evaluation.
+ In the example below we compute left and right derivative at point 1.0.
+
+ >>> def g(x):
+ ... return x**2 if x >= 1 else x
+ ...
+ >>> x0 = 1.0
+ >>> approx_derivative(g, x0, bounds=(-np.inf, 1.0))
+ array([ 1.])
+ >>> approx_derivative(g, x0, bounds=(1.0, np.inf))
+ array([ 2.])
+
+ We can also parallelize the derivative calculation using the workers
+ keyword.
+
+ >>> from multiprocessing import Pool
+ >>> import time
+ >>> def fun2(x): # import from an external file for use with multiprocessing
+ ... time.sleep(0.002)
+ ... return rosen(x)
+
+ >>> rng = np.random.default_rng()
+ >>> x0 = rng.uniform(high=10, size=(2000,))
+ >>> f0 = rosen(x0)
+
+ >>> %timeit approx_derivative(fun2, x0, f0=f0) # may vary
+ 10.5 s ± 5.91 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
+
+ >>> elapsed = []
+ >>> with Pool() as workers:
+ ... for i in range(10):
+ ... t = time.perf_counter()
+ ... approx_derivative(fun2, x0, workers=workers.map, f0=f0)
+ ... et = time.perf_counter()
+ ... elapsed.append(et - t)
+ >>> np.mean(elapsed) # may vary
+ np.float64(1.442545195999901)
+
+ Create a map-like vectorized version. `x` is a generator, so first of all
+ a 2-D array, `xx`, is reconstituted. Here `xx` has shape `(Y, N)` where `Y`
+ is the number of function evaluations to perform and `N` is the dimensionality
+ of the objective function. The underlying objective function is `rosen`, which
+ requires `xx` to have shape `(N, Y)`, so a transpose is required.
+
+ >>> def fun(f, x, *args, **kwds):
+ ... xx = np.r_[[xs for xs in x]]
+ ... return f(xx.T)
+ >>> %timeit approx_derivative(fun2, x0, workers=fun, f0=f0) # may vary
+ 91.8 ms ± 755 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
+
+ """
+ if method not in ['2-point', '3-point', 'cs']:
+ raise ValueError(f"Unknown method '{method}'. ")
+
+ info_dict = {'nfev': None}
+
+ xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # promotes to floating
+ x0 = xp.astype(_x, _dtype)
+
+ if x0.ndim > 1:
+ raise ValueError("`x0` must have at most 1 dimension.")
+
+ lb, ub = _prepare_bounds(bounds, x0)
+
+ if lb.shape != x0.shape or ub.shape != x0.shape:
+ raise ValueError("Inconsistent shapes between bounds and `x0`.")
+
+ if as_linear_operator and not (np.all(np.isinf(lb))
+ and np.all(np.isinf(ub))):
+ raise ValueError("Bounds not supported when "
+ "`as_linear_operator` is True.")
+
+ if kwargs is None:
+ kwargs = {}
+
+ fun_wrapped = _Fun_Wrapper(fun, x0, args, kwargs)
+
+ # Record how function evaluations are consumed by `approx_derivative`.
+ # Historically this was done by upstream functions wrapping `fun`.
+ # However, with parallelization via workers it was going to be impossible to
+ # keep that counter updated across Processes. Counter synchronisation can
+ # be achieved via multiprocessing.Value and a Pool. However, workers can be
+ # any map-like, not necessarily a Pool, so initialization of the Value would
+ # be difficult.
+ nfev = _nfev = 0
+
+ if f0 is None:
+ f0 = fun_wrapped(x0)
+ nfev = 1
+ else:
+ f0 = np.atleast_1d(f0)
+ if f0.ndim > 1:
+ raise ValueError("`f0` passed has more than 1 dimension.")
+
+ if np.any((x0 < lb) | (x0 > ub)):
+ raise ValueError("`x0` violates bound constraints.")
+
+ if as_linear_operator:
+ if rel_step is None:
+ rel_step = _eps_for_method(x0.dtype, f0.dtype, method)
+
+ J, _ = _linear_operator_difference(fun_wrapped, x0,
+ f0, rel_step, method)
+ else:
+ # by default we use rel_step
+ if abs_step is None:
+ h = _compute_absolute_step(rel_step, x0, f0, method)
+ else:
+ # user specifies an absolute step
+ sign_x0 = (x0 >= 0).astype(x0.dtype) * 2 - 1
+ h = abs_step
+
+ # cannot have a zero step. This might happen if x0 is very large
+ # or small. In which case fall back to relative step.
+ dx = ((x0 + h) - x0)
+ h = np.where(dx == 0,
+ _eps_for_method(x0.dtype, f0.dtype, method) *
+ sign_x0 * np.maximum(1.0, np.abs(x0)),
+ h)
+ h = h.astype(x0.dtype)
+
+ if method == '2-point':
+ h, use_one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '1-sided', lb, ub)
+ elif method == '3-point':
+ h, use_one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', lb, ub)
+ elif method == 'cs':
+ use_one_sided = False
+
+ # normalize workers
+ workers = workers or map
+ with MapWrapper(workers) as mf:
+ if sparsity is None:
+ J, _nfev = _dense_difference(fun_wrapped, x0, f0, h,
+ use_one_sided, method,
+ mf)
+ else:
+ if not issparse(sparsity) and len(sparsity) == 2:
+ structure, groups = sparsity
+ else:
+ structure = sparsity
+ groups = group_columns(sparsity)
+
+ if issparse(structure):
+ structure = structure.tocsc()
+ else:
+ structure = np.atleast_2d(structure)
+ groups = np.atleast_1d(groups)
+ J, _nfev = _sparse_difference(fun_wrapped, x0, f0, h,
+ use_one_sided, structure,
+ groups, method, mf)
+
+ if full_output:
+ nfev += _nfev
+ info_dict["nfev"] = nfev
+ return J, info_dict
+ else:
+ return J
+
+
+def _linear_operator_difference(fun, x0, f0, h, method):
+ m = f0.size
+ n = x0.size
+
+ result_dtype = xp_result_type(x0, f0, force_floating=True, xp=np)
+
+ if method == '2-point':
+ # nfev = 1
+ def matvec(p):
+ if np.array_equal(p, np.zeros_like(p)):
+ return np.zeros(m, dtype=result_dtype)
+ dx = h / norm(p)
+ x = x0 + dx*p
+ df = fun(x) - f0
+ return df / dx
+
+ elif method == '3-point':
+ # nfev = 2
+ def matvec(p):
+ if np.array_equal(p, np.zeros_like(p)):
+ return np.zeros(m, dtype=result_dtype)
+ dx = 2*h / norm(p)
+ x1 = x0 - (dx/2)*p
+ x2 = x0 + (dx/2)*p
+ f1 = fun(x1)
+ f2 = fun(x2)
+ df = f2 - f1
+ return df / dx
+
+ elif method == 'cs':
+ # nfev = 1
+ def matvec(p):
+ if np.array_equal(p, np.zeros_like(p)):
+ return np.zeros(m, dtype=result_dtype)
+ dx = h / norm(p)
+ x = x0 + dx*p*1.j
+ f1 = fun(x)
+ df = f1.imag
+ return df / dx
+ else:
+ raise RuntimeError("Never be here.")
+
+ return LinearOperator(shape=(m, n), matvec=matvec, dtype=result_dtype), 0
+
+
+def _dense_difference(fun, x0, f0, h, use_one_sided, method, workers):
+ m = f0.size
+ n = x0.size
+ nfev = 0
+
+ # h should have same dtype as x0
+ result_type = xp_result_type(x0, f0, force_floating=True, xp=np)
+ # output dtype should be the same as df_dx
+ J_transposed = np.empty((n, m), dtype=result_type)
+
+ if method == '2-point':
+ def x_generator2(x0, h):
+ for i in range(n):
+ # If copying isn't done then it's possible for different workers
+ # to see the same values of x1. (At least that's what happened
+ # when I used `multiprocessing.dummy.Pool`).
+ # I also considered creating all the vectors at once, but that
+ # means assembling a very large N x N array. It's therefore a
+ # trade-off between N array copies or creating an NxN array.
+ x1 = np.copy(x0)
+ x1[i] = x0[i] + h[i]
+ yield x1
+
+ # only f_evals (numerator) needs parallelization, the denominator
+ # (the step size) is fast to calculate.
+ f_evals = workers(fun, x_generator2(x0, h))
+ dx = [(x0[i] + h[i]) - x0[i] for i in range(n)]
+ df = [f_eval - f0 for f_eval in f_evals]
+ df_dx = [delf / delx for delf, delx in zip(df, dx)]
+ nfev += len(df_dx)
+
+ elif method == '3-point':
+ def x_generator3(x0, h, use_one_sided):
+ for i, one_sided in enumerate(use_one_sided):
+ x1 = np.copy(x0)
+ x2 = np.copy(x0)
+ if one_sided:
+ x1[i] = x0[i] + h[i]
+ x2[i] = x0[i] + 2*h[i]
+ else:
+ x1[i] = x0[i] - h[i]
+ x2[i] = x0[i] + h[i]
+ yield x1
+ yield x2
+
+ # workers may return something like a list that needs to be turned
+ # into an iterable (can't call `next` on a list)
+ f_evals = iter(workers(fun, x_generator3(x0, h, use_one_sided)))
+ gen = x_generator3(x0, h, use_one_sided)
+ dx = list()
+ df = list()
+ for i, one_sided in enumerate(use_one_sided):
+ l = next(gen)
+ u = next(gen)
+
+ f1 = next(f_evals)
+ f2 = next(f_evals)
+ if one_sided:
+ dx.append(u[i] - x0[i])
+ df.append(-3.0 * f0 + 4 * f1 - f2)
+ else:
+ dx.append(u[i] - l[i])
+ df.append(f2 - f1)
+ df_dx = [delf / delx for delf, delx in zip(df, dx)]
+ nfev += 2 * len(df_dx)
+ elif method == 'cs':
+ def x_generator_cs(x0, h):
+ for i in range(n):
+ xc = x0.astype(complex, copy=True)
+ xc[i] += h[i] * 1.j
+ yield xc
+
+ f_evals = iter(workers(fun, x_generator_cs(x0, h)))
+ df_dx = [f1.imag / hi for f1, hi in zip(f_evals, h)]
+ nfev += len(df_dx)
+ else:
+ raise RuntimeError("Never be here.")
+
+ for i, v in enumerate(df_dx):
+ J_transposed[i] = v
+
+ if m == 1:
+ J_transposed = np.ravel(J_transposed)
+
+ return J_transposed.T, nfev
+
+
+def _sparse_difference(fun, x0, f0, h, use_one_sided,
+ structure, groups, method, workers):
+ m = f0.size
+ n = x0.size
+ row_indices = []
+ col_indices = []
+ fractions = []
+ result_type = xp_result_type(x0, f0, force_floating=True, xp=np)
+
+ n_groups = np.max(groups) + 1
+ nfev = 0
+
+ def e_generator():
+ # Perturb variables which are in the same group simultaneously.
+ for group in range(n_groups):
+ yield np.equal(group, groups)
+
+ def x_generator2():
+ e_gen = e_generator()
+ for e in e_gen:
+ h_vec = h * e
+ x = x0 + h_vec
+ yield x
+
+ def x_generator3():
+ e_gen = e_generator()
+ for e in e_gen:
+ h_vec = h * e
+ x1 = x0.copy()
+ x2 = x0.copy()
+
+ mask_1 = use_one_sided & e
+ x1[mask_1] += h_vec[mask_1]
+ x2[mask_1] += 2 * h_vec[mask_1]
+
+ mask_2 = ~use_one_sided & e
+ x1[mask_2] -= h_vec[mask_2]
+ x2[mask_2] += h_vec[mask_2]
+ yield x1
+ yield x2
+
+ def x_generator_cs():
+ e_gen = e_generator()
+ for e in e_gen:
+ h_vec = h * e
+ yield x0 + h_vec * 1.j
+
+ # evaluate the function for each of the groups
+ if method == '2-point':
+ f_evals = iter(workers(fun, x_generator2()))
+ xs = x_generator2()
+ elif method == '3-point':
+ f_evals = iter(workers(fun, x_generator3()))
+ xs = x_generator3()
+ elif method == 'cs':
+ f_evals = iter(workers(fun, x_generator_cs()))
+
+ for e in e_generator():
+ # The result is written to columns which correspond to perturbed
+ # variables.
+ cols, = np.nonzero(e)
+ # Find all non-zero elements in selected columns of Jacobian.
+ i, j, _ = find(structure[:, cols])
+ # Restore column indices in the full array.
+ j = cols[j]
+
+ if method == '2-point':
+ dx = next(xs) - x0
+ df = next(f_evals) - f0
+ nfev += 1
+ elif method == '3-point':
+ # Here we do conceptually the same but separate one-sided
+ # and two-sided schemes.
+ x1 = next(xs)
+ x2 = next(xs)
+
+ mask_1 = use_one_sided & e
+ mask_2 = ~use_one_sided & e
+
+ dx = np.zeros(n, dtype=x0.dtype)
+ dx[mask_1] = x2[mask_1] - x0[mask_1]
+ dx[mask_2] = x2[mask_2] - x1[mask_2]
+
+ f1 = next(f_evals)
+ f2 = next(f_evals)
+ nfev += 2
+
+ mask = use_one_sided[j]
+ df = np.empty(m, dtype=f0.dtype)
+
+ rows = i[mask]
+ df[rows] = -3 * f0[rows] + 4 * f1[rows] - f2[rows]
+
+ rows = i[~mask]
+ df[rows] = f2[rows] - f1[rows]
+ elif method == 'cs':
+ f1 = next(f_evals)
+ nfev += 1
+ df = f1.imag
+ dx = h * e
+ else:
+ raise ValueError("Never be here.")
+
+ # All that's left is to compute the fraction. We store i, j and
+ # fractions as separate arrays and later construct csr_array.
+ row_indices.append(i)
+ col_indices.append(j)
+ fractions.append(df[i] / dx[j])
+
+ row_indices = np.hstack(row_indices)
+ col_indices = np.hstack(col_indices)
+ fractions = np.hstack(fractions)
+
+ if isinstance(structure, spmatrix):
+ return csr_matrix(
+ (fractions, (row_indices, col_indices)),
+ shape=(m, n),
+ dtype=result_type
+ ), nfev
+ return csr_array(
+ (fractions, (row_indices, col_indices)),
+ shape=(m, n),
+ dtype=result_type
+ ), nfev
+
+
+class _Fun_Wrapper:
+ # Permits pickling of a wrapped function
+ def __init__(self, fun, x0, args, kwargs):
+ self.fun = fun
+ self.x0 = x0
+ self.args = args
+ self.kwargs = kwargs
+
+ def __call__(self, x):
+ # send user function same fp type as x0. (but only if cs is not being
+ # used
+ xp = array_namespace(self.x0)
+
+ if xp.isdtype(x.dtype, "real floating"):
+ x = xp.astype(x, self.x0.dtype)
+
+ f = np.atleast_1d(self.fun(x, *self.args, **self.kwargs))
+ if f.ndim > 1:
+ raise RuntimeError("`fun` return value has "
+ "more than 1 dimension.")
+ return f
+
+
+def check_derivative(fun, jac, x0, bounds=(-np.inf, np.inf), args=(),
+ kwargs=None):
+ """Check correctness of a function computing derivatives (Jacobian or
+ gradient) by comparison with a finite difference approximation.
+
+ Parameters
+ ----------
+ fun : callable
+ Function of which to estimate the derivatives. The argument x
+ passed to this function is ndarray of shape (n,) (never a scalar
+ even if n=1). It must return 1-D array_like of shape (m,) or a scalar.
+ jac : callable
+ Function which computes Jacobian matrix of `fun`. It must work with
+ argument x the same way as `fun`. The return value must be array_like
+ or sparse array with an appropriate shape.
+ x0 : array_like of shape (n,) or float
+ Point at which to estimate the derivatives. Float will be converted
+ to 1-D array.
+ bounds : 2-tuple of array_like, optional
+ Lower and upper bounds on independent variables. Defaults to no bounds.
+ Each bound must match the size of `x0` or be a scalar, in the latter
+ case the bound will be the same for all variables. Use it to limit the
+ range of function evaluation.
+ args, kwargs : tuple and dict, optional
+ Additional arguments passed to `fun` and `jac`. Both empty by default.
+ The calling signature is ``fun(x, *args, **kwargs)`` and the same
+ for `jac`.
+
+ Returns
+ -------
+ accuracy : float
+ The maximum among all relative errors for elements with absolute values
+ higher than 1 and absolute errors for elements with absolute values
+ less or equal than 1. If `accuracy` is on the order of 1e-6 or lower,
+ then it is likely that your `jac` implementation is correct.
+
+ See Also
+ --------
+ approx_derivative : Compute finite difference approximation of derivative.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize._numdiff import check_derivative
+ >>>
+ >>>
+ >>> def f(x, c1, c2):
+ ... return np.array([x[0] * np.sin(c1 * x[1]),
+ ... x[0] * np.cos(c2 * x[1])])
+ ...
+ >>> def jac(x, c1, c2):
+ ... return np.array([
+ ... [np.sin(c1 * x[1]), c1 * x[0] * np.cos(c1 * x[1])],
+ ... [np.cos(c2 * x[1]), -c2 * x[0] * np.sin(c2 * x[1])]
+ ... ])
+ ...
+ >>>
+ >>> x0 = np.array([1.0, 0.5 * np.pi])
+ >>> check_derivative(f, jac, x0, args=(1, 2))
+ 2.4492935982947064e-16
+ """
+ if kwargs is None:
+ kwargs = {}
+ J_to_test = jac(x0, *args, **kwargs)
+ if issparse(J_to_test):
+ J_diff = approx_derivative(fun, x0, bounds=bounds, sparsity=J_to_test,
+ args=args, kwargs=kwargs)
+ J_to_test = csr_array(J_to_test)
+ abs_err = J_to_test - J_diff
+ i, j, abs_err_data = find(abs_err)
+ J_diff_data = np.asarray(J_diff[i, j]).ravel()
+ return np.max(np.abs(abs_err_data) /
+ np.maximum(1, np.abs(J_diff_data)))
+ else:
+ J_diff = approx_derivative(fun, x0, bounds=bounds,
+ args=args, kwargs=kwargs)
+ abs_err = np.abs(J_to_test - J_diff)
+ return np.max(abs_err / np.maximum(1, np.abs(J_diff)))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_optimize.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..47fbd2320eec85ad30ed42354a290e1ba49fad6b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_optimize.py
@@ -0,0 +1,4169 @@
+#__docformat__ = "restructuredtext en"
+# ******NOTICE***************
+# optimize.py module by Travis E. Oliphant
+#
+# You may copy and use this module as you see fit with no
+# guarantee implied provided you keep this notice in all copies.
+# *****END NOTICE************
+
+# A collection of optimization algorithms. Version 0.5
+# CHANGES
+# Added fminbound (July 2001)
+# Added brute (Aug. 2002)
+# Finished line search satisfying strong Wolfe conditions (Mar. 2004)
+# Updated strong Wolfe conditions line search to use
+# cubic-interpolation (Mar. 2004)
+
+
+# Minimization routines
+
+__all__ = ['fmin', 'fmin_powell', 'fmin_bfgs', 'fmin_ncg', 'fmin_cg',
+ 'fminbound', 'brent', 'golden', 'bracket', 'rosen', 'rosen_der',
+ 'rosen_hess', 'rosen_hess_prod', 'brute', 'approx_fprime',
+ 'line_search', 'check_grad', 'OptimizeResult', 'show_options',
+ 'OptimizeWarning']
+
+__docformat__ = "restructuredtext en"
+
+import math
+import warnings
+import sys
+from numpy import eye, argmin, zeros, shape, asarray, sqrt
+import numpy as np
+from scipy.linalg import cholesky, issymmetric, LinAlgError
+from scipy.sparse.linalg import LinearOperator
+from ._linesearch import (line_search_wolfe1, line_search_wolfe2,
+ line_search_wolfe2 as line_search,
+ LineSearchWarning)
+from ._numdiff import approx_derivative
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+from scipy._lib._util import (MapWrapper, check_random_state, _RichResult,
+ _call_callback_maybe_halt, _transition_to_rng,
+ wrapped_inspect_signature)
+from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS
+from scipy._lib._array_api import array_namespace, xp_capabilities, xp_promote
+from scipy._external import array_api_extra as xpx
+
+
+# standard status messages of optimizers
+_status_message = {'success': 'Optimization terminated successfully.',
+ 'maxfev': 'Maximum number of function evaluations has '
+ 'been exceeded.',
+ 'maxiter': 'Maximum number of iterations has been '
+ 'exceeded.',
+ 'pr_loss': 'Desired error not necessarily achieved due '
+ 'to precision loss.',
+ 'nan': 'NaN result encountered.',
+ 'out_of_bounds': 'The result is outside of the provided '
+ 'bounds.'}
+
+
+class MemoizeJac:
+ """Decorator that caches the return values of a function returning ``(fun, grad)``
+ each time it is called."""
+
+ def __init__(self, fun):
+ self.fun = fun
+ self.jac = None
+ self._value = None
+ self.x = None
+
+ def _compute_if_needed(self, x, *args):
+ if not np.all(x == self.x) or self._value is None or self.jac is None:
+ self.x = np.asarray(x).copy()
+ fg = self.fun(x, *args)
+ self.jac = fg[1]
+ self._value = fg[0]
+
+ def __call__(self, x, *args):
+ """ returns the function value """
+ self._compute_if_needed(x, *args)
+ return self._value
+
+ def derivative(self, x, *args):
+ self._compute_if_needed(x, *args)
+ return self.jac
+
+
+def _wrap_callback(callback, method=None):
+ """Wrap a user-provided callback so that attributes can be attached."""
+ if callback is None or method in {'tnc', 'cobyla', 'cobyqa'}:
+ return callback # don't wrap
+
+ sig = wrapped_inspect_signature(callback)
+
+ if set(sig.parameters) == {'intermediate_result'}:
+ def wrapped_callback(res):
+ return callback(intermediate_result=res)
+ elif method == 'trust-constr':
+ def wrapped_callback(res):
+ return callback(np.copy(res.x), res)
+ elif method == 'differential_evolution':
+ def wrapped_callback(res):
+ return callback(np.copy(res.x), res.convergence)
+ else:
+ def wrapped_callback(res):
+ return callback(np.copy(res.x))
+
+ wrapped_callback.stop_iteration = False
+ return wrapped_callback
+
+
+class OptimizeResult(_RichResult):
+ """
+ Represents the optimization result.
+
+ Attributes
+ ----------
+ x : ndarray
+ The solution of the optimization.
+ success : bool
+ Whether or not the optimizer exited successfully.
+ status : int
+ Termination status of the optimizer. Its value depends on the
+ underlying solver. Refer to `message` for details.
+ message : str
+ Description of the cause of the termination.
+ fun : float
+ Value of objective function at `x`.
+ jac, hess : ndarray
+ Values of objective function's Jacobian and its Hessian at `x` (if
+ available). The Hessian may be an approximation, see the documentation
+ of the function in question.
+ hess_inv : object
+ Inverse of the objective function's Hessian; may be an approximation.
+ Not available for all solvers. The type of this attribute may be
+ either np.ndarray or scipy.sparse.linalg.LinearOperator.
+ nfev, njev, nhev : int
+ Number of evaluations of the objective functions and of its
+ Jacobian and Hessian.
+ nit : int
+ Number of iterations performed by the optimizer.
+ maxcv : float
+ The maximum constraint violation.
+
+ Notes
+ -----
+ Depending on the specific solver being used, `OptimizeResult` may
+ not have all attributes listed here, and they may have additional
+ attributes not listed here. Since this class is essentially a
+ subclass of dict with attribute accessors, one can see which
+ attributes are available using the `OptimizeResult.keys` method.
+
+ """
+ pass
+
+
+class OptimizeWarning(UserWarning):
+ """General warning for :mod:`scipy.optimize`."""
+ pass
+
+def _check_positive_definite(Hk):
+ def is_pos_def(A):
+ if issymmetric(A):
+ try:
+ cholesky(A)
+ return True
+ except LinAlgError:
+ return False
+ else:
+ return False
+ if Hk is not None:
+ if not is_pos_def(Hk):
+ raise ValueError("'hess_inv0' matrix isn't positive definite.")
+
+
+def _check_unknown_options(unknown_options):
+ if unknown_options:
+ msg = ", ".join(map(str, unknown_options.keys()))
+ # Stack level 4: this is called from _minimize_*, which is
+ # called from another function in SciPy. Level 4 is the first
+ # level in user code.
+ warnings.warn(f"Unknown solver options: {msg}", OptimizeWarning, stacklevel=4)
+
+
+def is_finite_scalar(x):
+ """Test whether `x` is either a finite scalar or a finite array scalar.
+
+ """
+ return np.size(x) == 1 and np.isfinite(x)
+
+
+_epsilon = sqrt(np.finfo(float).eps)
+
+
+def vecnorm(x, ord=2):
+ if ord == np.inf:
+ return np.amax(np.abs(x))
+ elif ord == -np.inf:
+ return np.amin(np.abs(x))
+ else:
+ return np.sum(np.abs(x)**ord, axis=0)**(1.0 / ord)
+
+
+def _prepare_scalar_function(fun, x0, jac=None, args=(), bounds=None,
+ epsilon=None, finite_diff_rel_step=None,
+ hess=None, workers=None):
+ """
+ Creates a ScalarFunction object for use with scalar minimizers
+ (BFGS/LBFGSB/SLSQP/TNC/CG/etc).
+
+ Parameters
+ ----------
+ fun : callable
+ The objective function to be minimized.
+
+ ``fun(x, *args) -> float``
+
+ where ``x`` is a 1-D array with shape (n,) and ``args``
+ is a tuple of the fixed parameters needed to completely
+ specify the function.
+ x0 : ndarray, shape (n,)
+ Initial guess. Array of real elements of size (n,),
+ where 'n' is the number of independent variables.
+ jac : {callable, '2-point', '3-point', 'cs', None}, optional
+ Method for computing the gradient vector. If it is a callable, it
+ should be a function that returns the gradient vector:
+
+ ``jac(x, *args) -> array_like, shape (n,)``
+
+ If one of `{'2-point', '3-point', 'cs'}` is selected then the gradient
+ is calculated with a relative step for finite differences. If `None`,
+ then two-point finite differences with an absolute step is used.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its
+ derivatives (`fun`, `jac` functions).
+ bounds : sequence, optional
+ Bounds on variables. 'new-style' bounds are required.
+ eps : float or ndarray
+ If ``jac is None`` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``,
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ hess : {callable, '2-point', '3-point', 'cs', None}
+ Computes the Hessian matrix. If it is callable, it should return the
+ Hessian matrix:
+
+ ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``
+
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} select a
+ finite difference scheme for numerical estimation.
+ Whenever the gradient is estimated via finite-differences, the Hessian
+ cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
+ to be estimated using one of the quasi-Newton strategies.
+ workers : int or map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``, or
+ ``workers(grad, iterable)``, depending on what is being numerically
+ differentiated.
+ Alternatively, if `workers` is an int the task is subdivided into `workers`
+ sections and the function evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ It is recommended that a map-like be used instead of int, as repeated
+ calls to `approx_derivative` will incur large overhead from setting up
+ new processes.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ sf : ScalarFunction
+ """
+ if callable(jac):
+ grad = jac
+ elif jac in FD_METHODS:
+ # epsilon is set to None so that ScalarFunction is made to use
+ # rel_step
+ epsilon = None
+ grad = jac
+ else:
+ # default (jac is None) is to do 2-point finite differences with
+ # absolute step size. ScalarFunction has to be provided an
+ # epsilon value that is not None to use absolute steps. This is
+ # normally the case from most _minimize* methods.
+ grad = '2-point'
+ epsilon = epsilon
+
+ if hess is None:
+ # ScalarFunction requires something for hess, so we give a dummy
+ # implementation here if nothing is provided, return a value of None
+ # so that downstream minimisers halt. The results of `fun.hess`
+ # should not be used.
+ def hess(x, *args):
+ return None
+
+ if bounds is None:
+ bounds = (-np.inf, np.inf)
+
+ # normalize workers
+ workers = workers or map
+
+ # ScalarFunction caches. Reuse of fun(x) during grad
+ # calculation reduces overall function evaluations.
+ sf = ScalarFunction(fun, x0, args, grad, hess,
+ finite_diff_rel_step, bounds, epsilon=epsilon,
+ workers=workers)
+
+ return sf
+
+
+def _clip_x_for_func(func, bounds):
+ # ensures that x values sent to func are clipped to bounds
+
+ # this is used as a mitigation for gh11403, slsqp/tnc sometimes
+ # suggest a move that is outside the limits by 1 or 2 ULP. This
+ # unclean fix makes sure x is strictly within bounds.
+ def eval(x):
+ x = _check_clip_x(x, bounds)
+ return func(x)
+
+ return eval
+
+
+def _check_clip_x(x, bounds):
+ if (x < bounds[0]).any() or (x > bounds[1]).any():
+ warnings.warn("Values in x were outside bounds during a "
+ "minimize step, clipping to bounds",
+ RuntimeWarning, stacklevel=3)
+ x = np.clip(x, bounds[0], bounds[1])
+ return x
+
+ return x
+
+
+@xp_capabilities()
+def rosen(x):
+ """
+ The Rosenbrock function.
+
+ The function computed is::
+
+ sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the Rosenbrock function is to be computed.
+
+ Returns
+ -------
+ f : float
+ The value of the Rosenbrock function.
+
+ See Also
+ --------
+ rosen_der, rosen_hess, rosen_hess_prod
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen
+ >>> X = 0.1 * np.arange(10)
+ >>> rosen(X)
+ 76.56
+
+ For higher-dimensional input ``rosen`` broadcasts.
+ In the following example, we use this to plot a 2D landscape.
+ Note that ``rosen_hess`` does not broadcast in this manner.
+
+ >>> import matplotlib.pyplot as plt
+ >>> from mpl_toolkits.mplot3d import Axes3D
+ >>> x = np.linspace(-1, 1, 50)
+ >>> X, Y = np.meshgrid(x, x)
+ >>> ax = plt.subplot(111, projection='3d')
+ >>> ax.plot_surface(X, Y, rosen([X, Y]))
+ >>> plt.show()
+ """
+ xp = array_namespace(x)
+ x = xp_promote(x, force_floating=True, xp=xp)
+ r = xp.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
+ axis=0, dtype=x.dtype)
+ return r
+
+
+@xp_capabilities(skip_backends=[('jax.numpy', "JAX doesn't allow item assignment.")])
+def rosen_der(x):
+ """
+ The derivative (i.e. gradient) of the Rosenbrock function.
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the derivative is to be computed.
+
+ Returns
+ -------
+ rosen_der : (N,) ndarray
+ The gradient of the Rosenbrock function at `x`.
+
+ See Also
+ --------
+ rosen, rosen_hess, rosen_hess_prod
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen_der
+ >>> X = 0.1 * np.arange(9)
+ >>> rosen_der(X)
+ array([ -2. , 10.6, 15.6, 13.4, 6.4, -3. , -12.4, -19.4, 62. ])
+
+ """
+ xp = array_namespace(x)
+ x = xp_promote(x, force_floating=True, xp=xp)
+ xm = x[1:-1]
+ xm_m1 = x[:-2]
+ xm_p1 = x[2:]
+ der = xp.zeros_like(x)
+ der[1:-1] = (200 * (xm - xm_m1**2) -
+ 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
+ der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
+ der[-1] = 200 * (x[-1] - x[-2]**2)
+ return der
+
+
+@xp_capabilities()
+def rosen_hess(x):
+ """
+ The Hessian matrix of the Rosenbrock function.
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the Hessian matrix is to be computed.
+
+ Returns
+ -------
+ rosen_hess : ndarray
+ The Hessian matrix of the Rosenbrock function at `x`.
+
+ See Also
+ --------
+ rosen, rosen_der, rosen_hess_prod
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen_hess
+ >>> X = 0.1 * np.arange(4)
+ >>> rosen_hess(X)
+ array([[-38., 0., 0., 0.],
+ [ 0., 134., -40., 0.],
+ [ 0., -40., 130., -80.],
+ [ 0., 0., -80., 200.]])
+
+ """
+ xp = array_namespace(x)
+ x = xp_promote(x, force_floating=True, xp=xp)
+
+ H = (xpx.create_diagonal(-400 * x[:-1], offset=1, xp=xp)
+ - xpx.create_diagonal(400 * x[:-1], offset=-1, xp=xp))
+ diagonal = xp.zeros(x.shape[0], dtype=x.dtype)
+ diagonal = xpx.at(diagonal)[0].set(1200 * x[0]**2 - 400 * x[1] + 2)
+ diagonal = xpx.at(diagonal)[-1].set(200)
+ diagonal = xpx.at(diagonal)[1:-1].set(202 + 1200 * x[1:-1]**2 - 400 * x[2:])
+ return H + xpx.create_diagonal(diagonal, xp=xp)
+
+
+@xp_capabilities(skip_backends=[('jax.numpy', "JAX doesn't allow item assignment.")])
+def rosen_hess_prod(x, p):
+ """
+ Product of the Hessian matrix of the Rosenbrock function with a vector.
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the Hessian matrix is to be computed.
+ p : array_like
+ 1-D array, the vector to be multiplied by the Hessian matrix.
+
+ Returns
+ -------
+ rosen_hess_prod : ndarray
+ The Hessian matrix of the Rosenbrock function at `x` multiplied
+ by the vector `p`.
+
+ See Also
+ --------
+ rosen, rosen_der, rosen_hess
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen_hess_prod
+ >>> X = 0.1 * np.arange(9)
+ >>> p = 0.5 * np.arange(9)
+ >>> rosen_hess_prod(X, p)
+ array([ -0., 27., -10., -95., -192., -265., -278., -195., -180.])
+
+ """
+ xp = array_namespace(x, p)
+ x = xp_promote(x, force_floating=True, xp=xp)
+ x = xpx.atleast_nd(x, ndim=1, xp=xp)
+ p = xp.asarray(p, dtype=x.dtype)
+ Hp = xp.zeros(x.shape[0], dtype=x.dtype)
+ Hp[0] = (1200 * x[0]**2 - 400 * x[1] + 2) * p[0] - 400 * x[0] * p[1]
+ Hp[1:-1] = (-400 * x[:-2] * p[:-2] +
+ (202 + 1200 * x[1:-1]**2 - 400 * x[2:]) * p[1:-1] -
+ 400 * x[1:-1] * p[2:])
+ Hp[-1] = -400 * x[-2] * p[-2] + 200*p[-1]
+ return Hp
+
+
+def _wrap_scalar_function(function, args):
+ # wraps a minimizer function to count number of evaluations
+ # and to easily provide an args kwd.
+ ncalls = [0]
+ if function is None:
+ return ncalls, None
+
+ def function_wrapper(x, *wrapper_args):
+ ncalls[0] += 1
+ # A copy of x is sent to the user function (gh13740)
+ fx = function(np.copy(x), *(wrapper_args + args))
+ # Ideally, we'd like to a have a true scalar returned from f(x). For
+ # backwards-compatibility, also allow np.array([1.3]), np.array([[1.3]]) etc.
+ if not np.isscalar(fx):
+ _dt = getattr(fx, "dtype", np.float64)
+ try:
+ fx = _dt.type(np.asarray(fx).item())
+ except (TypeError, ValueError) as e:
+ raise ValueError("The user-provided objective function "
+ "must return a scalar value.") from e
+ return fx
+
+ return ncalls, function_wrapper
+
+
+class _MaxFuncCallError(RuntimeError):
+ pass
+
+
+def _wrap_scalar_function_maxfun_validation(function, args, maxfun):
+ # wraps a minimizer function to count number of evaluations
+ # and to easily provide an args kwd.
+ ncalls = [0]
+ if function is None:
+ return ncalls, None
+
+ def function_wrapper(x, *wrapper_args):
+ if ncalls[0] >= maxfun:
+ raise _MaxFuncCallError("Too many function calls")
+ ncalls[0] += 1
+ # A copy of x is sent to the user function (gh13740)
+ fx = function(np.copy(x), *(wrapper_args + args))
+ # Ideally, we'd like to a have a true scalar returned from f(x). For
+ # backwards-compatibility, also allow np.array([1.3]),
+ # np.array([[1.3]]) etc.
+ if not np.isscalar(fx):
+ _dt = getattr(fx, "dtype", np.dtype(np.float64))
+ try:
+ fx = _dt.type(np.asarray(fx).item())
+ except (TypeError, ValueError) as e:
+ raise ValueError("The user-provided objective function "
+ "must return a scalar value.") from e
+ return fx
+
+ return ncalls, function_wrapper
+
+
+def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None,
+ full_output=0, disp=1, retall=0, callback=None, initial_simplex=None):
+ """
+ Minimize a function using the downhill simplex algorithm.
+
+ This algorithm only uses function values, not derivatives or second
+ derivatives.
+
+ Parameters
+ ----------
+ func : callable func(x,*args)
+ The objective function to be minimized.
+ x0 : ndarray
+ Initial guess.
+ args : tuple, optional
+ Extra arguments passed to func, i.e., ``f(x,*args)``.
+ xtol : float, optional
+ Absolute error in xopt between iterations that is acceptable for
+ convergence.
+ ftol : number, optional
+ Absolute error in func(xopt) between iterations that is acceptable for
+ convergence.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ maxfun : number, optional
+ Maximum number of function evaluations to make.
+ full_output : bool, optional
+ Set to True if fopt and warnflag outputs are desired.
+ disp : bool, optional
+ Set to True to print convergence messages.
+ retall : bool, optional
+ Set to True to return list of solutions at each iteration.
+ callback : callable, optional
+ Called after each iteration, as callback(xk), where xk is the
+ current parameter vector.
+ initial_simplex : array_like of shape (N + 1, N), optional
+ Initial simplex. If given, overrides `x0`.
+ ``initial_simplex[j,:]`` should contain the coordinates of
+ the jth vertex of the ``N+1`` vertices in the simplex, where
+ ``N`` is the dimension.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameter that minimizes function.
+ fopt : float
+ Value of function at minimum: ``fopt = func(xopt)``.
+ iter : int
+ Number of iterations performed.
+ funcalls : int
+ Number of function calls made.
+ warnflag : int
+ 1 : Maximum number of function evaluations made.
+ 2 : Maximum number of iterations reached.
+ allvecs : list
+ Solution at each iteration.
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'Nelder-Mead' `method` in particular.
+
+ Notes
+ -----
+ Uses a Nelder-Mead simplex algorithm to find the minimum of function of
+ one or more variables.
+
+ This algorithm has a long history of successful use in applications.
+ But it will usually be slower than an algorithm that uses first or
+ second derivative information. In practice, it can have poor
+ performance in high-dimensional problems and is not robust to
+ minimizing complicated functions. Additionally, there currently is no
+ complete theory describing when the algorithm will successfully
+ converge to the minimum, or how fast it will if it does. Both the ftol and
+ xtol criteria must be met for convergence.
+
+ References
+ ----------
+ .. [1] Nelder, J.A. and Mead, R. (1965), "A simplex method for function
+ minimization", The Computer Journal, 7, pp. 308-313
+
+ .. [2] Wright, M.H. (1996), "Direct Search Methods: Once Scorned, Now
+ Respectable", in Numerical Analysis 1995, Proceedings of the
+ 1995 Dundee Biennial Conference in Numerical Analysis, D.F.
+ Griffiths and G.A. Watson (Eds.), Addison Wesley Longman,
+ Harlow, UK, pp. 191-208.
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return x**2
+
+ >>> from scipy import optimize
+
+ >>> minimum = optimize.fmin(f, 1)
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 17
+ Function evaluations: 34
+ >>> minimum[0]
+ -8.8817841970012523e-16
+ """
+ opts = {'xatol': xtol,
+ 'fatol': ftol,
+ 'maxiter': maxiter,
+ 'maxfev': maxfun,
+ 'disp': disp,
+ 'return_all': retall,
+ 'initial_simplex': initial_simplex}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
+ if full_output:
+ retlist = res['x'], res['fun'], res['nit'], res['nfev'], res['status']
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_neldermead(func, x0, args=(), callback=None,
+ maxiter=None, maxfev=None, disp=False,
+ return_all=False, initial_simplex=None,
+ xatol=1e-4, fatol=1e-4, adaptive=False, bounds=None,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ Nelder-Mead algorithm.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ maxiter, maxfev : int
+ Maximum allowed number of iterations and function evaluations.
+ Will default to ``N*200``, where ``N`` is the number of
+ variables, if neither `maxiter` or `maxfev` is set. If both
+ `maxiter` and `maxfev` are set, minimization will stop at the
+ first reached.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ initial_simplex : array_like of shape (N + 1, N)
+ Initial simplex. If given, overrides `x0`.
+ ``initial_simplex[j,:]`` should contain the coordinates of
+ the jth vertex of the ``N+1`` vertices in the simplex, where
+ ``N`` is the dimension.
+ xatol : float, optional
+ Absolute error in xopt between iterations that is acceptable for
+ convergence.
+ fatol : number, optional
+ Absolute error in func(xopt) between iterations that is acceptable for
+ convergence.
+ adaptive : bool, optional
+ Adapt algorithm parameters to dimensionality of problem. Useful for
+ high-dimensional minimization [1]_.
+ bounds : sequence or `Bounds`, optional
+ Bounds on variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
+ is used to specify no bound.
+
+ Note that this just clips all vertices in simplex based on
+ the bounds.
+
+ References
+ ----------
+ .. [1] Gao, F. and Han, L.
+ Implementing the Nelder-Mead simplex algorithm with adaptive
+ parameters. 2012. Computational Optimization and Applications.
+ 51:1, pp. 259-277
+
+ """
+ _check_unknown_options(unknown_options)
+ maxfun = maxfev
+ retall = return_all
+
+ x0 = np.atleast_1d(x0).flatten()
+ dtype = x0.dtype if np.issubdtype(x0.dtype, np.inexact) else np.float64
+ x0 = np.asarray(x0, dtype=dtype)
+
+ if adaptive:
+ dim = float(len(x0))
+ rho = 1
+ chi = 1 + 2/dim
+ psi = 0.75 - 1/(2*dim)
+ sigma = 1 - 1/dim
+ else:
+ rho = 1
+ chi = 2
+ psi = 0.5
+ sigma = 0.5
+
+ nonzdelt = 0.05
+ zdelt = 0.00025
+
+ if bounds is not None:
+ lower_bound, upper_bound = bounds.lb, bounds.ub
+ # check bounds
+ if (lower_bound > upper_bound).any():
+ raise ValueError("Nelder Mead - one of the lower bounds "
+ "is greater than an upper bound.")
+ if np.any(lower_bound > x0) or np.any(x0 > upper_bound):
+ warnings.warn("Initial guess is not within the specified bounds",
+ OptimizeWarning, stacklevel=3)
+
+ if bounds is not None:
+ x0 = np.clip(x0, lower_bound, upper_bound)
+
+ if initial_simplex is None:
+ N = len(x0)
+
+ sim = np.empty((N + 1, N), dtype=x0.dtype)
+ sim[0] = x0
+ for k in range(N):
+ y = np.array(x0, copy=True)
+ if y[k] != 0:
+ y[k] = (1 + nonzdelt)*y[k]
+ else:
+ y[k] = zdelt
+ sim[k + 1] = y
+ else:
+ sim = np.atleast_2d(initial_simplex).copy()
+ dtype = sim.dtype if np.issubdtype(sim.dtype, np.inexact) else np.float64
+ sim = np.asarray(sim, dtype=dtype)
+ if sim.ndim != 2 or sim.shape[0] != sim.shape[1] + 1:
+ raise ValueError("`initial_simplex` should be an array of shape (N+1,N)")
+ if len(x0) != sim.shape[1]:
+ raise ValueError("Size of `initial_simplex` is not consistent with `x0`")
+ N = sim.shape[1]
+
+ if retall:
+ allvecs = [sim[0]]
+
+ # If neither are set, then set both to default
+ if maxiter is None and maxfun is None:
+ maxiter = N * 200
+ maxfun = N * 200
+ elif maxiter is None:
+ # Convert remaining Nones, to np.inf, unless the other is np.inf, in
+ # which case use the default to avoid unbounded iteration
+ if maxfun == np.inf:
+ maxiter = N * 200
+ else:
+ maxiter = np.inf
+ elif maxfun is None:
+ if maxiter == np.inf:
+ maxfun = N * 200
+ else:
+ maxfun = np.inf
+
+ if bounds is not None:
+ # The default simplex construction may make all entries (for a given
+ # parameter) greater than an upper bound if x0 is very close to the
+ # upper bound. If one simply clips the simplex to the bounds this could
+ # make the simplex entries degenerate. If that occurs reflect into the
+ # interior.
+ msk = sim > upper_bound
+ # reflect into the interior
+ sim = np.where(msk, 2*upper_bound - sim, sim)
+ # but make sure the reflection is no less than the lower_bound
+ sim = np.clip(sim, lower_bound, upper_bound)
+
+ one2np1 = list(range(1, N + 1))
+ fsim = np.full((N + 1,), np.inf, dtype=float)
+
+ fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun)
+
+ try:
+ for k in range(N + 1):
+ fsim[k] = func(sim[k])
+ except _MaxFuncCallError:
+ pass
+ finally:
+ ind = np.argsort(fsim)
+ sim = np.take(sim, ind, 0)
+ fsim = np.take(fsim, ind, 0)
+
+ ind = np.argsort(fsim)
+ fsim = np.take(fsim, ind, 0)
+ # sort so sim[0,:] has the lowest function value
+ sim = np.take(sim, ind, 0)
+
+ iterations = 1
+
+ while (fcalls[0] < maxfun and iterations < maxiter):
+ try:
+ if (np.max(np.ravel(np.abs(sim[1:] - sim[0]))) <= xatol and
+ np.max(np.abs(fsim[0] - fsim[1:])) <= fatol):
+ break
+
+ xbar = np.add.reduce(sim[:-1], 0) / N
+ xr = (1 + rho) * xbar - rho * sim[-1]
+ if bounds is not None:
+ xr = np.clip(xr, lower_bound, upper_bound)
+ fxr = func(xr)
+ doshrink = 0
+
+ if fxr < fsim[0]:
+ xe = (1 + rho * chi) * xbar - rho * chi * sim[-1]
+ if bounds is not None:
+ xe = np.clip(xe, lower_bound, upper_bound)
+ fxe = func(xe)
+
+ if fxe < fxr:
+ sim[-1] = xe
+ fsim[-1] = fxe
+ else:
+ sim[-1] = xr
+ fsim[-1] = fxr
+ else: # fsim[0] <= fxr
+ if fxr < fsim[-2]:
+ sim[-1] = xr
+ fsim[-1] = fxr
+ else: # fxr >= fsim[-2]
+ # Perform contraction
+ if fxr < fsim[-1]:
+ xc = (1 + psi * rho) * xbar - psi * rho * sim[-1]
+ if bounds is not None:
+ xc = np.clip(xc, lower_bound, upper_bound)
+ fxc = func(xc)
+
+ if fxc <= fxr:
+ sim[-1] = xc
+ fsim[-1] = fxc
+ else:
+ doshrink = 1
+ else:
+ # Perform an inside contraction
+ xcc = (1 - psi) * xbar + psi * sim[-1]
+ if bounds is not None:
+ xcc = np.clip(xcc, lower_bound, upper_bound)
+ fxcc = func(xcc)
+
+ if fxcc < fsim[-1]:
+ sim[-1] = xcc
+ fsim[-1] = fxcc
+ else:
+ doshrink = 1
+
+ if doshrink:
+ for j in one2np1:
+ sim[j] = sim[0] + sigma * (sim[j] - sim[0])
+ if bounds is not None:
+ sim[j] = np.clip(
+ sim[j], lower_bound, upper_bound)
+ fsim[j] = func(sim[j])
+ iterations += 1
+ except _MaxFuncCallError:
+ pass
+ ind = np.argsort(fsim)
+ sim = np.take(sim, ind, 0)
+ fsim = np.take(fsim, ind, 0)
+ if retall:
+ allvecs.append(sim[0])
+ intermediate_result = OptimizeResult(x=sim[0], fun=fsim[0])
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ x = sim[0]
+ fval = np.min(fsim)
+ warnflag = 0
+
+ if fcalls[0] >= maxfun:
+ warnflag = 1
+ msg = _status_message['maxfev']
+ if disp:
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ elif iterations >= maxiter:
+ warnflag = 2
+ msg = _status_message['maxiter']
+ if disp:
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ else:
+ msg = _status_message['success']
+ if disp:
+ print(msg)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {iterations:d}")
+ print(f" Function evaluations: {fcalls[0]:d}")
+
+ result = OptimizeResult(fun=fval, nit=iterations, nfev=fcalls[0],
+ status=warnflag, success=(warnflag == 0),
+ message=msg, x=x, final_simplex=(sim, fsim))
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def approx_fprime(xk, f, epsilon=_epsilon, *args):
+ """Finite difference approximation of the derivatives of a
+ scalar or vector-valued function.
+
+ If a function maps from :math:`R^n` to :math:`R^m`, its derivatives form
+ an m-by-n matrix
+ called the Jacobian, where an element :math:`(i, j)` is a partial
+ derivative of f[i] with respect to ``xk[j]``.
+
+ Parameters
+ ----------
+ xk : array_like
+ The coordinate vector at which to determine the gradient of `f`.
+ f : callable
+ Function of which to estimate the derivatives of. Has the signature
+ ``f(xk, *args)`` where `xk` is the argument in the form of a 1-D array
+ and `args` is a tuple of any additional fixed parameters needed to
+ completely specify the function. The argument `xk` passed to this
+ function is an ndarray of shape (n,) (never a scalar even if n=1).
+ It must return a 1-D array_like of shape (m,) or a scalar.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+
+ .. versionchanged:: 1.9.0
+ `f` is now able to return a 1-D array-like, with the :math:`(m, n)`
+ Jacobian being estimated.
+
+ epsilon : {float, array_like}, optional
+ Increment to `xk` to use for determining the function gradient.
+ If a scalar, uses the same finite difference delta for all partial
+ derivatives. If an array, should contain one value per element of
+ `xk`. Defaults to ``sqrt(np.finfo(float).eps)``, which is approximately
+ 1.49e-08.
+ \\*args : args, optional
+ Any other arguments that are to be passed to `f`.
+
+ Returns
+ -------
+ jac : ndarray
+ The partial derivatives of `f` to `xk`.
+
+ See Also
+ --------
+ check_grad : Check correctness of gradient function against approx_fprime.
+
+ Notes
+ -----
+ The function gradient is determined by the forward finite difference
+ formula::
+
+ f(xk[i] + epsilon[i]) - f(xk[i])
+ f'[i] = ---------------------------------
+ epsilon[i]
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import optimize
+ >>> def func(x, c0, c1):
+ ... "Coordinate vector `x` should be an array of size two."
+ ... return c0 * x[0]**2 + c1*x[1]**2
+
+ >>> x = np.ones(2)
+ >>> c0, c1 = (1, 200)
+ >>> eps = np.sqrt(np.finfo(float).eps)
+ >>> optimize.approx_fprime(x, func, [eps, np.sqrt(200) * eps], c0, c1)
+ array([ 2. , 400.00004208])
+
+ """
+ xk = np.asarray(xk, float)
+ f0 = f(xk, *args)
+
+ return approx_derivative(f, xk, method='2-point', abs_step=epsilon,
+ args=args, f0=f0)
+
+
+@_transition_to_rng("seed", position_num=6)
+def check_grad(func, grad, x0, *args, epsilon=_epsilon, direction='all', rng=None):
+ r"""Check the correctness of a gradient function by comparing it against a
+ (forward) finite-difference approximation of the gradient.
+
+ Parameters
+ ----------
+ func : callable ``func(x0, *args)``
+ Function whose derivative is to be checked.
+ grad : callable ``grad(x0, *args)``
+ Jacobian of `func`.
+ x0 : ndarray
+ Points to check `grad` against forward difference approximation of grad
+ using `func`.
+ *args : optional
+ Extra arguments passed to `func` and `grad`.
+ epsilon : float, optional
+ Step size used for the finite difference approximation. It defaults to
+ ``sqrt(np.finfo(float).eps)``, which is approximately 1.49e-08.
+ direction : str, optional
+ If set to ``'random'``, then gradients along a random vector
+ are used to check `grad` against forward difference approximation
+ using `func`. By default it is ``'all'``, in which case, all
+ the one hot direction vectors are considered to check `grad`.
+ If `func` is a vector valued function then only ``'all'`` can be used.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+ The random numbers generated affect the random vector along which gradients
+ are computed to check ``grad``. Note that `rng` is only used when `direction`
+ argument is set to `'random'`.
+
+ Returns
+ -------
+ err : float
+ The square root of the sum of squares (i.e., the 2-norm) of the
+ difference between ``grad(x0, *args)`` and the finite difference
+ approximation of `grad` using func at the points `x0`.
+
+ See Also
+ --------
+ approx_fprime
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> def func(x):
+ ... return x[0]**2 - 0.5 * x[1]**3
+ >>> def grad(x):
+ ... return [2 * x[0], -1.5 * x[1]**2]
+ >>> from scipy.optimize import check_grad
+ >>> check_grad(func, grad, [1.5, -1.5])
+ 2.9802322387695312e-08 # may vary
+ >>> rng = np.random.default_rng()
+ >>> check_grad(func, grad, [1.5, -1.5],
+ ... direction='random', seed=rng)
+ 2.9802322387695312e-08
+
+ """
+ step = epsilon
+ x0 = np.asarray(x0)
+
+ def g(w, func, x0, v, *args):
+ return func(x0 + w*v, *args)
+
+ if direction == 'random':
+ _grad = np.asanyarray(grad(x0, *args))
+ if _grad.ndim > 1:
+ raise ValueError("'random' can only be used with scalar valued"
+ " func")
+ rng_gen = check_random_state(rng)
+ v = rng_gen.standard_normal(size=(x0.shape))
+ _args = (func, x0, v) + args
+ _func = g
+ vars = np.zeros((1,))
+ analytical_grad = np.dot(_grad, v)
+ elif direction == 'all':
+ _args = args
+ _func = func
+ vars = x0
+ analytical_grad = grad(x0, *args)
+ else:
+ raise ValueError(f"{direction} is not a valid string for "
+ "``direction`` argument")
+
+ return np.sqrt(np.sum(np.abs(
+ (analytical_grad - approx_fprime(vars, _func, step, *_args))**2
+ )))
+
+
+def approx_fhess_p(x0, p, fprime, epsilon, *args):
+ # calculate fprime(x0) first, as this may be cached by ScalarFunction
+ f1 = fprime(*((x0,) + args))
+ f2 = fprime(*((x0 + epsilon*p,) + args))
+ return (f2 - f1) / epsilon
+
+
+class _LineSearchError(RuntimeError):
+ pass
+
+
+def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval,
+ **kwargs):
+ """
+ Same as line_search_wolfe1, but fall back to line_search_wolfe2 if
+ suitable step length is not found, and raise an exception if a
+ suitable step length is not found.
+
+ Raises
+ ------
+ _LineSearchError
+ If no suitable step size is found
+
+ """
+
+ extra_condition = kwargs.pop('extra_condition', None)
+
+ ret = line_search_wolfe1(f, fprime, xk, pk, gfk,
+ old_fval, old_old_fval,
+ **kwargs)
+
+ if ret[0] is not None and extra_condition is not None:
+ xp1 = xk + ret[0] * pk
+ if not extra_condition(ret[0], xp1, ret[3], ret[5]):
+ # Reject step if extra_condition fails
+ ret = (None,)
+
+ if ret[0] is None:
+ # line search failed: try different one.
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', LineSearchWarning)
+ kwargs2 = {}
+ for key in ('c1', 'c2', 'amax'):
+ if key in kwargs:
+ kwargs2[key] = kwargs[key]
+ ret = line_search_wolfe2(f, fprime, xk, pk, gfk,
+ old_fval, old_old_fval,
+ extra_condition=extra_condition,
+ **kwargs2)
+
+ if ret[0] is None:
+ raise _LineSearchError()
+
+ return ret
+
+
+def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf,
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1,
+ retall=0, callback=None, xrtol=0, c1=1e-4, c2=0.9,
+ hess_inv0=None):
+ """
+ Minimize a function using the BFGS algorithm.
+
+ Parameters
+ ----------
+ f : callable ``f(x,*args)``
+ Objective function to be minimized.
+ x0 : ndarray
+ Initial guess, shape (n,)
+ fprime : callable ``f'(x,*args)``, optional
+ Gradient of f.
+ args : tuple, optional
+ Extra arguments passed to f and fprime.
+ gtol : float, optional
+ Terminate successfully if gradient norm is less than `gtol`
+ norm : float, optional
+ Order of norm (Inf is max, -Inf is min)
+ epsilon : int or ndarray, optional
+ If `fprime` is approximated, use this value for the step size.
+ callback : callable, optional
+ An optional user-supplied function to call after each
+ iteration. Called as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ full_output : bool, optional
+ If True, return ``fopt``, ``func_calls``, ``grad_calls``, and
+ ``warnflag`` in addition to ``xopt``.
+ disp : bool, optional
+ Print convergence message if True.
+ retall : bool, optional
+ Return a list of results at each iteration if True.
+ xrtol : float, default: 0
+ Relative tolerance for `x`. Terminate successfully if step
+ size is less than ``xk * xrtol`` where ``xk`` is the current
+ parameter vector.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule.
+ hess_inv0 : None or ndarray, optional``
+ Initial inverse hessian estimate, shape (n, n). If None (default) then
+ the identity matrix is used.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
+ fopt : float
+ Minimum value.
+ gopt : ndarray
+ Value of gradient at minimum, f'(xopt), which should be near 0.
+ Bopt : ndarray
+ Value of 1/f''(xopt), i.e., the inverse Hessian matrix.
+ func_calls : int
+ Number of function_calls made.
+ grad_calls : int
+ Number of gradient calls made.
+ warnflag : int
+ 1 : Maximum number of iterations exceeded.
+ 2 : Gradient and/or function calls not changing.
+ 3 : NaN result encountered.
+ allvecs : list
+ The value of `xopt` at each iteration. Only returned if `retall` is
+ True.
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See ``method='BFGS'`` in particular.
+
+ Notes
+ -----
+ Optimize the function, `f`, whose gradient is given by `fprime`
+ using the quasi-Newton method of Broyden, Fletcher, Goldfarb,
+ and Shanno (BFGS).
+
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ References
+ ----------
+ .. [1] Wright, and Nocedal 'Numerical Optimization', 1999, p. 198.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import fmin_bfgs
+ >>> def quadratic_cost(x, Q):
+ ... return x @ Q @ x
+ ...
+ >>> x0 = np.array([-3, -4])
+ >>> cost_weight = np.diag([1., 10.])
+ >>> # Note that a trailing comma is necessary for a tuple with single element
+ >>> fmin_bfgs(quadratic_cost, x0, args=(cost_weight,))
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 7 # may vary
+ Function evaluations: 24 # may vary
+ Gradient evaluations: 8 # may vary
+ array([ 2.85169950e-06, -4.61820139e-07])
+
+ >>> def quadratic_cost_grad(x, Q):
+ ... return 2 * Q @ x
+ ...
+ >>> fmin_bfgs(quadratic_cost, x0, quadratic_cost_grad, args=(cost_weight,))
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 7
+ Function evaluations: 8
+ Gradient evaluations: 8
+ array([ 2.85916637e-06, -4.54371951e-07])
+
+ """
+ opts = {'gtol': gtol,
+ 'norm': norm,
+ 'eps': epsilon,
+ 'disp': disp,
+ 'maxiter': maxiter,
+ 'return_all': retall,
+ 'xrtol': xrtol,
+ 'c1': c1,
+ 'c2': c2,
+ 'hess_inv0': hess_inv0}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_bfgs(f, x0, args, fprime, callback=callback, **opts)
+
+ if full_output:
+ retlist = (res['x'], res['fun'], res['jac'], res['hess_inv'],
+ res['nfev'], res['njev'], res['status'])
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_bfgs(fun, x0, args=(), jac=None, callback=None,
+ gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None,
+ disp=False, return_all=False, finite_diff_rel_step=None,
+ xrtol=0, c1=1e-4, c2=0.9,
+ hess_inv0=None, workers=None, **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ BFGS algorithm.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ maxiter : int
+ Maximum number of iterations to perform.
+ gtol : float
+ Terminate successfully if gradient norm is less than `gtol`.
+ norm : float
+ Order of norm (Inf is max, -Inf is min).
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ xrtol : float, default: 0
+ Relative tolerance for `x`. Terminate successfully if step size is
+ less than ``xk * xrtol`` where ``xk`` is the current parameter vector.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule.
+ hess_inv0 : None or ndarray, optional
+ Initial inverse hessian estimate, shape (n, n). If None (default) then
+ the identity matrix is used.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ If minimization doesn't complete successfully, with an error message of
+ ``Desired error not necessarily achieved due to precision loss``, then
+ consider setting `gtol` to a higher value. This precision loss typically
+ occurs when the (finite difference) numerical differentiation cannot provide
+ sufficient precision to satisfy the `gtol` termination criterion.
+ This can happen when working in single precision and a callable jac is not
+ provided. For single precision problems a `gtol` of 1e-3 seems to work.
+ """
+ _check_unknown_options(unknown_options)
+ _check_positive_definite(hess_inv0)
+ retall = return_all
+
+ x0 = asarray(x0).flatten()
+ if x0.ndim == 0:
+ x0 = x0.reshape((1,))
+ if maxiter is None:
+ maxiter = len(x0) * 200
+
+ sf = _prepare_scalar_function(fun, x0, jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ workers=workers)
+
+ f = sf.fun
+ myfprime = sf.grad
+
+ old_fval = f(x0)
+ gfk = myfprime(x0)
+
+ k = 0
+ N = len(x0)
+ I = np.eye(N, dtype=int)
+ Hk = I if hess_inv0 is None else hess_inv0
+
+ # Sets the initial step guess to dx ~ 1
+ old_old_fval = old_fval + np.linalg.norm(gfk) / 2
+
+ xk = x0
+ if retall:
+ allvecs = [x0]
+ warnflag = 0
+ gnorm = vecnorm(gfk, ord=norm)
+ while (gnorm > gtol) and (k < maxiter):
+ pk = -np.dot(Hk, gfk)
+ try:
+ alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
+ _line_search_wolfe12(f, myfprime, xk, pk, gfk,
+ old_fval, old_old_fval, amin=1e-100,
+ amax=1e100, c1=c1, c2=c2)
+ except _LineSearchError:
+ # Line search failed to find a better solution.
+ warnflag = 2
+ break
+
+ sk = alpha_k * pk
+ xkp1 = xk + sk
+
+ if retall:
+ allvecs.append(xkp1)
+ xk = xkp1
+ if gfkp1 is None:
+ gfkp1 = myfprime(xkp1)
+
+ yk = gfkp1 - gfk
+ gfk = gfkp1
+ k += 1
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+ gnorm = vecnorm(gfk, ord=norm)
+ if (gnorm <= gtol):
+ break
+
+ # See Chapter 5 in P.E. Frandsen, K. Jonasson, H.B. Nielsen,
+ # O. Tingleff: "Unconstrained Optimization", IMM, DTU. 1999.
+ # These notes are available here:
+ # http://www2.imm.dtu.dk/documents/ftp/publlec.html
+ if (alpha_k*vecnorm(pk) <= xrtol*(xrtol + vecnorm(xk))):
+ break
+
+ if not np.isfinite(old_fval):
+ # We correctly found +-Inf as optimal value, or something went
+ # wrong.
+ warnflag = 2
+ break
+
+ rhok_inv = np.dot(yk, sk)
+ # this was handled in numeric, let it remains for more safety
+ # Cryptic comment above is preserved for posterity. Future reader:
+ # consider change to condition below proposed in gh-1261/gh-17345.
+ if rhok_inv == 0.:
+ rhok = 1000.0
+ if disp:
+ msg = "Divide-by-zero encountered: rhok assumed large"
+ _print_success_message_or_warn(True, msg)
+ else:
+ rhok = 1. / rhok_inv
+
+ A1 = I - sk[:, np.newaxis] * yk[np.newaxis, :] * rhok
+ A2 = I - yk[:, np.newaxis] * sk[np.newaxis, :] * rhok
+ Hk = np.dot(A1, np.dot(Hk, A2)) + (rhok * sk[:, np.newaxis] *
+ sk[np.newaxis, :])
+
+ fval = old_fval
+
+ if warnflag == 2:
+ msg = _status_message['pr_loss']
+ elif k >= maxiter:
+ warnflag = 1
+ msg = _status_message['maxiter']
+ elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any():
+ warnflag = 3
+ msg = _status_message['nan']
+ else:
+ msg = _status_message['success']
+
+ if disp:
+ _print_success_message_or_warn(warnflag, msg)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+
+ result = OptimizeResult(fun=fval, jac=gfk, hess_inv=Hk, nfev=sf.nfev,
+ njev=sf.ngev, status=warnflag,
+ success=(warnflag == 0), message=msg, x=xk,
+ nit=k)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def _print_success_message_or_warn(warnflag, message, warntype=None):
+ if not warnflag:
+ print(message)
+ else:
+ warnings.warn(message, warntype or OptimizeWarning, stacklevel=3)
+
+
+def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf,
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0,
+ callback=None, c1=1e-4, c2=0.4):
+ """
+ Minimize a function using a nonlinear conjugate gradient algorithm.
+
+ Parameters
+ ----------
+ f : callable, ``f(x, *args)``
+ Objective function to be minimized. Here `x` must be a 1-D array of
+ the variables that are to be changed in the search for a minimum, and
+ `args` are the other (fixed) parameters of `f`.
+ x0 : ndarray
+ A user-supplied initial estimate of `xopt`, the optimal value of `x`.
+ It must be a 1-D array of values.
+ fprime : callable, ``fprime(x, *args)``, optional
+ A function that returns the gradient of `f` at `x`. Here `x` and `args`
+ are as described above for `f`. The returned value must be a 1-D array.
+ Defaults to None, in which case the gradient is approximated
+ numerically (see `epsilon`, below).
+ args : tuple, optional
+ Parameter values passed to `f` and `fprime`. Must be supplied whenever
+ additional fixed parameters are needed to completely specify the
+ functions `f` and `fprime`.
+ gtol : float, optional
+ Stop when the norm of the gradient is less than `gtol`.
+ norm : float, optional
+ Order to use for the norm of the gradient
+ (``-np.inf`` is min, ``np.inf`` is max).
+ epsilon : float or ndarray, optional
+ Step size(s) to use when `fprime` is approximated numerically. Can be a
+ scalar or a 1-D array. Defaults to ``sqrt(eps)``, with eps the
+ floating point machine precision. Usually ``sqrt(eps)`` is about
+ 1.5e-8.
+ maxiter : int, optional
+ Maximum number of iterations to perform. Default is ``200 * len(x0)``.
+ full_output : bool, optional
+ If True, return `fopt`, `func_calls`, `grad_calls`, and `warnflag` in
+ addition to `xopt`. See the Returns section below for additional
+ information on optional return values.
+ disp : bool, optional
+ If True, return a convergence message, followed by `xopt`.
+ retall : bool, optional
+ If True, add to the returned values the results of each iteration.
+ callback : callable, optional
+ An optional user-supplied function, called after each iteration.
+ Called as ``callback(xk)``, where ``xk`` is the current value of `x0`.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.4
+ Parameter for curvature condition rule.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
+ fopt : float, optional
+ Minimum value found, f(xopt). Only returned if `full_output` is True.
+ func_calls : int, optional
+ The number of function_calls made. Only returned if `full_output`
+ is True.
+ grad_calls : int, optional
+ The number of gradient calls made. Only returned if `full_output` is
+ True.
+ warnflag : int, optional
+ Integer value with warning status, only returned if `full_output` is
+ True.
+
+ 0 : Success.
+
+ 1 : The maximum number of iterations was exceeded.
+
+ 2 : Gradient and/or function calls were not changing. May indicate
+ that precision was lost, i.e., the routine did not converge.
+
+ 3 : NaN result encountered.
+
+ allvecs : list of ndarray, optional
+ List of arrays, containing the results at each iteration.
+ Only returned if `retall` is True.
+
+ See Also
+ --------
+ minimize : common interface to all `scipy.optimize` algorithms for
+ unconstrained and constrained minimization of multivariate
+ functions. It provides an alternative way to call
+ ``fmin_cg``, by specifying ``method='CG'``.
+
+ Notes
+ -----
+ This conjugate gradient algorithm is based on that of Polak and Ribiere
+ [1]_.
+
+ Conjugate gradient methods tend to work better when:
+
+ 1. `f` has a unique global minimizing point, and no local minima or
+ other stationary points,
+ 2. `f` is, at least locally, reasonably well approximated by a
+ quadratic function of the variables,
+ 3. `f` is continuous and has a continuous gradient,
+ 4. `fprime` is not too large, e.g., has a norm less than 1000,
+ 5. The initial guess, `x0`, is reasonably close to `f` 's global
+ minimizing point, `xopt`.
+
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ References
+ ----------
+ .. [1] Wright & Nocedal, "Numerical Optimization", 1999, pp. 120-122.
+
+ Examples
+ --------
+ Example 1: seek the minimum value of the expression
+ ``a*u**2 + b*u*v + c*v**2 + d*u + e*v + f`` for given values
+ of the parameters and an initial guess ``(u, v) = (0, 0)``.
+
+ >>> import numpy as np
+ >>> args = (2, 3, 7, 8, 9, 10) # parameter values
+ >>> def f(x, *args):
+ ... u, v = x
+ ... a, b, c, d, e, f = args
+ ... return a*u**2 + b*u*v + c*v**2 + d*u + e*v + f
+ >>> def gradf(x, *args):
+ ... u, v = x
+ ... a, b, c, d, e, f = args
+ ... gu = 2*a*u + b*v + d # u-component of the gradient
+ ... gv = b*u + 2*c*v + e # v-component of the gradient
+ ... return np.asarray((gu, gv))
+ >>> x0 = np.asarray((0, 0)) # Initial guess.
+ >>> from scipy import optimize
+ >>> res1 = optimize.fmin_cg(f, x0, fprime=gradf, args=args)
+ Optimization terminated successfully.
+ Current function value: 1.617021
+ Iterations: 4
+ Function evaluations: 8
+ Gradient evaluations: 8
+ >>> res1
+ array([-1.80851064, -0.25531915])
+
+ Example 2: solve the same problem using the `minimize` function.
+ (This `myopts` dictionary shows all of the available options,
+ although in practice only non-default values would be needed.
+ The returned value will be a dictionary.)
+
+ >>> opts = {'maxiter' : None, # default value.
+ ... 'disp' : True, # non-default value.
+ ... 'gtol' : 1e-5, # default value.
+ ... 'norm' : np.inf, # default value.
+ ... 'eps' : 1.4901161193847656e-08} # default value.
+ >>> res2 = optimize.minimize(f, x0, jac=gradf, args=args,
+ ... method='CG', options=opts)
+ Optimization terminated successfully.
+ Current function value: 1.617021
+ Iterations: 4
+ Function evaluations: 8
+ Gradient evaluations: 8
+ >>> res2.x # minimum found
+ array([-1.80851064, -0.25531915])
+
+ """
+ opts = {'gtol': gtol,
+ 'norm': norm,
+ 'eps': epsilon,
+ 'disp': disp,
+ 'maxiter': maxiter,
+ 'return_all': retall}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_cg(f, x0, args, fprime, callback=callback, c1=c1, c2=c2,
+ **opts)
+
+ if full_output:
+ retlist = res['x'], res['fun'], res['nfev'], res['njev'], res['status']
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_cg(fun, x0, args=(), jac=None, callback=None,
+ gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None,
+ disp=False, return_all=False, finite_diff_rel_step=None,
+ c1=1e-4, c2=0.4, workers=None,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ conjugate gradient algorithm.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ maxiter : int
+ Maximum number of iterations to perform.
+ gtol : float
+ Gradient norm must be less than `gtol` before successful
+ termination.
+ norm : float
+ Order of norm (Inf is max, -Inf is min).
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.4
+ Parameter for curvature condition rule.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+ """
+ _check_unknown_options(unknown_options)
+
+ retall = return_all
+
+ x0 = asarray(x0).flatten()
+ if maxiter is None:
+ maxiter = len(x0) * 200
+
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ workers=workers)
+
+ f = sf.fun
+ myfprime = sf.grad
+
+ old_fval = f(x0)
+ gfk = myfprime(x0)
+
+ k = 0
+ xk = x0
+ # Sets the initial step guess to dx ~ 1
+ old_old_fval = old_fval + np.linalg.norm(gfk) / 2
+
+ if retall:
+ allvecs = [xk]
+ warnflag = 0
+ pk = -gfk
+ gnorm = vecnorm(gfk, ord=norm)
+
+ sigma_3 = 0.01
+
+ while (gnorm > gtol) and (k < maxiter):
+ deltak = np.dot(gfk, gfk)
+
+ cached_step = [None]
+
+ def polak_ribiere_powell_step(alpha, gfkp1=None):
+ xkp1 = xk + alpha * pk
+ if gfkp1 is None:
+ gfkp1 = myfprime(xkp1)
+ yk = gfkp1 - gfk
+ beta_k = max(0, np.dot(yk, gfkp1) / deltak)
+ pkp1 = -gfkp1 + beta_k * pk
+ gnorm = vecnorm(gfkp1, ord=norm)
+ return (alpha, xkp1, pkp1, gfkp1, gnorm)
+
+ def descent_condition(alpha, xkp1, fp1, gfkp1):
+ # Polak-Ribiere+ needs an explicit check of a sufficient
+ # descent condition, which is not guaranteed by strong Wolfe.
+ #
+ # See Gilbert & Nocedal, "Global convergence properties of
+ # conjugate gradient methods for optimization",
+ # SIAM J. Optimization 2, 21 (1992).
+ cached_step[:] = polak_ribiere_powell_step(alpha, gfkp1)
+ alpha, xk, pk, gfk, gnorm = cached_step
+
+ # Accept step if it leads to convergence.
+ if gnorm <= gtol:
+ return True
+
+ # Accept step if sufficient descent condition applies.
+ return np.dot(pk, gfk) <= -sigma_3 * np.dot(gfk, gfk)
+
+ try:
+ alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
+ _line_search_wolfe12(f, myfprime, xk, pk, gfk, old_fval,
+ old_old_fval, c1=c1, c2=c2, amin=1e-100,
+ amax=1e100, extra_condition=descent_condition)
+ except _LineSearchError:
+ # Line search failed to find a better solution.
+ warnflag = 2
+ break
+
+ # Reuse already computed results if possible
+ if alpha_k == cached_step[0]:
+ alpha_k, xk, pk, gfk, gnorm = cached_step
+ else:
+ alpha_k, xk, pk, gfk, gnorm = polak_ribiere_powell_step(alpha_k, gfkp1)
+
+ if retall:
+ allvecs.append(xk)
+ k += 1
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ fval = old_fval
+ if warnflag == 2:
+ msg = _status_message['pr_loss']
+ elif k >= maxiter:
+ warnflag = 1
+ msg = _status_message['maxiter']
+ elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any():
+ warnflag = 3
+ msg = _status_message['nan']
+ else:
+ msg = _status_message['success']
+
+ if disp:
+ _print_success_message_or_warn(warnflag, msg)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+
+ result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev,
+ njev=sf.ngev, status=warnflag,
+ success=(warnflag == 0), message=msg, x=xk,
+ nit=k)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5,
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0,
+ callback=None, c1=1e-4, c2=0.9):
+ """
+ Unconstrained minimization of a function using the Newton-CG method.
+
+ Parameters
+ ----------
+ f : callable ``f(x, *args)``
+ Objective function to be minimized.
+ x0 : ndarray
+ Initial guess.
+ fprime : callable ``f'(x, *args)``
+ Gradient of f.
+ fhess_p : callable ``fhess_p(x, p, *args)``, optional
+ Function which computes the Hessian of f times an
+ arbitrary vector, p.
+ fhess : callable ``fhess(x, *args)``, optional
+ Function to compute the Hessian matrix of f.
+ args : tuple, optional
+ Extra arguments passed to f, fprime, fhess_p, and fhess
+ (the same set of extra arguments is supplied to all of
+ these functions).
+ epsilon : float or ndarray, optional
+ If fhess is approximated, use this value for the step size.
+ callback : callable, optional
+ An optional user-supplied function which is called after
+ each iteration. Called as callback(xk), where xk is the
+ current parameter vector.
+ avextol : float, optional
+ Convergence is assumed when the average relative error in
+ the minimizer falls below this amount.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ full_output : bool, optional
+ If True, return the optional outputs.
+ disp : bool, optional
+ If True, print convergence message.
+ retall : bool, optional
+ If True, return a list of results at each iteration.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
+ fopt : float
+ Value of the function at xopt, i.e., ``fopt = f(xopt)``.
+ fcalls : int
+ Number of function calls made.
+ gcalls : int
+ Number of gradient calls made.
+ hcalls : int
+ Number of Hessian calls made.
+ warnflag : int
+ Warnings generated by the algorithm.
+ 1 : Maximum number of iterations exceeded.
+ 2 : Line search failure (precision loss).
+ 3 : NaN result encountered.
+ allvecs : list
+ The result at each iteration, if retall is True (see below).
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'Newton-CG' `method` in particular.
+
+ Notes
+ -----
+ Only one of `fhess_p` or `fhess` need to be given. If `fhess`
+ is provided, then `fhess_p` will be ignored. If neither `fhess`
+ nor `fhess_p` is provided, then the hessian product will be
+ approximated using finite differences on `fprime`. `fhess_p`
+ must compute the hessian times an arbitrary vector. If it is not
+ given, finite-differences on `fprime` are used to compute
+ it.
+
+ Newton-CG methods are also called truncated Newton methods. This
+ function differs from scipy.optimize.fmin_tnc because
+
+ 1. scipy.optimize.fmin_ncg is written purely in Python using NumPy
+ and scipy while scipy.optimize.fmin_tnc calls a C function.
+ 2. scipy.optimize.fmin_ncg is only for unconstrained minimization
+ while scipy.optimize.fmin_tnc is for unconstrained minimization
+ or box constrained minimization. (Box constraints give
+ lower and upper bounds for each variable separately.)
+
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ References
+ ----------
+ Wright & Nocedal, 'Numerical Optimization', 1999, p. 140.
+
+ """
+ opts = {'xtol': avextol,
+ 'eps': epsilon,
+ 'maxiter': maxiter,
+ 'disp': disp,
+ 'return_all': retall}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_newtoncg(f, x0, args, fprime, fhess, fhess_p,
+ callback=callback, c1=c1, c2=c2, **opts)
+
+ if full_output:
+ retlist = (res['x'], res['fun'], res['nfev'], res['njev'],
+ res['nhev'], res['status'])
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_newtoncg(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ callback=None, xtol=1e-5, eps=_epsilon, maxiter=None,
+ disp=False, return_all=False, c1=1e-4, c2=0.9, workers=None,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ Newton-CG algorithm.
+
+ Note that the `jac` parameter (Jacobian) is required.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ xtol : float
+ Average relative error in solution `xopt` acceptable for
+ convergence.
+ maxiter : int
+ Maximum number of iterations to perform.
+ eps : float or ndarray
+ If `hessp` is approximated, use this value for the step size.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+ """
+ _check_unknown_options(unknown_options)
+ if jac is None:
+ raise ValueError('Jacobian is required for Newton-CG method')
+ fhess_p = hessp
+ fhess = hess
+ avextol = xtol
+ epsilon = eps
+ retall = return_all
+
+ x0 = asarray(x0).flatten()
+ # TODO: add hessp (callable or FD) to ScalarFunction?
+ sf = _prepare_scalar_function(
+ fun, x0, jac, args=args, epsilon=eps, hess=hess, workers=workers
+ )
+ f = sf.fun
+ fprime = sf.grad
+ _h = sf.hess(x0)
+
+ # Logic for hess/hessp
+ # - If a callable(hess) is provided, then use that
+ # - If hess is a FD_METHOD, or the output from hess(x) is a LinearOperator
+ # then create a hessp function using those.
+ # - If hess is None but you have callable(hessp) then use the hessp.
+ # - If hess and hessp are None then approximate hessp using the grad/jac.
+
+ if (hess in FD_METHODS or isinstance(_h, LinearOperator)):
+ fhess = None
+
+ def _hessp(x, p, *args):
+ return sf.hess(x).dot(p)
+
+ fhess_p = _hessp
+
+ def terminate(warnflag, msg):
+ if disp:
+ _print_success_message_or_warn(warnflag, msg)
+ print(f" Current function value: {old_fval:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+ print(f" Hessian evaluations: {hcalls:d}")
+ fval = old_fval
+ result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev,
+ njev=sf.ngev, nhev=hcalls, status=warnflag,
+ success=(warnflag == 0), message=msg, x=xk,
+ nit=k)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+ hcalls = 0
+ if maxiter is None:
+ maxiter = len(x0)*200
+ cg_maxiter = 20*len(x0)
+
+ xtol = len(x0) * avextol
+ # Make sure we enter the while loop.
+ update_l1norm = np.finfo(float).max
+ xk = np.copy(x0)
+ if retall:
+ allvecs = [xk]
+ k = 0
+ gfk = None
+ old_fval = f(x0)
+ old_old_fval = None
+ float64eps = np.finfo(np.float64).eps
+ while update_l1norm > xtol:
+ if k >= maxiter:
+ msg = "Warning: " + _status_message['maxiter']
+ return terminate(1, msg)
+ # Compute a search direction pk by applying the CG method to
+ # del2 f(xk) p = - grad f(xk) starting from 0.
+ b = -fprime(xk)
+ maggrad = np.linalg.norm(b, ord=1)
+ eta = min(0.5, math.sqrt(maggrad))
+ termcond = eta * maggrad
+ xsupi = zeros(len(x0), dtype=x0.dtype)
+ ri = -b
+ psupi = -ri
+ i = 0
+ dri0 = np.dot(ri, ri)
+
+ if fhess is not None: # you want to compute hessian once.
+ A = sf.hess(xk)
+ hcalls += 1
+
+ for k2 in range(cg_maxiter):
+ if np.add.reduce(np.abs(ri)) <= termcond:
+ break
+ if fhess is None:
+ if fhess_p is None:
+ Ap = approx_fhess_p(xk, psupi, fprime, epsilon)
+ else:
+ Ap = fhess_p(xk, psupi, *args)
+ hcalls += 1
+ else:
+ # hess was supplied as a callable or hessian update strategy, so
+ # A is a dense numpy array or sparse array
+ Ap = A.dot(psupi)
+ # check curvature
+ Ap = asarray(Ap).squeeze() # get rid of matrices...
+ curv = np.dot(psupi, Ap)
+ if 0 <= curv <= 3 * float64eps:
+ break
+ elif curv < 0:
+ if (i > 0):
+ break
+ else:
+ # fall back to steepest descent direction
+ xsupi = dri0 / (-curv) * b
+ break
+ alphai = dri0 / curv
+ xsupi += alphai * psupi
+ ri += alphai * Ap
+ dri1 = np.dot(ri, ri)
+ betai = dri1 / dri0
+ psupi = -ri + betai * psupi
+ i += 1
+ dri0 = dri1 # update np.dot(ri,ri) for next time.
+ else:
+ # curvature keeps increasing, bail out
+ msg = ("Warning: CG iterations didn't converge. The Hessian is not "
+ "positive definite.")
+ return terminate(3, msg)
+
+ pk = xsupi # search direction is solution to system.
+ gfk = -b # gradient at xk
+
+ try:
+ alphak, fc, gc, old_fval, old_old_fval, gfkp1 = \
+ _line_search_wolfe12(f, fprime, xk, pk, gfk,
+ old_fval, old_old_fval, c1=c1, c2=c2)
+ except _LineSearchError:
+ # Line search failed to find a better solution.
+ msg = "Warning: " + _status_message['pr_loss']
+ return terminate(2, msg)
+
+ update = alphak * pk
+ xk += update # upcast if necessary
+ if retall:
+ allvecs.append(xk)
+ k += 1
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ return terminate(5, "")
+ update_l1norm = np.linalg.norm(update, ord=1)
+
+ else:
+ if np.isnan(old_fval) or np.isnan(update_l1norm):
+ return terminate(3, _status_message['nan'])
+
+ msg = _status_message['success']
+ return terminate(0, msg)
+
+
+def fminbound(func, x1, x2, args=(), xtol=1e-5, maxfun=500,
+ full_output=0, disp=1):
+ """Bounded minimization for scalar functions.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function to be minimized (must accept and return scalars).
+ x1, x2 : float or array scalar
+ Finite optimization bounds.
+ args : tuple, optional
+ Extra arguments passed to function.
+ xtol : float, optional
+ The convergence tolerance.
+ maxfun : int, optional
+ Maximum number of function evaluations allowed.
+ full_output : bool, optional
+ If True, return optional outputs.
+ disp : int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters (over given interval) which minimize the
+ objective function.
+ fval : number
+ (Optional output) The function value evaluated at the minimizer.
+ ierr : int
+ (Optional output) An error flag (0 if converged, 1 if maximum number of
+ function calls reached).
+ numfunc : int
+ (Optional output) The number of function calls made.
+
+ See Also
+ --------
+ minimize_scalar: Interface to minimization algorithms for scalar
+ univariate functions. See the 'Bounded' `method` in particular.
+
+ Notes
+ -----
+ Finds a local minimizer of the scalar function `func` in the
+ interval x1 < xopt < x2 using Brent's method. (See `brent`
+ for auto-bracketing.)
+
+ References
+ ----------
+ .. [1] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods
+ for Mathematical Computations." Prentice-Hall Series in Automatic
+ Computation 259 (1977).
+ .. [2] Brent, Richard P. Algorithms for Minimization Without Derivatives.
+ Courier Corporation, 2013.
+
+ Examples
+ --------
+ `fminbound` finds the minimizer of the function in the given range.
+ The following examples illustrate this.
+
+ >>> from scipy import optimize
+ >>> def f(x):
+ ... return (x-1)**2
+ >>> minimizer = optimize.fminbound(f, -4, 4)
+ >>> minimizer
+ 1.0
+ >>> minimum = f(minimizer)
+ >>> minimum
+ 0.0
+ >>> res = optimize.fminbound(f, 3, 4, full_output=True)
+ >>> minimizer, fval, ierr, numfunc = res
+ >>> minimizer
+ 3.000005960860986
+ >>> minimum = f(minimizer)
+ >>> minimum, fval
+ (4.000023843479476, 4.000023843479476)
+ """
+ options = {'xatol': xtol,
+ 'maxiter': maxfun,
+ 'disp': disp}
+
+ res = _minimize_scalar_bounded(func, (x1, x2), args, **options)
+ if full_output:
+ return res['x'], res['fun'], res['status'], res['nfev']
+ else:
+ return res['x']
+
+
+def _minimize_scalar_bounded(func, bounds, args=(),
+ xatol=1e-5, maxiter=500, disp=0,
+ **unknown_options):
+ """
+ Options
+ -------
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp: int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+
+ xatol : float
+ Absolute error in solution `xopt` acceptable for convergence.
+
+ """
+ _check_unknown_options(unknown_options)
+ maxfun = maxiter
+ # Test bounds are of correct form
+ if len(bounds) != 2:
+ raise ValueError('bounds must have two elements.')
+ x1, x2 = bounds
+
+ if not (is_finite_scalar(x1) and is_finite_scalar(x2)):
+ raise ValueError("Optimization bounds must be finite scalars.")
+
+ if x1 > x2:
+ raise ValueError("The lower bound exceeds the upper bound.")
+
+ flag = 0
+ header = ' Func-count x f(x) Procedure'
+ step = ' initial'
+
+ sqrt_eps = sqrt(2.2e-16)
+ golden_mean = 0.5 * (3.0 - sqrt(5.0))
+ a, b = x1, x2
+ fulc = a + golden_mean * (b - a)
+ nfc, xf = fulc, fulc
+ rat = e = 0.0
+ x = xf
+ fx = func(x, *args)
+ num = 1
+ fmin_data = (1, xf, fx)
+ fu = np.inf
+
+ ffulc = fnfc = fx
+ xm = 0.5 * (a + b)
+ tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0
+ tol2 = 2.0 * tol1
+
+ if disp > 2:
+ print(" ")
+ print(header)
+ print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)))
+
+ while (np.abs(xf - xm) > (tol2 - 0.5 * (b - a))):
+ golden = 1
+ # Check for parabolic fit
+ if np.abs(e) > tol1:
+ golden = 0
+ r = (xf - nfc) * (fx - ffulc)
+ q = (xf - fulc) * (fx - fnfc)
+ p = (xf - fulc) * q - (xf - nfc) * r
+ q = 2.0 * (q - r)
+ if q > 0.0:
+ p = -p
+ q = np.abs(q)
+ r = e
+ e = rat
+
+ # Check for acceptability of parabola
+ if ((np.abs(p) < np.abs(0.5*q*r)) and (p > q*(a - xf)) and
+ (p < q * (b - xf))):
+ rat = (p + 0.0) / q
+ x = xf + rat
+ step = ' parabolic'
+
+ if ((x - a) < tol2) or ((b - x) < tol2):
+ si = np.sign(xm - xf) + ((xm - xf) == 0)
+ rat = tol1 * si
+ else: # do a golden-section step
+ golden = 1
+
+ if golden: # do a golden-section step
+ if xf >= xm:
+ e = a - xf
+ else:
+ e = b - xf
+ rat = golden_mean*e
+ step = ' golden'
+
+ si = np.sign(rat) + (rat == 0)
+ x = xf + si * np.maximum(np.abs(rat), tol1)
+ fu = func(x, *args)
+ num += 1
+ fmin_data = (num, x, fu)
+ if disp > 2:
+ print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)))
+
+ if fu <= fx:
+ if x >= xf:
+ a = xf
+ else:
+ b = xf
+ fulc, ffulc = nfc, fnfc
+ nfc, fnfc = xf, fx
+ xf, fx = x, fu
+ else:
+ if x < xf:
+ a = x
+ else:
+ b = x
+ if (fu <= fnfc) or (nfc == xf):
+ fulc, ffulc = nfc, fnfc
+ nfc, fnfc = x, fu
+ elif (fu <= ffulc) or (fulc == xf) or (fulc == nfc):
+ fulc, ffulc = x, fu
+
+ xm = 0.5 * (a + b)
+ tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0
+ tol2 = 2.0 * tol1
+
+ if num >= maxfun:
+ flag = 1
+ break
+
+ if np.isnan(xf) or np.isnan(fx) or np.isnan(fu):
+ flag = 2
+
+ fval = fx
+ if disp > 0:
+ _endprint(x, flag, fval, maxfun, xatol, disp)
+
+ result = OptimizeResult(fun=fval, status=flag, success=(flag == 0),
+ message={0: 'Solution found.',
+ 1: 'Maximum number of function calls '
+ 'reached.',
+ 2: _status_message['nan']}.get(flag, ''),
+ x=xf, nfev=num, nit=num)
+
+ return result
+
+
+class Brent:
+ #need to rethink design of __init__
+ def __init__(self, func, args=(), tol=1.48e-8, maxiter=500,
+ full_output=0, disp=0):
+ self.func = func
+ self.args = args
+ self.tol = tol
+ self.maxiter = maxiter
+ self._mintol = 1.0e-11
+ self._cg = 0.3819660
+ self.xmin = None
+ self.fval = None
+ self.iter = 0
+ self.funcalls = 0
+ self.disp = disp
+
+ # need to rethink design of set_bracket (new options, etc.)
+ def set_bracket(self, brack=None):
+ self.brack = brack
+
+ def get_bracket_info(self):
+ #set up
+ func = self.func
+ args = self.args
+ brack = self.brack
+ ### BEGIN core bracket_info code ###
+ ### carefully DOCUMENT any CHANGES in core ##
+ if brack is None:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
+ elif len(brack) == 2:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
+ xb=brack[1], args=args)
+ elif len(brack) == 3:
+ xa, xb, xc = brack
+ if (xa > xc): # swap so xa < xc can be assumed
+ xc, xa = xa, xc
+ if not ((xa < xb) and (xb < xc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not"
+ " fulfill this requirement: (xa < xb) and (xb < xc)"
+ )
+ fa = func(*((xa,) + args))
+ fb = func(*((xb,) + args))
+ fc = func(*((xc,) + args))
+ if not ((fb < fa) and (fb < fc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not fulfill"
+ " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))"
+ )
+
+ funcalls = 3
+ else:
+ raise ValueError("Bracketing interval must be "
+ "length 2 or 3 sequence.")
+ ### END core bracket_info code ###
+
+ return xa, xb, xc, fa, fb, fc, funcalls
+
+ def optimize(self):
+ # set up for optimization
+ func = self.func
+ xa, xb, xc, fa, fb, fc, funcalls = self.get_bracket_info()
+ _mintol = self._mintol
+ _cg = self._cg
+ #################################
+ #BEGIN CORE ALGORITHM
+ #################################
+ x = w = v = xb
+ fw = fv = fx = fb
+ if (xa < xc):
+ a = xa
+ b = xc
+ else:
+ a = xc
+ b = xa
+ deltax = 0.0
+ iter = 0
+
+ if self.disp > 2:
+ print(" ")
+ print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}")
+ print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}")
+
+ while (iter < self.maxiter):
+ tol1 = self.tol * np.abs(x) + _mintol
+ tol2 = 2.0 * tol1
+ xmid = 0.5 * (a + b)
+ # check for convergence
+ if np.abs(x - xmid) < (tol2 - 0.5 * (b - a)):
+ break
+ # XXX In the first iteration, rat is only bound in the true case
+ # of this conditional. This used to cause an UnboundLocalError
+ # (gh-4140). It should be set before the if (but to what?).
+ if (np.abs(deltax) <= tol1):
+ if (x >= xmid):
+ deltax = a - x # do a golden section step
+ else:
+ deltax = b - x
+ rat = _cg * deltax
+ else: # do a parabolic step
+ tmp1 = (x - w) * (fx - fv)
+ tmp2 = (x - v) * (fx - fw)
+ p = (x - v) * tmp2 - (x - w) * tmp1
+ tmp2 = 2.0 * (tmp2 - tmp1)
+ if (tmp2 > 0.0):
+ p = -p
+ tmp2 = np.abs(tmp2)
+ dx_temp = deltax
+ deltax = rat
+ # check parabolic fit
+ if ((p > tmp2 * (a - x)) and (p < tmp2 * (b - x)) and
+ (np.abs(p) < np.abs(0.5 * tmp2 * dx_temp))):
+ rat = p * 1.0 / tmp2 # if parabolic step is useful.
+ u = x + rat
+ if ((u - a) < tol2 or (b - u) < tol2):
+ if xmid - x >= 0:
+ rat = tol1
+ else:
+ rat = -tol1
+ else:
+ if (x >= xmid):
+ deltax = a - x # if it's not do a golden section step
+ else:
+ deltax = b - x
+ rat = _cg * deltax
+
+ if (np.abs(rat) < tol1): # update by at least tol1
+ if rat >= 0:
+ u = x + tol1
+ else:
+ u = x - tol1
+ else:
+ u = x + rat
+ fu = func(*((u,) + self.args)) # calculate new output value
+ funcalls += 1
+
+ if (fu > fx): # if it's bigger than current
+ if (u < x):
+ a = u
+ else:
+ b = u
+ if (fu <= fw) or (w == x):
+ v = w
+ w = u
+ fv = fw
+ fw = fu
+ elif (fu <= fv) or (v == x) or (v == w):
+ v = u
+ fv = fu
+ else:
+ if (u >= x):
+ a = x
+ else:
+ b = x
+ v = w
+ w = x
+ x = u
+ fv = fw
+ fw = fx
+ fx = fu
+
+ if self.disp > 2:
+ print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}")
+
+ iter += 1
+ #################################
+ #END CORE ALGORITHM
+ #################################
+
+ self.xmin = x
+ self.fval = fx
+ self.iter = iter
+ self.funcalls = funcalls
+
+ def get_result(self, full_output=False):
+ if full_output:
+ return self.xmin, self.fval, self.iter, self.funcalls
+ else:
+ return self.xmin
+
+
+def brent(func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500):
+ """
+ Given a function of one variable and a possible bracket, return
+ a local minimizer of the function isolated to a fractional precision
+ of tol.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function.
+ args : tuple, optional
+ Additional arguments (if present).
+ brack : tuple, optional
+ Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair
+ ``(xa, xb)`` to be used as initial points for a downhill bracket search
+ (see `scipy.optimize.bracket`).
+ The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
+ tol : float, optional
+ Relative error in solution `xopt` acceptable for convergence.
+ full_output : bool, optional
+ If True, return all output args (xmin, fval, iter,
+ funcalls).
+ maxiter : int, optional
+ Maximum number of iterations in solution.
+
+ Returns
+ -------
+ xmin : ndarray
+ Optimum point.
+ fval : float
+ (Optional output) Optimum function value.
+ iter : int
+ (Optional output) Number of iterations.
+ funcalls : int
+ (Optional output) Number of objective function evaluations made.
+
+ See Also
+ --------
+ minimize_scalar: Interface to minimization algorithms for scalar
+ univariate functions. See the 'Brent' `method` in particular.
+
+ Notes
+ -----
+ Uses inverse parabolic interpolation when possible to speed up
+ convergence of golden section method.
+
+ Does not ensure that the minimum lies in the range specified by
+ `brack`. See `scipy.optimize.fminbound`.
+
+ Examples
+ --------
+ We illustrate the behaviour of the function when `brack` is of
+ size 2 and 3 respectively. In the case where `brack` is of the
+ form ``(xa, xb)``, we can see for the given values, the output does
+ not necessarily lie in the range ``(xa, xb)``.
+
+ >>> def f(x):
+ ... return (x-1)**2
+
+ >>> from scipy import optimize
+
+ >>> minimizer = optimize.brent(f, brack=(1, 2))
+ >>> minimizer
+ 1
+ >>> res = optimize.brent(f, brack=(-1, 0.5, 2), full_output=True)
+ >>> xmin, fval, iter, funcalls = res
+ >>> f(xmin), fval
+ (0.0, 0.0)
+
+ """
+ options = {'xtol': tol,
+ 'maxiter': maxiter}
+ res = _minimize_scalar_brent(func, brack, args, **options)
+ if full_output:
+ return res['x'], res['fun'], res['nit'], res['nfev']
+ else:
+ return res['x']
+
+
+def _minimize_scalar_brent(func, brack=None, args=(), xtol=1.48e-8,
+ maxiter=500, disp=0,
+ **unknown_options):
+ """
+ Options
+ -------
+ maxiter : int
+ Maximum number of iterations to perform.
+ xtol : float
+ Relative error in solution `xopt` acceptable for convergence.
+ disp : int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+
+ Notes
+ -----
+ Uses inverse parabolic interpolation when possible to speed up
+ convergence of golden section method.
+
+ """
+ _check_unknown_options(unknown_options)
+ tol = xtol
+ if tol < 0:
+ raise ValueError(f'tolerance should be >= 0, got {tol!r}')
+
+ brent = Brent(func=func, args=args, tol=tol,
+ full_output=True, maxiter=maxiter, disp=disp)
+ brent.set_bracket(brack)
+ brent.optimize()
+ x, fval, nit, nfev = brent.get_result(full_output=True)
+
+ success = nit < maxiter and not (np.isnan(x) or np.isnan(fval))
+
+ if success:
+ message = ("\nOptimization terminated successfully;\n"
+ "The returned value satisfies the termination criteria\n"
+ f"(using xtol = {xtol} )")
+ else:
+ if nit >= maxiter:
+ message = "\nMaximum number of iterations exceeded"
+ if np.isnan(x) or np.isnan(fval):
+ message = f"{_status_message['nan']}"
+
+ if disp:
+ _print_success_message_or_warn(not success, message)
+
+ return OptimizeResult(fun=fval, x=x, nit=nit, nfev=nfev,
+ success=success, message=message)
+
+
+def golden(func, args=(), brack=None, tol=_epsilon,
+ full_output=0, maxiter=5000):
+ """
+ Return the minimizer of a function of one variable using the golden section
+ method.
+
+ Given a function of one variable and a possible bracketing interval,
+ return a minimizer of the function isolated to a fractional precision of
+ tol.
+
+ Parameters
+ ----------
+ func : callable func(x,*args)
+ Objective function to minimize.
+ args : tuple, optional
+ Additional arguments (if present), passed to func.
+ brack : tuple, optional
+ Either a triple ``(xa, xb, xc)`` where ``xa < xb < xc`` and
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair (xa, xb)
+ to be used as initial points for a downhill bracket search (see
+ `scipy.optimize.bracket`).
+ The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
+ tol : float, optional
+ x tolerance stop criterion
+ full_output : bool, optional
+ If True, return optional outputs.
+ maxiter : int
+ Maximum number of iterations to perform.
+
+ Returns
+ -------
+ xmin : ndarray
+ Optimum point.
+ fval : float
+ (Optional output) Optimum function value.
+ funcalls : int
+ (Optional output) Number of objective function evaluations made.
+
+ See Also
+ --------
+ minimize_scalar: Interface to minimization algorithms for scalar
+ univariate functions. See the 'Golden' `method` in particular.
+
+ Notes
+ -----
+ Uses analog of bisection method to decrease the bracketed
+ interval.
+
+ Examples
+ --------
+ We illustrate the behaviour of the function when `brack` is of
+ size 2 and 3, respectively. In the case where `brack` is of the
+ form (xa,xb), we can see for the given values, the output need
+ not necessarily lie in the range ``(xa, xb)``.
+
+ >>> def f(x):
+ ... return (x-1)**2
+
+ >>> from scipy import optimize
+
+ >>> minimizer = optimize.golden(f, brack=(1, 2))
+ >>> minimizer
+ 1
+ >>> res = optimize.golden(f, brack=(-1, 0.5, 2), full_output=True)
+ >>> xmin, fval, funcalls = res
+ >>> f(xmin), fval
+ (9.925165290385052e-18, 9.925165290385052e-18)
+
+ """
+ options = {'xtol': tol, 'maxiter': maxiter}
+ res = _minimize_scalar_golden(func, brack, args, **options)
+ if full_output:
+ return res['x'], res['fun'], res['nfev']
+ else:
+ return res['x']
+
+
+def _minimize_scalar_golden(func, brack=None, args=(),
+ xtol=_epsilon, maxiter=5000, disp=0,
+ **unknown_options):
+ """
+ Options
+ -------
+ xtol : float
+ Relative error in solution `xopt` acceptable for convergence.
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp: int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+ """
+ _check_unknown_options(unknown_options)
+ tol = xtol
+ if brack is None:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
+ elif len(brack) == 2:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
+ xb=brack[1], args=args)
+ elif len(brack) == 3:
+ xa, xb, xc = brack
+ if (xa > xc): # swap so xa < xc can be assumed
+ xc, xa = xa, xc
+ if not ((xa < xb) and (xb < xc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not"
+ " fulfill this requirement: (xa < xb) and (xb < xc)"
+ )
+ fa = func(*((xa,) + args))
+ fb = func(*((xb,) + args))
+ fc = func(*((xc,) + args))
+ if not ((fb < fa) and (fb < fc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not fulfill"
+ " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))"
+ )
+ funcalls = 3
+ else:
+ raise ValueError("Bracketing interval must be length 2 or 3 sequence.")
+
+ _gR = 0.61803399 # golden ratio conjugate: 2.0/(1.0+sqrt(5.0))
+ _gC = 1.0 - _gR
+ x3 = xc
+ x0 = xa
+ if (np.abs(xc - xb) > np.abs(xb - xa)):
+ x1 = xb
+ x2 = xb + _gC * (xc - xb)
+ else:
+ x2 = xb
+ x1 = xb - _gC * (xb - xa)
+ f1 = func(*((x1,) + args))
+ f2 = func(*((x2,) + args))
+ funcalls += 2
+ nit = 0
+
+ if disp > 2:
+ print(" ")
+ print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}")
+
+ for i in range(maxiter):
+ if np.abs(x3 - x0) <= tol * (np.abs(x1) + np.abs(x2)):
+ break
+ if (f2 < f1):
+ x0 = x1
+ x1 = x2
+ x2 = _gR * x1 + _gC * x3
+ f1 = f2
+ f2 = func(*((x2,) + args))
+ else:
+ x3 = x2
+ x2 = x1
+ x1 = _gR * x2 + _gC * x0
+ f2 = f1
+ f1 = func(*((x1,) + args))
+ funcalls += 1
+ if disp > 2:
+ if (f1 < f2):
+ xmin, fval = x1, f1
+ else:
+ xmin, fval = x2, f2
+ print(f"{funcalls:^12g} {xmin:^12.6g} {fval:^12.6g}")
+
+ nit += 1
+ # end of iteration loop
+
+ if (f1 < f2):
+ xmin = x1
+ fval = f1
+ else:
+ xmin = x2
+ fval = f2
+
+ success = nit < maxiter and not (np.isnan(fval) or np.isnan(xmin))
+
+ if success:
+ message = ("\nOptimization terminated successfully;\n"
+ "The returned value satisfies the termination criteria\n"
+ f"(using xtol = {xtol} )")
+ else:
+ if nit >= maxiter:
+ message = "\nMaximum number of iterations exceeded"
+ if np.isnan(xmin) or np.isnan(fval):
+ message = f"{_status_message['nan']}"
+
+ if disp:
+ _print_success_message_or_warn(not success, message)
+
+ return OptimizeResult(fun=fval, nfev=funcalls, x=xmin, nit=nit,
+ success=success, message=message)
+
+
+def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0, maxiter=1000):
+ """
+ Bracket the minimum of a function.
+
+ Given a function and distinct initial points, search in the
+ downhill direction (as defined by the initial points) and return
+ three points that bracket the minimum of the function.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function to minimize.
+ xa, xb : float, optional
+ Initial points. Defaults `xa` to 0.0, and `xb` to 1.0.
+ A local minimum need not be contained within this interval.
+ args : tuple, optional
+ Additional arguments (if present), passed to `func`.
+ grow_limit : float, optional
+ Maximum grow limit. Defaults to 110.0
+ maxiter : int, optional
+ Maximum number of iterations to perform. Defaults to 1000.
+
+ Returns
+ -------
+ xa, xb, xc : float
+ Final points of the bracket.
+ fa, fb, fc : float
+ Objective function values at the bracket points.
+ funcalls : int
+ Number of function evaluations made.
+
+ Raises
+ ------
+ BracketError
+ If no valid bracket is found before the algorithm terminates.
+ See notes for conditions of a valid bracket.
+
+ Notes
+ -----
+ The algorithm attempts to find three strictly ordered points (i.e.
+ :math:`x_a < x_b < x_c` or :math:`x_c < x_b < x_a`) satisfying
+ :math:`f(x_b) ≤ f(x_a)` and :math:`f(x_b) ≤ f(x_c)`, where one of the
+ inequalities must be satisfied strictly and all :math:`x_i` must be
+ finite.
+
+ Examples
+ --------
+ This function can find a downward convex region of a function:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.optimize import bracket
+ >>> def f(x):
+ ... return 10*x**2 + 3*x + 5
+ >>> x = np.linspace(-2, 2)
+ >>> y = f(x)
+ >>> init_xa, init_xb = 0.1, 1
+ >>> xa, xb, xc, fa, fb, fc, funcalls = bracket(f, xa=init_xa, xb=init_xb)
+ >>> plt.axvline(x=init_xa, color="k", linestyle="--")
+ >>> plt.axvline(x=init_xb, color="k", linestyle="--")
+ >>> plt.plot(x, y, "-k")
+ >>> plt.plot(xa, fa, "bx")
+ >>> plt.plot(xb, fb, "rx")
+ >>> plt.plot(xc, fc, "bx")
+ >>> plt.show()
+
+ Note that both initial points were to the right of the minimum, and the
+ third point was found in the "downhill" direction: the direction
+ in which the function appeared to be decreasing (to the left).
+ The final points are strictly ordered, and the function value
+ at the middle point is less than the function values at the endpoints;
+ it follows that a minimum must lie within the bracket.
+
+ """
+ _gold = 1.618034 # golden ratio: (1.0+sqrt(5.0))/2.0
+ _verysmall_num = 1e-21
+ # convert to numpy floats if not already
+ xa, xb = np.asarray([xa, xb])
+ fa = func(*(xa,) + args)
+ fb = func(*(xb,) + args)
+ if (fa < fb): # Switch so fa > fb
+ xa, xb = xb, xa
+ fa, fb = fb, fa
+ xc = xb + _gold * (xb - xa)
+ fc = func(*((xc,) + args))
+ funcalls = 3
+ iter = 0
+ while (fc < fb):
+ tmp1 = (xb - xa) * (fb - fc)
+ tmp2 = (xb - xc) * (fb - fa)
+ val = tmp2 - tmp1
+ if np.abs(val) < _verysmall_num:
+ denom = 2.0 * _verysmall_num
+ else:
+ denom = 2.0 * val
+ w = xb - ((xb - xc) * tmp2 - (xb - xa) * tmp1) / denom
+ wlim = xb + grow_limit * (xc - xb)
+ msg = ("No valid bracket was found before the iteration limit was "
+ "reached. Consider trying different initial points or "
+ "increasing `maxiter`.")
+ if iter > maxiter:
+ raise RuntimeError(msg)
+ iter += 1
+ if (w - xc) * (xb - w) > 0.0:
+ fw = func(*((w,) + args))
+ funcalls += 1
+ if (fw < fc):
+ xa = xb
+ xb = w
+ fa = fb
+ fb = fw
+ break
+ elif (fw > fb):
+ xc = w
+ fc = fw
+ break
+ w = xc + _gold * (xc - xb)
+ fw = func(*((w,) + args))
+ funcalls += 1
+ elif (w - wlim)*(wlim - xc) >= 0.0:
+ w = wlim
+ fw = func(*((w,) + args))
+ funcalls += 1
+ elif (w - wlim)*(xc - w) > 0.0:
+ fw = func(*((w,) + args))
+ funcalls += 1
+ if (fw < fc):
+ xb = xc
+ xc = w
+ w = xc + _gold * (xc - xb)
+ fb = fc
+ fc = fw
+ fw = func(*((w,) + args))
+ funcalls += 1
+ else:
+ w = xc + _gold * (xc - xb)
+ fw = func(*((w,) + args))
+ funcalls += 1
+ xa = xb
+ xb = xc
+ xc = w
+ fa = fb
+ fb = fc
+ fc = fw
+
+ # three conditions for a valid bracket
+ cond1 = (fb < fc and fb <= fa) or (fb < fa and fb <= fc)
+ cond2 = (xa < xb < xc or xc < xb < xa)
+ cond3 = np.isfinite(xa) and np.isfinite(xb) and np.isfinite(xc)
+ msg = ("The algorithm terminated without finding a valid bracket. "
+ "Consider trying different initial points.")
+ if not (cond1 and cond2 and cond3):
+ e = BracketError(msg)
+ e.data = (xa, xb, xc, fa, fb, fc, funcalls)
+ raise e
+
+ return xa, xb, xc, fa, fb, fc, funcalls
+
+
+class BracketError(RuntimeError):
+ pass
+
+
+def _recover_from_bracket_error(solver, fun, bracket, args, **options):
+ # `bracket` was originally written without checking whether the resulting
+ # bracket is valid. `brent` and `golden` built on top of it without
+ # checking the returned bracket for validity, and their output can be
+ # incorrect without warning/error if the original bracket is invalid.
+ # gh-14858 noticed the problem, and the following is the desired
+ # behavior:
+ # - `scipy.optimize.bracket`, `scipy.optimize.brent`, and
+ # `scipy.optimize.golden` should raise an error if the bracket is
+ # invalid, as opposed to silently returning garbage
+ # - `scipy.optimize.minimize_scalar` should return with `success=False`
+ # and other information
+ # The changes that would be required to achieve this the traditional
+ # way (`return`ing all the required information from bracket all the way
+ # up to `minimizer_scalar`) are extensive and invasive. (See a6aa40d.)
+ # We can achieve the same thing by raising the error in `bracket`, but
+ # storing the information needed by `minimize_scalar` in the error object,
+ # and intercepting it here.
+ try:
+ res = solver(fun, bracket, args, **options)
+ except BracketError as e:
+ msg = str(e)
+ xa, xb, xc, fa, fb, fc, funcalls = e.data
+ xs, fs = [xa, xb, xc], [fa, fb, fc]
+ if np.any(np.isnan([xs, fs])):
+ x, fun = np.nan, np.nan
+ else:
+ imin = np.argmin(fs)
+ x, fun = xs[imin], fs[imin]
+ return OptimizeResult(fun=fun, nfev=funcalls, x=x,
+ nit=0, success=False, message=msg)
+ return res
+
+
+def _line_for_search(x0, alpha, lower_bound, upper_bound):
+ """
+ Given a parameter vector ``x0`` with length ``n`` and a direction
+ vector ``alpha`` with length ``n``, and lower and upper bounds on
+ each of the ``n`` parameters, what are the bounds on a scalar
+ ``l`` such that ``lower_bound <= x0 + alpha * l <= upper_bound``.
+
+
+ Parameters
+ ----------
+ x0 : np.array.
+ The vector representing the current location.
+ Note ``np.shape(x0) == (n,)``.
+ alpha : np.array.
+ The vector representing the direction.
+ Note ``np.shape(alpha) == (n,)``.
+ lower_bound : np.array.
+ The lower bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
+ should be ``-np.inf``.
+ Note ``np.shape(lower_bound) == (n,)``.
+ upper_bound : np.array.
+ The upper bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
+ should be ``np.inf``.
+ Note ``np.shape(upper_bound) == (n,)``.
+
+ Returns
+ -------
+ res : tuple ``(lmin, lmax)``
+ The bounds for ``l`` such that
+ ``lower_bound[i] <= x0[i] + alpha[i] * l <= upper_bound[i]``
+ for all ``i``.
+
+ """
+ # get nonzero indices of alpha so we don't get any zero division errors.
+ # alpha will not be all zero, since it is called from _linesearch_powell
+ # where we have a check for this.
+ nonzero, = alpha.nonzero()
+ lower_bound, upper_bound = lower_bound[nonzero], upper_bound[nonzero]
+ x0, alpha = x0[nonzero], alpha[nonzero]
+ low = (lower_bound - x0) / alpha
+ high = (upper_bound - x0) / alpha
+
+ # positive and negative indices
+ pos = alpha > 0
+
+ lmin_pos = np.where(pos, low, 0)
+ lmin_neg = np.where(pos, 0, high)
+ lmax_pos = np.where(pos, high, 0)
+ lmax_neg = np.where(pos, 0, low)
+
+ lmin = np.max(lmin_pos + lmin_neg)
+ lmax = np.min(lmax_pos + lmax_neg)
+
+ # if x0 is outside the bounds, then it is possible that there is
+ # no way to get back in the bounds for the parameters being updated
+ # with the current direction alpha.
+ # when this happens, lmax < lmin.
+ # If this is the case, then we can just return (0, 0)
+ return (lmin, lmax) if lmax >= lmin else (0, 0)
+
+
+def _linesearch_powell(func, p, xi, tol=1e-3,
+ lower_bound=None, upper_bound=None, fval=None):
+ """Line-search algorithm using fminbound.
+
+ Find the minimum of the function ``func(x0 + alpha*direc)``.
+
+ lower_bound : np.array.
+ The lower bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
+ should be ``-np.inf``.
+ Note ``np.shape(lower_bound) == (n,)``.
+ upper_bound : np.array.
+ The upper bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
+ should be ``np.inf``.
+ Note ``np.shape(upper_bound) == (n,)``.
+ fval : number.
+ ``fval`` is equal to ``func(p)``, the idea is just to avoid
+ recomputing it so we can limit the ``fevals``.
+
+ """
+ def myfunc(alpha):
+ return func(p + alpha*xi)
+
+ # if xi is zero, then don't optimize
+ if not np.any(xi):
+ return ((fval, p, xi) if fval is not None else (func(p), p, xi))
+ elif lower_bound is None and upper_bound is None:
+ # non-bounded minimization
+ res = _recover_from_bracket_error(_minimize_scalar_brent,
+ myfunc, None, tuple(), xtol=tol)
+ alpha_min, fret = res.x, res.fun
+ xi = alpha_min * xi
+ return fret, p + xi, xi
+ else:
+ bound = _line_for_search(p, xi, lower_bound, upper_bound)
+ if np.isneginf(bound[0]) and np.isposinf(bound[1]):
+ # equivalent to unbounded
+ return _linesearch_powell(func, p, xi, fval=fval, tol=tol)
+ elif not np.isneginf(bound[0]) and not np.isposinf(bound[1]):
+ # we can use a bounded scalar minimization
+ res = _minimize_scalar_bounded(myfunc, bound, xatol=tol / 100)
+ xi = res.x * xi
+ return res.fun, p + xi, xi
+ else:
+ # only bounded on one side. use the tangent function to convert
+ # the infinity bound to a finite bound. The new bounded region
+ # is a subregion of the region bounded by -np.pi/2 and np.pi/2.
+ bound = np.arctan(bound[0]), np.arctan(bound[1])
+ res = _minimize_scalar_bounded(
+ lambda x: myfunc(np.tan(x)),
+ bound,
+ xatol=tol / 100)
+ xi = np.tan(res.x) * xi
+ return res.fun, p + xi, xi
+
+
+def fmin_powell(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None,
+ maxfun=None, full_output=0, disp=1, retall=0, callback=None,
+ direc=None):
+ """
+ Minimize a function using modified Powell's method.
+
+ This method only uses function values, not derivatives.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function to be minimized.
+ x0 : ndarray
+ Initial guess.
+ args : tuple, optional
+ Extra arguments passed to func.
+ xtol : float, optional
+ Line-search error tolerance.
+ ftol : float, optional
+ Relative error in ``func(xopt)`` acceptable for convergence.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ maxfun : int, optional
+ Maximum number of function evaluations to make.
+ full_output : bool, optional
+ If True, ``fopt``, ``xi``, ``direc``, ``iter``, ``funcalls``, and
+ ``warnflag`` are returned.
+ disp : bool, optional
+ If True, print convergence messages.
+ retall : bool, optional
+ If True, return a list of the solution at each iteration.
+ callback : callable, optional
+ An optional user-supplied function, called after each
+ iteration. Called as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ direc : ndarray, optional
+ Initial fitting step and parameter order set as an (N, N) array, where N
+ is the number of fitting parameters in `x0`. Defaults to step size 1.0
+ fitting all parameters simultaneously (``np.eye((N, N))``). To
+ prevent initial consideration of values in a step or to change initial
+ step size, set to 0 or desired step size in the Jth position in the Mth
+ block, where J is the position in `x0` and M is the desired evaluation
+ step, with steps being evaluated in index order. Step size and ordering
+ will change freely as minimization proceeds.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameter which minimizes `func`.
+ fopt : number
+ Value of function at minimum: ``fopt = func(xopt)``.
+ direc : ndarray
+ Current direction set.
+ iter : int
+ Number of iterations.
+ funcalls : int
+ Number of function calls made.
+ warnflag : int
+ Integer warning flag:
+ 1 : Maximum number of function evaluations.
+ 2 : Maximum number of iterations.
+ 3 : NaN result encountered.
+ 4 : The result is out of the provided bounds.
+ allvecs : list
+ List of solutions at each iteration.
+
+ See Also
+ --------
+ minimize: Interface to unconstrained minimization algorithms for
+ multivariate functions. See the 'Powell' method in particular.
+
+ Notes
+ -----
+ Uses a modification of Powell's method to find the minimum of
+ a function of N variables. Powell's method is a conjugate
+ direction method.
+
+ The algorithm has two loops. The outer loop merely iterates over the inner
+ loop. The inner loop minimizes over each current direction in the direction
+ set. At the end of the inner loop, if certain conditions are met, the
+ direction that gave the largest decrease is dropped and replaced with the
+ difference between the current estimated x and the estimated x from the
+ beginning of the inner-loop.
+
+ The technical conditions for replacing the direction of greatest
+ increase amount to checking that
+
+ 1. No further gain can be made along the direction of greatest increase
+ from that iteration.
+ 2. The direction of greatest increase accounted for a large sufficient
+ fraction of the decrease in the function value from that iteration of
+ the inner loop.
+
+ References
+ ----------
+ Powell M.J.D. (1964) An efficient method for finding the minimum of a
+ function of several variables without calculating derivatives,
+ Computer Journal, 7 (2):155-162.
+
+ Press W., Teukolsky S.A., Vetterling W.T., and Flannery B.P.:
+ Numerical Recipes (any edition), Cambridge University Press
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return x**2
+
+ >>> from scipy import optimize
+
+ >>> minimum = optimize.fmin_powell(f, -1)
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 2
+ Function evaluations: 16
+ >>> minimum
+ array(0.0)
+
+ """
+ opts = {'xtol': xtol,
+ 'ftol': ftol,
+ 'maxiter': maxiter,
+ 'maxfev': maxfun,
+ 'disp': disp,
+ 'direc': direc,
+ 'return_all': retall}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_powell(func, x0, args, callback=callback, **opts)
+
+ if full_output:
+ retlist = (res['x'], res['fun'], res['direc'], res['nit'],
+ res['nfev'], res['status'])
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_powell(func, x0, args=(), callback=None, bounds=None,
+ xtol=1e-4, ftol=1e-4, maxiter=None, maxfev=None,
+ disp=False, direc=None, return_all=False,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ modified Powell algorithm.
+
+ Parameters
+ ----------
+ fun : callable
+ The objective function to be minimized::
+
+ fun(x, *args) -> float
+
+ where ``x`` is a 1-D array with shape (n,) and ``args``
+ is a tuple of the fixed parameters needed to completely
+ specify the function.
+ x0 : ndarray, shape (n,)
+ Initial guess. Array of real elements of size (n,),
+ where ``n`` is the number of independent variables.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its
+ derivatives (`fun`, `jac` and `hess` functions).
+ method : str or callable, optional
+ The present documentation is specific to ``method='powell'``, but other
+ options are available. See documentation for `scipy.optimize.minimize`.
+ bounds : sequence or `Bounds`, optional
+ Bounds on decision variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
+ is used to specify no bound.
+
+ If bounds are not provided, then an unbounded line search will be used.
+ If bounds are provided and the initial guess is within the bounds, then
+ every function evaluation throughout the minimization procedure will be
+ within the bounds. If bounds are provided, the initial guess is outside
+ the bounds, and `direc` is full rank (or left to default), then some
+ function evaluations during the first iteration may be outside the
+ bounds, but every function evaluation after the first iteration will be
+ within the bounds. If `direc` is not full rank, then some parameters
+ may not be optimized and the solution is not guaranteed to be within
+ the bounds.
+
+ options : dict, optional
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform. Depending on the
+ method each iteration may use several function evaluations.
+ disp : bool
+ Set to True to print convergence messages.
+
+ See method-specific options for ``method='powell'`` below.
+ callback : callable, optional
+ Called after each iteration. The signature is::
+
+ callback(xk)
+
+ where ``xk`` is the current parameter vector.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ xtol : float
+ Relative error in solution `xopt` acceptable for convergence.
+ ftol : float
+ Relative error in ``fun(xopt)`` acceptable for convergence.
+ maxiter, maxfev : int
+ Maximum allowed number of iterations and function evaluations.
+ Will default to ``N*1000``, where ``N`` is the number of
+ variables, if neither `maxiter` or `maxfev` is set. If both
+ `maxiter` and `maxfev` are set, minimization will stop at the
+ first reached.
+ direc : ndarray
+ Initial set of direction vectors for the Powell method.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ """
+ _check_unknown_options(unknown_options)
+ maxfun = maxfev
+ retall = return_all
+
+ x = asarray(x0).flatten()
+ if retall:
+ allvecs = [x]
+ N = len(x)
+ # If neither are set, then set both to default
+ if maxiter is None and maxfun is None:
+ maxiter = N * 1000
+ maxfun = N * 1000
+ elif maxiter is None:
+ # Convert remaining Nones, to np.inf, unless the other is np.inf, in
+ # which case use the default to avoid unbounded iteration
+ if maxfun == np.inf:
+ maxiter = N * 1000
+ else:
+ maxiter = np.inf
+ elif maxfun is None:
+ if maxiter == np.inf:
+ maxfun = N * 1000
+ else:
+ maxfun = np.inf
+
+ # we need to use a mutable object here that we can update in the
+ # wrapper function
+ fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun)
+
+ if direc is None:
+ direc = eye(N, dtype=float)
+ else:
+ direc = asarray(direc, dtype=float)
+ if np.linalg.matrix_rank(direc) != direc.shape[0]:
+ warnings.warn("direc input is not full rank, some parameters may "
+ "not be optimized",
+ OptimizeWarning, stacklevel=3)
+
+ if bounds is None:
+ # don't make these arrays of all +/- inf. because
+ # _linesearch_powell will do an unnecessary check of all the elements.
+ # just keep them None, _linesearch_powell will not have to check
+ # all the elements.
+ lower_bound, upper_bound = None, None
+ else:
+ # bounds is standardized in _minimize.py.
+ lower_bound, upper_bound = bounds.lb, bounds.ub
+ if np.any(lower_bound > x0) or np.any(x0 > upper_bound):
+ warnings.warn("Initial guess is not within the specified bounds",
+ OptimizeWarning, stacklevel=3)
+
+ fval = func(x)
+ x1 = x.copy()
+ iter = 0
+ while True:
+ try:
+ fx = fval
+ bigind = 0
+ delta = 0.0
+ for i in range(N):
+ direc1 = direc[i]
+ fx2 = fval
+ fval, x, direc1 = _linesearch_powell(func, x, direc1,
+ tol=xtol * 100,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ if (fx2 - fval) > delta:
+ delta = fx2 - fval
+ bigind = i
+ iter += 1
+ if retall:
+ allvecs.append(x)
+ intermediate_result = OptimizeResult(x=x, fun=fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+ bnd = ftol * (np.abs(fx) + np.abs(fval)) + 1e-20
+ if 2.0 * (fx - fval) <= bnd:
+ break
+ if fcalls[0] >= maxfun:
+ break
+ if iter >= maxiter:
+ break
+ if np.isnan(fx) and np.isnan(fval):
+ # Ended up in a nan-region: bail out
+ break
+
+ # Construct the extrapolated point
+ direc1 = x - x1
+ x1 = x.copy()
+ # make sure that we don't go outside the bounds when extrapolating
+ if lower_bound is None and upper_bound is None:
+ lmax = 1
+ else:
+ _, lmax = _line_for_search(x, direc1, lower_bound, upper_bound)
+ x2 = x + min(lmax, 1) * direc1
+ fx2 = func(x2)
+
+ if (fx > fx2):
+ t = 2.0*(fx + fx2 - 2.0*fval)
+ temp = (fx - fval - delta)
+ t *= temp*temp
+ temp = fx - fx2
+ t -= delta*temp*temp
+ if t < 0.0:
+ fval, x, direc1 = _linesearch_powell(
+ func, x, direc1,
+ tol=xtol * 100,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval
+ )
+ if np.any(direc1):
+ direc[bigind] = direc[-1]
+ direc[-1] = direc1
+ except _MaxFuncCallError:
+ break
+
+ warnflag = 0
+ msg = _status_message['success']
+ # out of bounds is more urgent than exceeding function evals or iters,
+ # but I don't want to cause inconsistencies by changing the
+ # established warning flags for maxfev and maxiter, so the out of bounds
+ # warning flag becomes 3, but is checked for first.
+ if bounds and (np.any(lower_bound > x) or np.any(x > upper_bound)):
+ warnflag = 4
+ msg = _status_message['out_of_bounds']
+ elif fcalls[0] >= maxfun:
+ warnflag = 1
+ msg = _status_message['maxfev']
+ elif iter >= maxiter:
+ warnflag = 2
+ msg = _status_message['maxiter']
+ elif np.isnan(fval) or np.isnan(x).any():
+ warnflag = 3
+ msg = _status_message['nan']
+
+ if disp:
+ _print_success_message_or_warn(warnflag, msg, RuntimeWarning)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {iter:d}")
+ print(f" Function evaluations: {fcalls[0]:d}")
+ result = OptimizeResult(fun=fval, direc=direc, nit=iter, nfev=fcalls[0],
+ status=warnflag, success=(warnflag == 0),
+ message=msg, x=x)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def _endprint(x, flag, fval, maxfun, xtol, disp):
+ if flag == 0:
+ if disp > 1:
+ print("\nOptimization terminated successfully;\n"
+ "The returned value satisfies the termination criteria\n"
+ "(using xtol = ", xtol, ")")
+ return
+
+ if flag == 1:
+ msg = ("\nMaximum number of function evaluations exceeded --- "
+ "increase maxfun argument.\n")
+ elif flag == 2:
+ msg = f"\n{_status_message['nan']}"
+
+ _print_success_message_or_warn(flag, msg)
+ return
+
+
+def brute(func, ranges, args=(), Ns=20, full_output=0, finish=fmin,
+ disp=False, workers=1):
+ """Minimize a function over a given range by brute force.
+
+ Uses the "brute force" method, i.e., computes the function's value
+ at each point of a multidimensional grid of points, to find the global
+ minimum of the function.
+
+ The function is evaluated everywhere in the range with the datatype of the
+ first call to the function, as enforced by the ``vectorize`` NumPy
+ function. The value and type of the function evaluation returned when
+ ``full_output=True`` are affected in addition by the ``finish`` argument
+ (see Notes).
+
+ The brute force approach is inefficient because the number of grid points
+ increases exponentially - the number of grid points to evaluate is
+ ``Ns ** len(x)``. Consequently, even with coarse grid spacing, even
+ moderately sized problems can take a long time to run, and/or run into
+ memory limitations.
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the
+ form ``f(x, *args)``, where ``x`` is the argument in
+ the form of a 1-D array and ``args`` is a tuple of any
+ additional fixed parameters needed to completely specify
+ the function.
+ ranges : tuple
+ Each component of the `ranges` tuple must be either a
+ "slice object" or a range tuple of the form ``(low, high)``.
+ The program uses these to create the grid of points on which
+ the objective function will be computed. See `Note 2` for
+ more detail.
+ args : tuple, optional
+ Any additional fixed parameters needed to completely specify
+ the function.
+ Ns : int, optional
+ Number of grid points along the axes, if not otherwise
+ specified. See `Note2`.
+ full_output : bool, optional
+ If True, return the evaluation grid and the objective function's
+ values on it.
+ finish : callable, optional
+ An optimization function that is called with the result of brute force
+ minimization as initial guess. `finish` should take `func` and
+ the initial guess as positional arguments, and take `args` as
+ keyword arguments. It may additionally take `full_output`
+ and/or `disp` as keyword arguments. Use None if no "polishing"
+ function is to be used. See Notes for more details.
+ disp : bool, optional
+ Set to True to print convergence messages from the `finish` callable.
+ workers : int or map-like callable, optional
+ If `workers` is an int the grid is subdivided into `workers`
+ sections and evaluated in parallel (uses
+ `multiprocessing.Pool `).
+ Supply `-1` to use all cores available to the Process.
+ Alternatively supply a map-like callable, such as
+ `multiprocessing.Pool.map` for evaluating the grid in parallel.
+ This evaluation is carried out as ``workers(func, iterable)``.
+ Requires that `func` be pickleable.
+
+ .. versionadded:: 1.3.0
+
+ Returns
+ -------
+ x0 : ndarray
+ A 1-D array containing the coordinates of a point at which the
+ objective function had its minimum value. (See `Note 1` for
+ which point is returned.)
+ fval : float
+ Function value at the point `x0`. (Returned when `full_output` is
+ True.)
+ grid : tuple
+ Representation of the evaluation grid. It has the same
+ length as `x0`. (Returned when `full_output` is True.)
+ Jout : ndarray
+ Function values at each point of the evaluation
+ grid, i.e., ``Jout = func(*grid)``. (Returned
+ when `full_output` is True.)
+
+ See Also
+ --------
+ basinhopping, differential_evolution
+
+ Notes
+ -----
+ *Note 1*: The program finds the gridpoint at which the lowest value
+ of the objective function occurs. If `finish` is None, that is the
+ point returned. When the global minimum occurs within (or not very far
+ outside) the grid's boundaries, and the grid is fine enough, that
+ point will be in the neighborhood of the global minimum.
+
+ However, users often employ some other optimization program to
+ "polish" the gridpoint values, i.e., to seek a more precise
+ (local) minimum near `brute's` best gridpoint.
+ The `brute` function's `finish` option provides a convenient way to do
+ that. Any polishing program used must take `brute's` output as its
+ initial guess as a positional argument, and take `brute's` input values
+ for `args` as keyword arguments, otherwise an error will be raised.
+ It may additionally take `full_output` and/or `disp` as keyword arguments.
+
+ `brute` assumes that the `finish` function returns either an
+ `OptimizeResult` object or a tuple in the form:
+ ``(xmin, Jmin, ... , statuscode)``, where ``xmin`` is the minimizing
+ value of the argument, ``Jmin`` is the minimum value of the objective
+ function, "..." may be some other returned values (which are not used
+ by `brute`), and ``statuscode`` is the status code of the `finish` program.
+
+ Note that when `finish` is not None, the values returned are those
+ of the `finish` program, *not* the gridpoint ones. Consequently,
+ while `brute` confines its search to the input grid points,
+ the `finish` program's results usually will not coincide with any
+ gridpoint, and may fall outside the grid's boundary. Thus, if a
+ minimum only needs to be found over the provided grid points, make
+ sure to pass in ``finish=None``.
+
+ *Note 2*: The grid of points is a `numpy.mgrid` object.
+ For `brute` the `ranges` and `Ns` inputs have the following effect.
+ Each component of the `ranges` tuple can be either a slice object or a
+ two-tuple giving a range of values, such as (0, 5). If the component is a
+ slice object, `brute` uses it directly. If the component is a two-tuple
+ range, `brute` internally converts it to a slice object that interpolates
+ `Ns` points from its low-value to its high-value, inclusive.
+
+ Examples
+ --------
+ We illustrate the use of `brute` to seek the global minimum of a function
+ of two variables that is given as the sum of a positive-definite
+ quadratic and two deep "Gaussian-shaped" craters. Specifically, define
+ the objective function `f` as the sum of three other functions,
+ ``f = f1 + f2 + f3``. We suppose each of these has a signature
+ ``(z, *params)``, where ``z = (x, y)``, and ``params`` and the functions
+ are as defined below.
+
+ >>> import numpy as np
+ >>> params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
+ >>> def f1(z, *params):
+ ... x, y = z
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ ... return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
+
+ >>> def f2(z, *params):
+ ... x, y = z
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ ... return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale))
+
+ >>> def f3(z, *params):
+ ... x, y = z
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ ... return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale))
+
+ >>> def f(z, *params):
+ ... return f1(z, *params) + f2(z, *params) + f3(z, *params)
+
+ Thus, the objective function may have local minima near the minimum
+ of each of the three functions of which it is composed. To
+ use `fmin` to polish its gridpoint result, we may then continue as
+ follows:
+
+ >>> rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
+ >>> from scipy import optimize
+ >>> resbrute = optimize.brute(f, rranges, args=params, full_output=True,
+ ... finish=optimize.fmin)
+ >>> resbrute[0] # global minimum
+ array([-1.05665192, 1.80834843])
+ >>> resbrute[1] # function value at global minimum
+ -3.4085818767
+
+ Note that if `finish` had been set to None, we would have gotten the
+ gridpoint [-1.0 1.75] where the rounded function value is -2.892.
+
+ """
+ N = len(ranges)
+ if N > 40:
+ raise ValueError("Brute Force not possible with more "
+ "than 40 variables.")
+ lrange = list(ranges)
+ for k in range(N):
+ if not isinstance(lrange[k], slice):
+ if len(lrange[k]) < 3:
+ lrange[k] = tuple(lrange[k]) + (complex(Ns),)
+ lrange[k] = slice(*lrange[k])
+ if (N == 1):
+ lrange = lrange[0]
+
+ grid = np.mgrid[lrange]
+
+ # obtain an array of parameters that is iterable by a map-like callable
+ inpt_shape = grid.shape
+ if (N > 1):
+ grid = np.reshape(grid, (inpt_shape[0], np.prod(inpt_shape[1:]))).T
+
+ if not np.iterable(args):
+ args = (args,)
+
+ wrapped_func = _Brute_Wrapper(func, args)
+
+ # iterate over input arrays, possibly in parallel
+ with MapWrapper(pool=workers) as mapper:
+ Jout = np.array(list(mapper(wrapped_func, grid)))
+ if (N == 1):
+ grid = (grid,)
+ Jout = np.squeeze(Jout)
+ elif (N > 1):
+ Jout = np.reshape(Jout, inpt_shape[1:])
+ grid = np.reshape(grid.T, inpt_shape)
+
+ Nshape = shape(Jout)
+
+ indx = argmin(Jout.ravel(), axis=-1)
+ Nindx = np.empty(N, int)
+ xmin = np.empty(N, float)
+ for k in range(N - 1, -1, -1):
+ thisN = Nshape[k]
+ Nindx[k] = indx % Nshape[k]
+ indx = indx // thisN
+ for k in range(N):
+ xmin[k] = grid[k][tuple(Nindx)]
+
+ Jmin = Jout[tuple(Nindx)]
+ if (N == 1):
+ grid = grid[0]
+ xmin = xmin[0]
+
+ if callable(finish):
+ # set up kwargs for `finish` function
+ finish_args = _getfullargspec(finish).args
+ finish_kwargs = dict()
+ if 'full_output' in finish_args:
+ finish_kwargs['full_output'] = 1
+ if 'disp' in finish_args:
+ finish_kwargs['disp'] = disp
+ elif 'options' in finish_args:
+ # pass 'disp' as `options`
+ # (e.g., if `finish` is `minimize`)
+ finish_kwargs['options'] = {'disp': disp}
+
+ # run minimizer
+ res = finish(func, xmin, args=args, **finish_kwargs)
+
+ if isinstance(res, OptimizeResult):
+ xmin = res.x
+ Jmin = res.fun
+ success = res.success
+ else:
+ xmin = res[0]
+ Jmin = res[1]
+ success = res[-1] == 0
+ if not success:
+ if disp:
+ warnings.warn("Either final optimization did not succeed or `finish` "
+ "does not return `statuscode` as its last argument.",
+ RuntimeWarning, stacklevel=2)
+
+ if full_output:
+ return xmin, Jmin, grid, Jout
+ else:
+ return xmin
+
+
+class _Brute_Wrapper:
+ """
+ Object to wrap user cost function for optimize.brute, allowing picklability
+ """
+
+ def __init__(self, f, args):
+ self.f = f
+ self.args = [] if args is None else args
+
+ def __call__(self, x):
+ # flatten needed for one dimensional case.
+ return self.f(np.asarray(x).flatten(), *self.args)
+
+
+def show_options(solver=None, method=None, disp=True):
+ """
+ Show documentation for additional options of optimization solvers.
+
+ These are method-specific options that can be supplied through the
+ ``options`` dict.
+
+ Parameters
+ ----------
+ solver : str
+ Type of optimization solver. One of 'minimize', 'minimize_scalar',
+ 'root', 'root_scalar', 'linprog', or 'quadratic_assignment'.
+ method : str, optional
+ If not given, shows all methods of the specified solver. Otherwise,
+ show only the options for the specified method. Valid values
+ corresponds to methods' names of respective solver (e.g., 'BFGS' for
+ 'minimize').
+ disp : bool, optional
+ Whether to print the result rather than returning it.
+
+ Returns
+ -------
+ text
+ Either None (for disp=True) or the text string (disp=False)
+
+ Notes
+ -----
+ The solver-specific methods are:
+
+ `scipy.optimize.minimize`
+
+ - :ref:`Nelder-Mead `
+ - :ref:`Powell `
+ - :ref:`CG `
+ - :ref:`BFGS `
+ - :ref:`Newton-CG `
+ - :ref:`L-BFGS-B `
+ - :ref:`TNC `
+ - :ref:`COBYLA `
+ - :ref:`COBYQA `
+ - :ref:`SLSQP `
+ - :ref:`dogleg `
+ - :ref:`trust-ncg `
+
+ `scipy.optimize.root`
+
+ - :ref:`hybr `
+ - :ref:`lm `
+ - :ref:`broyden1 `
+ - :ref:`broyden2 `
+ - :ref:`anderson `
+ - :ref:`linearmixing `
+ - :ref:`diagbroyden `
+ - :ref:`excitingmixing `
+ - :ref:`krylov `
+ - :ref:`df-sane `
+
+ `scipy.optimize.minimize_scalar`
+
+ - :ref:`brent `
+ - :ref:`golden `
+ - :ref:`bounded `
+
+ `scipy.optimize.root_scalar`
+
+ - :ref:`bisect `
+ - :ref:`brentq `
+ - :ref:`brenth `
+ - :ref:`ridder `
+ - :ref:`toms748 `
+ - :ref:`newton `
+ - :ref:`secant `
+ - :ref:`halley `
+
+ `scipy.optimize.linprog`
+
+ - :ref:`simplex `
+ - :ref:`interior-point `
+ - :ref:`revised simplex `
+ - :ref:`highs `
+ - :ref:`highs-ds `
+ - :ref:`highs-ipm `
+
+ `scipy.optimize.quadratic_assignment`
+
+ - :ref:`faq `
+ - :ref:`2opt `
+
+ Examples
+ --------
+ We can print documentations of a solver in stdout:
+
+ >>> from scipy.optimize import show_options
+ >>> show_options(solver="minimize")
+ ...
+
+ Specifying a method is possible:
+
+ >>> show_options(solver="minimize", method="Nelder-Mead")
+ ...
+
+ We can also get the documentations as a string:
+
+ >>> show_options(solver="minimize", method="Nelder-Mead", disp=False)
+ Minimization of scalar function of one or more variables using the ...
+
+ """
+ import textwrap
+
+ doc_routines = {
+ 'minimize': (
+ ('bfgs', 'scipy.optimize._optimize._minimize_bfgs'),
+ ('cg', 'scipy.optimize._optimize._minimize_cg'),
+ ('cobyla', 'scipy.optimize._cobyla_py._minimize_cobyla'),
+ ('cobyqa', 'scipy.optimize._cobyqa_py._minimize_cobyqa'),
+ ('dogleg', 'scipy.optimize._trustregion_dogleg._minimize_dogleg'),
+ ('l-bfgs-b', 'scipy.optimize._lbfgsb_py._minimize_lbfgsb'),
+ ('nelder-mead', 'scipy.optimize._optimize._minimize_neldermead'),
+ ('newton-cg', 'scipy.optimize._optimize._minimize_newtoncg'),
+ ('powell', 'scipy.optimize._optimize._minimize_powell'),
+ ('slsqp', 'scipy.optimize._slsqp_py._minimize_slsqp'),
+ ('tnc', 'scipy.optimize._tnc._minimize_tnc'),
+ ('trust-ncg',
+ 'scipy.optimize._trustregion_ncg._minimize_trust_ncg'),
+ ('trust-constr',
+ 'scipy.optimize._trustregion_constr.'
+ '_minimize_trustregion_constr'),
+ ('trust-exact',
+ 'scipy.optimize._trustregion_exact._minimize_trustregion_exact'),
+ ('trust-krylov',
+ 'scipy.optimize._trustregion_krylov._minimize_trust_krylov'),
+ ),
+ 'root': (
+ ('hybr', 'scipy.optimize._minpack_py._root_hybr'),
+ ('lm', 'scipy.optimize._root._root_leastsq'),
+ ('broyden1', 'scipy.optimize._root._root_broyden1_doc'),
+ ('broyden2', 'scipy.optimize._root._root_broyden2_doc'),
+ ('anderson', 'scipy.optimize._root._root_anderson_doc'),
+ ('diagbroyden', 'scipy.optimize._root._root_diagbroyden_doc'),
+ ('excitingmixing', 'scipy.optimize._root._root_excitingmixing_doc'),
+ ('linearmixing', 'scipy.optimize._root._root_linearmixing_doc'),
+ ('krylov', 'scipy.optimize._root._root_krylov_doc'),
+ ('df-sane', 'scipy.optimize._spectral._root_df_sane'),
+ ),
+ 'root_scalar': (
+ ('bisect', 'scipy.optimize._root_scalar._root_scalar_bisect_doc'),
+ ('brentq', 'scipy.optimize._root_scalar._root_scalar_brentq_doc'),
+ ('brenth', 'scipy.optimize._root_scalar._root_scalar_brenth_doc'),
+ ('ridder', 'scipy.optimize._root_scalar._root_scalar_ridder_doc'),
+ ('toms748', 'scipy.optimize._root_scalar._root_scalar_toms748_doc'),
+ ('secant', 'scipy.optimize._root_scalar._root_scalar_secant_doc'),
+ ('newton', 'scipy.optimize._root_scalar._root_scalar_newton_doc'),
+ ('halley', 'scipy.optimize._root_scalar._root_scalar_halley_doc'),
+ ),
+ 'linprog': (
+ ('simplex', 'scipy.optimize._linprog._linprog_simplex_doc'),
+ ('interior-point', 'scipy.optimize._linprog._linprog_ip_doc'),
+ ('revised simplex', 'scipy.optimize._linprog._linprog_rs_doc'),
+ ('highs-ipm', 'scipy.optimize._linprog._linprog_highs_ipm_doc'),
+ ('highs-ds', 'scipy.optimize._linprog._linprog_highs_ds_doc'),
+ ('highs', 'scipy.optimize._linprog._linprog_highs_doc'),
+ ),
+ 'quadratic_assignment': (
+ ('faq', 'scipy.optimize._qap._quadratic_assignment_faq'),
+ ('2opt', 'scipy.optimize._qap._quadratic_assignment_2opt'),
+ ),
+ 'minimize_scalar': (
+ ('brent', 'scipy.optimize._optimize._minimize_scalar_brent'),
+ ('bounded', 'scipy.optimize._optimize._minimize_scalar_bounded'),
+ ('golden', 'scipy.optimize._optimize._minimize_scalar_golden'),
+ ),
+ }
+
+ if solver is None:
+ text = ["\n\n\n========\n", "minimize\n", "========\n"]
+ text.append(show_options('minimize', disp=False))
+ text.extend(["\n\n===============\n", "minimize_scalar\n",
+ "===============\n"])
+ text.append(show_options('minimize_scalar', disp=False))
+ text.extend(["\n\n\n====\n", "root\n",
+ "====\n"])
+ text.append(show_options('root', disp=False))
+ text.extend(['\n\n\n=======\n', 'linprog\n',
+ '=======\n'])
+ text.append(show_options('linprog', disp=False))
+ text = "".join(text)
+ else:
+ solver = solver.lower()
+ if solver not in doc_routines:
+ raise ValueError(f'Unknown solver {solver!r}')
+
+ if method is None:
+ text = []
+ for name, _ in doc_routines[solver]:
+ text.extend(["\n\n" + name, "\n" + "="*len(name) + "\n\n"])
+ text.append(show_options(solver, name, disp=False))
+ text = "".join(text)
+ else:
+ method = method.lower()
+ methods = dict(doc_routines[solver])
+ if method not in methods:
+ raise ValueError(f"Unknown method {method!r}")
+ name = methods[method]
+
+ # Import function object
+ parts = name.split('.')
+ mod_name = ".".join(parts[:-1])
+ __import__(mod_name)
+ obj = getattr(sys.modules[mod_name], parts[-1])
+
+ # Get doc
+ doc = obj.__doc__
+ if doc is not None:
+ text = textwrap.dedent(doc).strip()
+ else:
+ text = ""
+
+ if disp:
+ print(text)
+ return
+ else:
+ return text
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..00c042764d56a48ff172842c506e8664221937d7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7a3d9b3ae2c6f26621e34c9a6d0384ca0cd9d58534c7c8d3a1ce2e4a9edb7a69
+size 202576
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_qap.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_qap.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d5713b252d7a71bbd9af3b60e9e0564f7e8922b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_qap.py
@@ -0,0 +1,717 @@
+import numpy as np
+import operator
+from . import (linear_sum_assignment, OptimizeResult)
+from ._optimize import _check_unknown_options
+
+import itertools
+
+QUADRATIC_ASSIGNMENT_METHODS = ['faq', '2opt']
+
+
+def quadratic_assignment(A, B, method="faq", options=None):
+ r"""
+ Approximates solution to the quadratic assignment problem and
+ the graph matching problem.
+
+ Quadratic assignment solves problems of the following form:
+
+ .. math::
+
+ \min_P & \ {\ \text{trace}(A^T P B P^T)}\\
+ \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\
+
+ where :math:`\mathcal{P}` is the set of all permutation matrices,
+ and :math:`A` and :math:`B` are square matrices.
+
+ Graph matching tries to *maximize* the same objective function.
+ This algorithm can be thought of as finding the alignment of the
+ nodes of two graphs that minimizes the number of induced edge
+ disagreements, or, in the case of weighted graphs, the sum of squared
+ edge weight differences.
+
+ Note that the quadratic assignment problem is NP-hard. The results given
+ here are approximations and are not guaranteed to be optimal.
+
+
+ Parameters
+ ----------
+ A : 2-D array, square
+ The square matrix :math:`A` in the objective function above.
+
+ B : 2-D array, square
+ The square matrix :math:`B` in the objective function above.
+
+ method : str in {'faq', '2opt'} (default: 'faq')
+ The algorithm used to solve the problem.
+ :ref:`'faq' ` (default) and
+ :ref:`'2opt' ` are available.
+
+ options : dict, optional
+ A dictionary of solver options. All solvers support the following:
+
+ maximize : bool (default: False)
+ Maximizes the objective function if ``True``.
+
+ partial_match : 2-D array of integers, optional (default: None)
+ Fixes part of the matching. Also known as a "seed" [2]_.
+
+ Each row of `partial_match` specifies a pair of matched nodes:
+ node ``partial_match[i, 0]`` of `A` is matched to node
+ ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``,
+ where ``m`` is not greater than the number of nodes, :math:`n`.
+
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+ For method-specific options, see
+ :func:`show_options('quadratic_assignment') `.
+
+ Returns
+ -------
+ res : OptimizeResult
+ `OptimizeResult` containing the following fields.
+
+ col_ind : 1-D array
+ Column indices corresponding to the best permutation found of the
+ nodes of `B`.
+ fun : float
+ The objective value of the solution.
+ nit : int
+ The number of iterations performed during optimization.
+
+ Notes
+ -----
+ The default method :ref:`'faq' ` uses the Fast
+ Approximate QAP algorithm [1]_; it typically offers the best combination of
+ speed and accuracy.
+ Method :ref:`'2opt' ` can be computationally expensive,
+ but may be a useful alternative, or it can be used to refine the solution
+ returned by another method.
+
+ References
+ ----------
+ .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik,
+ S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and
+ C.E. Priebe, "Fast approximate quadratic programming for graph
+ matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015,
+ :doi:`10.1371/journal.pone.0121002`
+
+ .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski,
+ C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019):
+ 203-215, :doi:`10.1016/j.patcog.2018.09.014`
+
+ .. [3] "2-opt," Wikipedia.
+ https://en.wikipedia.org/wiki/2-opt
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import quadratic_assignment
+ >>> rng = np.random.default_rng()
+ >>> A = np.array([[0, 80, 150, 170], [80, 0, 130, 100],
+ ... [150, 130, 0, 120], [170, 100, 120, 0]])
+ >>> B = np.array([[0, 5, 2, 7], [0, 0, 3, 8],
+ ... [0, 0, 0, 3], [0, 0, 0, 0]])
+ >>> res = quadratic_assignment(A, B, options={'rng': rng})
+ >>> print(res)
+ fun: 3260
+ col_ind: [0 3 2 1]
+ nit: 9
+
+ The see the relationship between the returned ``col_ind`` and ``fun``,
+ use ``col_ind`` to form the best permutation matrix found, then evaluate
+ the objective function :math:`f(P) = trace(A^T P B P^T )`.
+
+ >>> perm = res['col_ind']
+ >>> P = np.eye(len(A), dtype=int)[perm]
+ >>> fun = np.trace(A.T @ P @ B @ P.T)
+ >>> print(fun)
+ 3260
+
+ Alternatively, to avoid constructing the permutation matrix explicitly,
+ directly permute the rows and columns of the distance matrix.
+
+ >>> fun = np.trace(A.T @ B[perm][:, perm])
+ >>> print(fun)
+ 3260
+
+ Although not guaranteed in general, ``quadratic_assignment`` happens to
+ have found the globally optimal solution.
+
+ >>> from itertools import permutations
+ >>> perm_opt, fun_opt = None, np.inf
+ >>> for perm in permutations([0, 1, 2, 3]):
+ ... perm = np.array(perm)
+ ... fun = np.trace(A.T @ B[perm][:, perm])
+ ... if fun < fun_opt:
+ ... fun_opt, perm_opt = fun, perm
+ >>> print(np.array_equal(perm_opt, res['col_ind']))
+ True
+
+ Here is an example for which the default method,
+ :ref:`'faq' `, does not find the global optimum.
+
+ >>> A = np.array([[0, 5, 8, 6], [5, 0, 5, 1],
+ ... [8, 5, 0, 2], [6, 1, 2, 0]])
+ >>> B = np.array([[0, 1, 8, 4], [1, 0, 5, 2],
+ ... [8, 5, 0, 5], [4, 2, 5, 0]])
+ >>> res = quadratic_assignment(A, B, options={'rng': rng})
+ >>> print(res)
+ fun: 178
+ col_ind: [1 0 3 2]
+ nit: 13
+
+ If accuracy is important, consider using :ref:`'2opt' `
+ to refine the solution.
+
+ >>> guess = np.array([np.arange(len(A)), res.col_ind]).T
+ >>> res = quadratic_assignment(A, B, method="2opt",
+ ... options = {'rng': rng, 'partial_guess': guess})
+ >>> print(res)
+ fun: 176
+ col_ind: [1 2 3 0]
+ nit: 17
+
+ """
+
+ if options is None:
+ options = {}
+
+ method = method.lower()
+ methods = {"faq": _quadratic_assignment_faq,
+ "2opt": _quadratic_assignment_2opt}
+ if method not in methods:
+ raise ValueError(f"method {method} must be in {methods}.")
+
+ res = methods[method](A, B, **options)
+ return res
+
+
+def _calc_score(A, B, perm):
+ # equivalent to objective function but avoids matmul
+ return np.sum(A * B[perm][:, perm])
+
+
+def _common_input_validation(A, B, partial_match):
+ A = np.atleast_2d(A)
+ B = np.atleast_2d(B)
+
+ if partial_match is None:
+ partial_match = np.array([[], []]).T
+ partial_match = np.atleast_2d(partial_match).astype(int)
+
+ msg = None
+ if A.shape[0] != A.shape[1]:
+ msg = "`A` must be square"
+ elif B.shape[0] != B.shape[1]:
+ msg = "`B` must be square"
+ elif A.ndim != 2 or B.ndim != 2:
+ msg = "`A` and `B` must have exactly two dimensions"
+ elif A.shape != B.shape:
+ msg = "`A` and `B` matrices must be of equal size"
+ elif partial_match.shape[0] > A.shape[0]:
+ msg = "`partial_match` can have only as many seeds as there are nodes"
+ elif partial_match.shape[1] != 2:
+ msg = "`partial_match` must have two columns"
+ elif partial_match.ndim != 2:
+ msg = "`partial_match` must have exactly two dimensions"
+ elif (partial_match < 0).any():
+ msg = "`partial_match` must contain only positive indices"
+ elif (partial_match >= len(A)).any():
+ msg = "`partial_match` entries must be less than number of nodes"
+ elif (not len(set(partial_match[:, 0])) == len(partial_match[:, 0]) or
+ not len(set(partial_match[:, 1])) == len(partial_match[:, 1])):
+ msg = "`partial_match` column entries must be unique"
+
+ if msg is not None:
+ raise ValueError(msg)
+
+ return A, B, partial_match
+
+
+def _quadratic_assignment_faq(A, B,
+ maximize=False, partial_match=None, rng=None,
+ P0="barycenter", shuffle_input=False, maxiter=30,
+ tol=0.03, **unknown_options):
+ r"""Solve the quadratic assignment problem (approximately).
+
+ This function solves the Quadratic Assignment Problem (QAP) and the
+ Graph Matching Problem (GMP) using the Fast Approximate QAP Algorithm
+ (FAQ) [1]_.
+
+ Quadratic assignment solves problems of the following form:
+
+ .. math::
+
+ \min_P & \ {\ \text{trace}(A^T P B P^T)}\\
+ \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\
+
+ where :math:`\mathcal{P}` is the set of all permutation matrices,
+ and :math:`A` and :math:`B` are square matrices.
+
+ Graph matching tries to *maximize* the same objective function.
+ This algorithm can be thought of as finding the alignment of the
+ nodes of two graphs that minimizes the number of induced edge
+ disagreements, or, in the case of weighted graphs, the sum of squared
+ edge weight differences.
+
+ Note that the quadratic assignment problem is NP-hard. The results given
+ here are approximations and are not guaranteed to be optimal.
+
+ Parameters
+ ----------
+ A : 2-D array, square
+ The square matrix :math:`A` in the objective function above.
+ B : 2-D array, square
+ The square matrix :math:`B` in the objective function above.
+ method : str in {'faq', '2opt'} (default: 'faq')
+ The algorithm used to solve the problem. This is the method-specific
+ documentation for 'faq'.
+ :ref:`'2opt' ` is also available.
+
+ Options
+ -------
+ maximize : bool (default: False)
+ Maximizes the objective function if ``True``.
+ partial_match : 2-D array of integers, optional (default: None)
+ Fixes part of the matching. Also known as a "seed" [2]_.
+
+ Each row of `partial_match` specifies a pair of matched nodes:
+ node ``partial_match[i, 0]`` of `A` is matched to node
+ ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, where
+ ``m`` is not greater than the number of nodes, :math:`n`.
+
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Pseudorandom number generator state. See `quadratic_assignment` for details.
+ P0 : 2-D array, "barycenter", or "randomized" (default: "barycenter")
+ Initial position. Must be a doubly-stochastic matrix [3]_.
+
+ If the initial position is an array, it must be a doubly stochastic
+ matrix of size :math:`m' \times m'` where :math:`m' = n - m`.
+
+ If ``"barycenter"`` (default), the initial position is the barycenter
+ of the Birkhoff polytope (the space of doubly stochastic matrices).
+ This is a :math:`m' \times m'` matrix with all entries equal to
+ :math:`1 / m'`.
+
+ If ``"randomized"`` the initial search position is
+ :math:`P_0 = (J + K) / 2`, where :math:`J` is the barycenter and
+ :math:`K` is a random doubly stochastic matrix.
+ shuffle_input : bool (default: False)
+ Set to `True` to resolve degenerate gradients randomly. For
+ non-degenerate gradients this option has no effect.
+ maxiter : int, positive (default: 30)
+ Integer specifying the max number of Frank-Wolfe iterations performed.
+ tol : float (default: 0.03)
+ Tolerance for termination. Frank-Wolfe iteration terminates when
+ :math:`\frac{||P_{i}-P_{i+1}||_F}{\sqrt{m'}} \leq tol`,
+ where :math:`i` is the iteration number.
+
+ Returns
+ -------
+ res : OptimizeResult
+ `OptimizeResult` containing the following fields.
+
+ col_ind : 1-D array
+ Column indices corresponding to the best permutation found of the
+ nodes of `B`.
+ fun : float
+ The objective value of the solution.
+ nit : int
+ The number of Frank-Wolfe iterations performed.
+
+ Notes
+ -----
+ The algorithm may be sensitive to the initial permutation matrix (or
+ search "position") due to the possibility of several local minima
+ within the feasible region. A barycenter initialization is more likely to
+ result in a better solution than a single random initialization. However,
+ calling ``quadratic_assignment`` several times with different random
+ initializations may result in a better optimum at the cost of longer
+ total execution time.
+
+ Examples
+ --------
+ As mentioned above, a barycenter initialization often results in a better
+ solution than a single random initialization.
+
+ >>> from scipy.optimize import quadratic_assignment
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+ >>> n = 15
+ >>> A = rng.random((n, n))
+ >>> B = rng.random((n, n))
+ >>> options = {"rng": rng}
+ >>> res = quadratic_assignment(A, B, options=options) # FAQ is default method
+ >>> print(res.fun)
+ 47.797048706380636 # may vary
+
+ >>> options = {"rng": rng, "P0": "randomized"} # use randomized initialization
+ >>> res = quadratic_assignment(A, B, options=options)
+ >>> print(res.fun)
+ 47.37287069769966 # may vary
+
+ However, consider running from several randomized initializations and
+ keeping the best result.
+
+ >>> res = min([quadratic_assignment(A, B, options=options)
+ ... for i in range(30)], key=lambda x: x.fun)
+ >>> print(res.fun)
+ 46.55974835248574 # may vary
+
+ The '2-opt' method can be used to attempt to refine the results.
+
+ >>> options = {"partial_guess": np.array([np.arange(n), res.col_ind]).T, "rng": rng}
+ >>> res = quadratic_assignment(A, B, method="2opt", options=options)
+ >>> print(res.fun)
+ 46.55974835248574 # may vary
+
+ References
+ ----------
+ .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik,
+ S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and
+ C.E. Priebe, "Fast approximate quadratic programming for graph
+ matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015,
+ :doi:`10.1371/journal.pone.0121002`
+
+ .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski,
+ C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019):
+ 203-215, :doi:`10.1016/j.patcog.2018.09.014`
+
+ .. [3] "Doubly stochastic Matrix," Wikipedia.
+ https://en.wikipedia.org/wiki/Doubly_stochastic_matrix
+
+ """
+
+ _check_unknown_options(unknown_options)
+
+ maxiter = operator.index(maxiter)
+
+ # ValueError check
+ A, B, partial_match = _common_input_validation(A, B, partial_match)
+
+ msg = None
+ if isinstance(P0, str) and P0 not in {'barycenter', 'randomized'}:
+ msg = "Invalid 'P0' parameter string"
+ elif maxiter <= 0:
+ msg = "'maxiter' must be a positive integer"
+ elif tol <= 0:
+ msg = "'tol' must be a positive float"
+ if msg is not None:
+ raise ValueError(msg)
+
+ rng = np.random.default_rng(rng)
+ n = len(A) # number of vertices in graphs
+ n_seeds = len(partial_match) # number of seeds
+ n_unseed = n - n_seeds
+
+ # [1] Algorithm 1 Line 1 - choose initialization
+ if not isinstance(P0, str):
+ P0 = np.atleast_2d(P0)
+ if P0.shape != (n_unseed, n_unseed):
+ msg = "`P0` matrix must have shape m' x m', where m'=n-m"
+ elif ((P0 < 0).any() or not np.allclose(np.sum(P0, axis=0), 1)
+ or not np.allclose(np.sum(P0, axis=1), 1)):
+ msg = "`P0` matrix must be doubly stochastic"
+ if msg is not None:
+ raise ValueError(msg)
+ elif P0 == 'barycenter':
+ P0 = np.ones((n_unseed, n_unseed)) / n_unseed
+ elif P0 == 'randomized':
+ J = np.ones((n_unseed, n_unseed)) / n_unseed
+ # generate a nxn matrix where each entry is a random number [0, 1]
+ # would use rand, but Generators don't have it
+ # would use random, but old mtrand.RandomStates don't have it
+ K = _doubly_stochastic(rng.uniform(size=(n_unseed, n_unseed)))
+ P0 = (J + K) / 2
+
+ # check trivial cases
+ if n == 0 or n_seeds == n:
+ score = _calc_score(A, B, partial_match[:, 1])
+ res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0}
+ return OptimizeResult(res)
+
+ obj_func_scalar = 1
+ if maximize:
+ obj_func_scalar = -1
+
+ nonseed_B = np.setdiff1d(range(n), partial_match[:, 1])
+ if shuffle_input:
+ nonseed_B = rng.permutation(nonseed_B)
+
+ nonseed_A = np.setdiff1d(range(n), partial_match[:, 0])
+ perm_A = np.concatenate([partial_match[:, 0], nonseed_A])
+ perm_B = np.concatenate([partial_match[:, 1], nonseed_B])
+
+ # definitions according to Seeded Graph Matching [2].
+ A11, A12, A21, A22 = _split_matrix(A[perm_A][:, perm_A], n_seeds)
+ B11, B12, B21, B22 = _split_matrix(B[perm_B][:, perm_B], n_seeds)
+ const_sum = A21 @ B21.T + A12.T @ B12
+
+ P = P0
+ # [1] Algorithm 1 Line 2 - loop while stopping criteria not met
+ for n_iter in range(1, maxiter+1):
+ # [1] Algorithm 1 Line 3 - compute the gradient of f(P) = -tr(APB^tP^t)
+ grad_fp = (const_sum + A22 @ P @ B22.T + A22.T @ P @ B22)
+ # [1] Algorithm 1 Line 4 - get direction Q by solving Eq. 8
+ _, cols = linear_sum_assignment(grad_fp, maximize=maximize)
+ Q = np.eye(n_unseed)[cols]
+
+ # [1] Algorithm 1 Line 5 - compute the step size
+ # Noting that e.g. trace(Ax) = trace(A)*x, expand and re-collect
+ # terms as ax**2 + bx + c. c does not affect location of minimum
+ # and can be ignored. Also, note that trace(A@B) = (A.T*B).sum();
+ # apply where possible for efficiency.
+ R = P - Q
+ b21 = ((R.T @ A21) * B21).sum()
+ b12 = ((R.T @ A12.T) * B12.T).sum()
+ AR22 = A22.T @ R
+ BR22 = B22 @ R.T
+ b22a = (AR22 * B22.T[cols]).sum()
+ b22b = (A22 * BR22[cols]).sum()
+ a = (AR22.T * BR22).sum()
+ b = b21 + b12 + b22a + b22b
+ # critical point of ax^2 + bx + c is at x = -d/(2*e)
+ # if a * obj_func_scalar > 0, it is a minimum
+ # if minimum is not in [0, 1], only endpoints need to be considered
+ if a*obj_func_scalar > 0 and 0 <= -b/(2*a) <= 1:
+ alpha = -b/(2*a)
+ else:
+ alpha = np.argmin([0, (b + a)*obj_func_scalar])
+
+ # [1] Algorithm 1 Line 6 - Update P
+ P_i1 = alpha * P + (1 - alpha) * Q
+ if np.linalg.norm(P - P_i1) / np.sqrt(n_unseed) < tol:
+ P = P_i1
+ break
+ P = P_i1
+ # [1] Algorithm 1 Line 7 - end main loop
+
+ # [1] Algorithm 1 Line 8 - project onto the set of permutation matrices
+ _, col = linear_sum_assignment(P, maximize=True)
+ perm = np.concatenate((np.arange(n_seeds), col + n_seeds))
+
+ unshuffled_perm = np.zeros(n, dtype=int)
+ unshuffled_perm[perm_A] = perm_B[perm]
+
+ score = _calc_score(A, B, unshuffled_perm)
+ res = {"col_ind": unshuffled_perm, "fun": score, "nit": n_iter}
+ return OptimizeResult(res)
+
+
+def _split_matrix(X, n):
+ # definitions according to Seeded Graph Matching [2].
+ upper, lower = X[:n], X[n:]
+ return upper[:, :n], upper[:, n:], lower[:, :n], lower[:, n:]
+
+
+def _doubly_stochastic(P, tol=1e-3):
+ # Adapted from @btaba implementation
+ # https://github.com/btaba/sinkhorn_knopp
+ # of Sinkhorn-Knopp algorithm
+ # https://projecteuclid.org/euclid.pjm/1102992505
+
+ max_iter = 1000
+ c = 1 / P.sum(axis=0)
+ r = 1 / (P @ c)
+ P_eps = P
+
+ for it in range(max_iter):
+ if ((np.abs(P_eps.sum(axis=1) - 1) < tol).all() and
+ (np.abs(P_eps.sum(axis=0) - 1) < tol).all()):
+ # All column/row sums ~= 1 within threshold
+ break
+
+ c = 1 / (r @ P)
+ r = 1 / (P @ c)
+ P_eps = r[:, None] * P * c
+
+ return P_eps
+
+
+def _quadratic_assignment_2opt(A, B, maximize=False, rng=None,
+ partial_match=None,
+ partial_guess=None,
+ **unknown_options):
+ r"""Solve the quadratic assignment problem (approximately).
+
+ This function solves the Quadratic Assignment Problem (QAP) and the
+ Graph Matching Problem (GMP) using the 2-opt algorithm [1]_.
+
+ Quadratic assignment solves problems of the following form:
+
+ .. math::
+
+ \min_P & \ {\ \text{trace}(A^T P B P^T)}\\
+ \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\
+
+ where :math:`\mathcal{P}` is the set of all permutation matrices,
+ and :math:`A` and :math:`B` are square matrices.
+
+ Graph matching tries to *maximize* the same objective function.
+ This algorithm can be thought of as finding the alignment of the
+ nodes of two graphs that minimizes the number of induced edge
+ disagreements, or, in the case of weighted graphs, the sum of squared
+ edge weight differences.
+
+ Note that the quadratic assignment problem is NP-hard. The results given
+ here are approximations and are not guaranteed to be optimal.
+
+ Parameters
+ ----------
+ A : 2-D array, square
+ The square matrix :math:`A` in the objective function above.
+ B : 2-D array, square
+ The square matrix :math:`B` in the objective function above.
+ method : str in {'faq', '2opt'} (default: 'faq')
+ The algorithm used to solve the problem. This is the method-specific
+ documentation for '2opt'.
+ :ref:`'faq' ` is also available.
+
+ Options
+ -------
+ maximize : bool (default: False)
+ Maximizes the objective function if ``True``.
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Pseudorandom number generator state. See `quadratic_assignment` for details.
+ partial_match : 2-D array of integers, optional (default: None)
+ Fixes part of the matching. Also known as a "seed" [2]_.
+
+ Each row of `partial_match` specifies a pair of matched nodes: node
+ ``partial_match[i, 0]`` of `A` is matched to node
+ ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``,
+ where ``m`` is not greater than the number of nodes, :math:`n`.
+
+ .. note::
+ `partial_match` must be sorted by the first column.
+
+ partial_guess : 2-D array of integers, optional (default: None)
+ A guess for the matching between the two matrices. Unlike
+ `partial_match`, `partial_guess` does not fix the indices; they are
+ still free to be optimized.
+
+ Each row of `partial_guess` specifies a pair of matched nodes: node
+ ``partial_guess[i, 0]`` of `A` is matched to node
+ ``partial_guess[i, 1]`` of `B`. The array has shape ``(m, 2)``,
+ where ``m`` is not greater than the number of nodes, :math:`n`.
+
+ .. note::
+ `partial_guess` must be sorted by the first column.
+
+ Returns
+ -------
+ res : OptimizeResult
+ `OptimizeResult` containing the following fields.
+
+ col_ind : 1-D array
+ Column indices corresponding to the best permutation found of the
+ nodes of `B`.
+ fun : float
+ The objective value of the solution.
+ nit : int
+ The number of iterations performed during optimization.
+
+ Notes
+ -----
+ This is a greedy algorithm that works similarly to bubble sort: beginning
+ with an initial permutation, it iteratively swaps pairs of indices to
+ improve the objective function until no such improvements are possible.
+
+ References
+ ----------
+ .. [1] "2-opt," Wikipedia.
+ https://en.wikipedia.org/wiki/2-opt
+
+ .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski,
+ C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019):
+ 203-215, :doi:`10.1016/j.patcog.2018.09.014`.
+
+ """
+ _check_unknown_options(unknown_options)
+ rng = np.random.default_rng(rng)
+ A, B, partial_match = _common_input_validation(A, B, partial_match)
+
+ N = len(A)
+ # check trivial cases
+ if N == 0 or partial_match.shape[0] == N:
+ score = _calc_score(A, B, partial_match[:, 1])
+ res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0}
+ return OptimizeResult(res)
+
+ if partial_guess is None:
+ partial_guess = np.array([[], []]).T
+ partial_guess = np.atleast_2d(partial_guess).astype(int)
+
+ msg = None
+ if partial_guess.shape[0] > A.shape[0]:
+ msg = ("`partial_guess` can have only as "
+ "many entries as there are nodes")
+ elif partial_guess.shape[1] != 2:
+ msg = "`partial_guess` must have two columns"
+ elif partial_guess.ndim != 2:
+ msg = "`partial_guess` must have exactly two dimensions"
+ elif (partial_guess < 0).any():
+ msg = "`partial_guess` must contain only positive indices"
+ elif (partial_guess >= len(A)).any():
+ msg = "`partial_guess` entries must be less than number of nodes"
+ elif (not len(set(partial_guess[:, 0])) == len(partial_guess[:, 0]) or
+ not len(set(partial_guess[:, 1])) == len(partial_guess[:, 1])):
+ msg = "`partial_guess` column entries must be unique"
+ if msg is not None:
+ raise ValueError(msg)
+
+ fixed_rows = None
+ if partial_match.size or partial_guess.size:
+ # use partial_match and partial_guess for initial permutation,
+ # but randomly permute the rest.
+ guess_rows = np.zeros(N, dtype=bool)
+ guess_cols = np.zeros(N, dtype=bool)
+ fixed_rows = np.zeros(N, dtype=bool)
+ fixed_cols = np.zeros(N, dtype=bool)
+ perm = np.zeros(N, dtype=int)
+
+ rg, cg = partial_guess.T
+ guess_rows[rg] = True
+ guess_cols[cg] = True
+ perm[guess_rows] = cg
+
+ # match overrides guess
+ rf, cf = partial_match.T
+ fixed_rows[rf] = True
+ fixed_cols[cf] = True
+ perm[fixed_rows] = cf
+
+ random_rows = ~fixed_rows & ~guess_rows
+ random_cols = ~fixed_cols & ~guess_cols
+ perm[random_rows] = rng.permutation(np.arange(N)[random_cols])
+ else:
+ perm = rng.permutation(np.arange(N))
+
+ best_score = _calc_score(A, B, perm)
+
+ i_free = np.arange(N)
+ if fixed_rows is not None:
+ i_free = i_free[~fixed_rows]
+
+ better = operator.gt if maximize else operator.lt
+ n_iter = 0
+ done = False
+ while not done:
+ # equivalent to nested for loops i in range(N), j in range(i, N)
+ for i, j in itertools.combinations_with_replacement(i_free, 2):
+ n_iter += 1
+ perm[i], perm[j] = perm[j], perm[i]
+ score = _calc_score(A, B, perm)
+ if better(score, best_score):
+ best_score = score
+ break
+ # faster to swap back than to create a new list every time
+ perm[i], perm[j] = perm[j], perm[i]
+ else: # no swaps made
+ done = True
+
+ res = {"col_ind": perm, "fun": best_score, "nit": n_iter}
+ return OptimizeResult(res)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_remove_redundancy.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf2d3e400d3d09b9cc51cdcc76c5573f19f21859
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_remove_redundancy.py
@@ -0,0 +1,522 @@
+"""
+Routines for removing redundant (linearly dependent) equations from linear
+programming equality constraints.
+"""
+# Author: Matt Haberland
+
+import numpy as np
+from scipy.linalg import svd
+from scipy.linalg.interpolative import interp_decomp
+import scipy
+from scipy.linalg.blas import dtrsm
+
+
+def _row_count(A):
+ """
+ Counts the number of nonzeros in each row of input array A.
+ Nonzeros are defined as any element with absolute value greater than
+ tol = 1e-13. This value should probably be an input to the function.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing a matrix
+
+ Returns
+ -------
+ rowcount : 1-D array
+ Number of nonzeros in each row of A
+
+ """
+ tol = 1e-13
+ return np.array((abs(A) > tol).sum(axis=1)).flatten()
+
+
+def _get_densest(A, eligibleRows):
+ """
+ Returns the index of the densest row of A. Ignores rows that are not
+ eligible for consideration.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing a matrix
+ eligibleRows : 1-D logical array
+ Values indicate whether the corresponding row of A is eligible
+ to be considered
+
+ Returns
+ -------
+ i_densest : int
+ Index of the densest row in A eligible for consideration
+
+ """
+ rowCounts = _row_count(A)
+ return np.argmax(rowCounts * eligibleRows)
+
+
+def _remove_zero_rows(A, b):
+ """
+ Eliminates trivial equations from system of equations defined by Ax = b
+ and identifies trivial infeasibilities
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the removal operation
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ """
+ status = 0
+ message = ""
+ i_zero = _row_count(A) == 0
+ A = A[np.logical_not(i_zero), :]
+ if not np.allclose(b[i_zero], 0):
+ status = 2
+ message = "There is a zero row in A_eq with a nonzero corresponding " \
+ "entry in b_eq. The problem is infeasible."
+ b = b[np.logical_not(i_zero)]
+ return A, b, status, message
+
+
+def bg_update_dense(plu, perm_r, v, j):
+ LU, p = plu
+
+ vperm = v[perm_r]
+ u = dtrsm(1, LU, vperm, lower=1, diag=1)
+ LU[:j+1, j] = u[:j+1]
+ l = u[j+1:]
+ piv = LU[j, j]
+ LU[j+1:, j] += (l/piv)
+ return LU, p
+
+
+def _remove_redundancy_pivot_dense(A, rhs, true_rank=None):
+ """
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D array
+ A matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [2] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+
+ """
+ tolapiv = 1e-8
+ tolprimal = 1e-8
+ status = 0
+ message = ""
+ inconsistent = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+ A, rhs, status, message = _remove_zero_rows(A, rhs)
+
+ if status != 0:
+ return A, rhs, status, message
+
+ m, n = A.shape
+
+ v = list(range(m)) # Artificial column indices.
+ b = list(v) # Basis column indices.
+ # This is better as a list than a set because column order of basis matrix
+ # needs to be consistent.
+ d = [] # Indices of dependent rows
+ perm_r = None
+
+ A_orig = A
+ A = np.zeros((m, m + n), order='F')
+ np.fill_diagonal(A, 1)
+ A[:, m:] = A_orig
+ e = np.zeros(m)
+
+ js_candidates = np.arange(m, m+n, dtype=int) # candidate columns for basis
+ # manual masking was faster than masked array
+ js_mask = np.ones(js_candidates.shape, dtype=bool)
+
+ # Implements basic algorithm from [2]
+ # Uses some of the suggested improvements (removing zero rows and
+ # Bartels-Golub update idea).
+ # Removing column singletons would be easy, but it is not as important
+ # because the procedure is performed only on the equality constraint
+ # matrix from the original problem - not on the canonical form matrix,
+ # which would have many more column singletons due to slack variables
+ # from the inequality constraints.
+ # The thoughts on "crashing" the initial basis are only really useful if
+ # the matrix is sparse.
+
+ lu = np.eye(m, order='F'), np.arange(m) # initial LU is trivial
+ perm_r = lu[1]
+ for i in v:
+
+ e[i] = 1
+ if i > 0:
+ e[i-1] = 0
+
+ try: # fails for i==0 and any time it gets ill-conditioned
+ j = b[i-1]
+ lu = bg_update_dense(lu, perm_r, A[:, j], i-1)
+ except Exception:
+ lu = scipy.linalg.lu_factor(A[:, b])
+ LU, p = lu
+ perm_r = list(range(m))
+ for i1, i2 in enumerate(p):
+ perm_r[i1], perm_r[i2] = perm_r[i2], perm_r[i1]
+
+ pi = scipy.linalg.lu_solve(lu, e, trans=1)
+
+ js = js_candidates[js_mask]
+ batch = 50
+
+ # This is a tiny bit faster than looping over columns individually,
+ # like for j in js: if abs(A[:,j].transpose().dot(pi)) > tolapiv:
+ for j_index in range(0, len(js), batch):
+ j_indices = js[j_index: min(j_index+batch, len(js))]
+
+ c = abs(A[:, j_indices].transpose().dot(pi))
+ if (c > tolapiv).any():
+ j = js[j_index + np.argmax(c)] # very independent column
+ b[i] = j
+ js_mask[j-m] = False
+ break
+ else:
+ bibar = pi.T.dot(rhs.reshape(-1, 1))
+ bnorm = np.linalg.norm(rhs)
+ if abs(bibar)/(1+bnorm) > tolprimal: # inconsistent
+ status = 2
+ message = inconsistent
+ return A_orig, rhs, status, message
+ else: # dependent
+ d.append(i)
+ if true_rank is not None and len(d) == m - true_rank:
+ break # found all redundancies
+
+ keep = set(range(m))
+ keep = list(keep - set(d))
+ return A_orig[keep, :], rhs[keep], status, message
+
+
+def _remove_redundancy_pivot_sparse(A, rhs):
+ """
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D sparse array
+ An matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D sparse array
+ A matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [2] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+
+ """
+
+ tolapiv = 1e-8
+ tolprimal = 1e-8
+ status = 0
+ message = ""
+ inconsistent = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+ A, rhs, status, message = _remove_zero_rows(A, rhs)
+
+ if status != 0:
+ return A, rhs, status, message
+
+ m, n = A.shape
+
+ v = list(range(m)) # Artificial column indices.
+ b = list(v) # Basis column indices.
+ # This is better as a list than a set because column order of basis matrix
+ # needs to be consistent.
+ k = set(range(m, m+n)) # Structural column indices.
+ d = [] # Indices of dependent rows
+
+ A_orig = A
+ A = scipy.sparse.hstack((scipy.sparse.eye_array(m), A)).tocsc()
+ e = np.zeros(m)
+
+ # Implements basic algorithm from [2]
+ # Uses only one of the suggested improvements (removing zero rows).
+ # Removing column singletons would be easy, but it is not as important
+ # because the procedure is performed only on the equality constraint
+ # matrix from the original problem - not on the canonical form matrix,
+ # which would have many more column singletons due to slack variables
+ # from the inequality constraints.
+ # The thoughts on "crashing" the initial basis sound useful, but the
+ # description of the procedure seems to assume a lot of familiarity with
+ # the subject; it is not very explicit. I already went through enough
+ # trouble getting the basic algorithm working, so I was not interested in
+ # trying to decipher this, too. (Overall, the paper is fraught with
+ # mistakes and ambiguities - which is strange, because the rest of
+ # Andersen's papers are quite good.)
+ # I tried and tried and tried to improve performance using the
+ # Bartels-Golub update. It works, but it's only practical if the LU
+ # factorization can be specialized as described, and that is not possible
+ # until the SciPy SuperLU interface permits control over column
+ # permutation - see issue #7700.
+
+ for i in v:
+ B = A[:, b]
+
+ e[i] = 1
+ if i > 0:
+ e[i-1] = 0
+
+ pi = scipy.sparse.linalg.spsolve(B.transpose(), e).reshape(-1, 1)
+
+ js = list(k-set(b)) # not efficient, but this is not the time sink...
+
+ # Due to overhead, it tends to be faster (for problems tested) to
+ # compute the full matrix-vector product rather than individual
+ # vector-vector products (with the chance of terminating as soon
+ # as any are nonzero). For very large matrices, it might be worth
+ # it to compute, say, 100 or 1000 at a time and stop when a nonzero
+ # is found.
+
+ c = (np.abs(A[:, js].transpose().dot(pi)) > tolapiv).nonzero()[0]
+ if len(c) > 0: # independent
+ j = js[c[0]]
+ # in a previous commit, the previous line was changed to choose
+ # index j corresponding with the maximum dot product.
+ # While this avoided issues with almost
+ # singular matrices, it slowed the routine in most NETLIB tests.
+ # I think this is because these columns were denser than the
+ # first column with nonzero dot product (c[0]).
+ # It would be nice to have a heuristic that balances sparsity with
+ # high dot product, but I don't think it's worth the time to
+ # develop one right now. Bartels-Golub update is a much higher
+ # priority.
+ b[i] = j # replace artificial column
+ else:
+ bibar = pi.T.dot(rhs.reshape(-1, 1))
+ bnorm = np.linalg.norm(rhs)
+ if abs(bibar)/(1 + bnorm) > tolprimal:
+ status = 2
+ message = inconsistent
+ return A_orig, rhs, status, message
+ else: # dependent
+ d.append(i)
+
+ keep = set(range(m))
+ keep = list(keep - set(d))
+ return A_orig[keep, :], rhs[keep], status, message
+
+
+def _remove_redundancy_svd(A, b):
+ """
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [2] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+
+ """
+
+ A, b, status, message = _remove_zero_rows(A, b)
+
+ if status != 0:
+ return A, b, status, message
+
+ U, s, Vh = svd(A)
+ eps = np.finfo(float).eps
+ tol = s.max() * max(A.shape) * eps
+
+ m, n = A.shape
+ s_min = s[-1] if m <= n else 0
+
+ # this algorithm is faster than that of [2] when the nullspace is small
+ # but it could probably be improvement by randomized algorithms and with
+ # a sparse implementation.
+ # it relies on repeated singular value decomposition to find linearly
+ # dependent rows (as identified by columns of U that correspond with zero
+ # singular values). Unfortunately, only one row can be removed per
+ # decomposition (I tried otherwise; doing so can cause problems.)
+ # It would be nice if we could do truncated SVD like sp.sparse.linalg.svds
+ # but that function is unreliable at finding singular values near zero.
+ # Finding max eigenvalue L of A A^T, then largest eigenvalue (and
+ # associated eigenvector) of -A A^T + L I (I is identity) via power
+ # iteration would also work in theory, but is only efficient if the
+ # smallest nonzero eigenvalue of A A^T is close to the largest nonzero
+ # eigenvalue.
+
+ while abs(s_min) < tol:
+ v = U[:, -1] # TODO: return these so user can eliminate from problem?
+ # rows need to be represented in significant amount
+ eligibleRows = np.abs(v) > tol * 10e6
+ if not np.any(eligibleRows) or np.any(np.abs(v.dot(A)) > tol):
+ status = 4
+ message = ("Due to numerical issues, redundant equality "
+ "constraints could not be removed automatically. "
+ "Try providing your constraint matrices as sparse "
+ "matrices to activate sparse presolve, try turning "
+ "off redundancy removal, or try turning off presolve "
+ "altogether.")
+ break
+ if np.any(np.abs(v.dot(b)) > tol * 100): # factor of 100 to fix 10038 and 10349
+ status = 2
+ message = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+ break
+
+ i_remove = _get_densest(A, eligibleRows)
+ A = np.delete(A, i_remove, axis=0)
+ b = np.delete(b, i_remove)
+ U, s, Vh = svd(A)
+ m, n = A.shape
+ s_min = s[-1] if m <= n else 0
+
+ return A, b, status, message
+
+
+def _remove_redundancy_id(A, rhs, rank=None, randomized=True):
+ """Eliminates redundant equations from a system of equations.
+
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ rank : int, optional
+ The rank of A
+ randomized: bool, optional
+ True for randomized interpolative decomposition
+
+ Returns
+ -------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ """
+
+ status = 0
+ message = ""
+ inconsistent = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+
+ A, rhs, status, message = _remove_zero_rows(A, rhs)
+
+ if status != 0:
+ return A, rhs, status, message
+
+ m, n = A.shape
+
+ k = rank
+ if rank is None:
+ k = np.linalg.matrix_rank(A)
+
+ idx, proj = interp_decomp(A.T, k, rand=randomized)
+
+ # first k entries in idx are indices of the independent rows
+ # remaining entries are the indices of the m-k dependent rows
+ # proj provides a linear combinations of rows of A2 that form the
+ # remaining m-k (dependent) rows. The same linear combination of entries
+ # in rhs2 must give the remaining m-k entries. If not, the system is
+ # inconsistent, and the problem is infeasible.
+ if not np.allclose(rhs[idx[:k]] @ proj, rhs[idx[k:]]):
+ status = 2
+ message = inconsistent
+
+ # sort indices because the other redundancy removal routines leave rows
+ # in original order and tests were written with that in mind
+ idx = sorted(idx[:k])
+ A2 = A[idx, :]
+ rhs2 = rhs[idx]
+ return A2, rhs2, status, message
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_root.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_root.py
new file mode 100644
index 0000000000000000000000000000000000000000..73b0d795d73b679f57ca5b85cbff8effcac72c11
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_root.py
@@ -0,0 +1,733 @@
+"""
+Unified interfaces to root finding algorithms.
+
+Functions
+---------
+- root : find a root of a vector function.
+"""
+__all__ = ['root']
+
+import numpy as np
+
+from warnings import warn
+
+from ._optimize import MemoizeJac, OptimizeResult, _check_unknown_options
+from ._minpack_py import _root_hybr, leastsq
+from ._spectral import _root_df_sane
+from . import _nonlin as nonlin
+
+
+ROOT_METHODS = ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson',
+ 'linearmixing', 'diagbroyden', 'excitingmixing', 'krylov',
+ 'df-sane']
+
+
+def root(fun, x0, args=(), method='hybr', jac=None, tol=None, callback=None,
+ options=None):
+ r"""
+ Find a root of a vector function.
+
+ Parameters
+ ----------
+ fun : callable
+ A vector function to find a root of.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+ x0 : ndarray
+ Initial guess.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its Jacobian.
+ method : str, optional
+ Type of solver. Should be one of
+
+ - 'hybr' :ref:`(see here) `
+ - 'lm' :ref:`(see here) `
+ - 'broyden1' :ref:`(see here) `
+ - 'broyden2' :ref:`(see here) `
+ - 'anderson' :ref:`(see here) `
+ - 'linearmixing' :ref:`(see here) `
+ - 'diagbroyden' :ref:`(see here) `
+ - 'excitingmixing' :ref:`(see here) `
+ - 'krylov' :ref:`(see here) `
+ - 'df-sane' :ref:`(see here) `
+
+ jac : bool or callable, optional
+ If `jac` is a Boolean and is True, `fun` is assumed to return the
+ value of Jacobian along with the objective function. If False, the
+ Jacobian will be estimated numerically.
+ `jac` can also be a callable returning the Jacobian of `fun`. In
+ this case, it must accept the same arguments as `fun`.
+ tol : float, optional
+ Tolerance for termination. For detailed control, use solver-specific
+ options.
+ callback : function, optional
+ Optional callback function. It is called on every iteration as
+ ``callback(x, f)`` where `x` is the current solution and `f`
+ the corresponding residual. For all methods but 'hybr' and 'lm'.
+ options : dict, optional
+ A dictionary of solver options. E.g., `xtol` or `maxiter`, see
+ :obj:`show_options()` for details.
+
+ Returns
+ -------
+ sol : OptimizeResult
+ The solution represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the algorithm exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ See Also
+ --------
+ show_options : Additional options accepted by the solvers
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter. The default method is *hybr*.
+
+ Method *hybr* uses a modification of the Powell hybrid method as
+ implemented in MINPACK [1]_.
+
+ Method *lm* solves the system of nonlinear equations in a least squares
+ sense using a modification of the Levenberg-Marquardt algorithm as
+ implemented in MINPACK [1]_.
+
+ Method *df-sane* is a derivative-free spectral method. [3]_
+
+ Methods *broyden1*, *broyden2*, *anderson*, *linearmixing*,
+ *diagbroyden*, *excitingmixing*, *krylov* are inexact Newton methods,
+ with backtracking or full line searches [2]_. Each method corresponds
+ to a particular Jacobian approximations.
+
+ - Method *broyden1* uses Broyden's first Jacobian approximation, it is
+ known as Broyden's good method.
+ - Method *broyden2* uses Broyden's second Jacobian approximation, it
+ is known as Broyden's bad method.
+ - Method *anderson* uses (extended) Anderson mixing.
+ - Method *Krylov* uses Krylov approximation for inverse Jacobian. It
+ is suitable for large-scale problem.
+ - Method *diagbroyden* uses diagonal Broyden Jacobian approximation.
+ - Method *linearmixing* uses a scalar Jacobian approximation.
+ - Method *excitingmixing* uses a tuned diagonal Jacobian
+ approximation.
+
+ .. warning::
+
+ The algorithms implemented for methods *diagbroyden*,
+ *linearmixing* and *excitingmixing* may be useful for specific
+ problems, but whether they will work may depend strongly on the
+ problem.
+
+ .. versionadded:: 0.11.0
+
+ References
+ ----------
+ .. [1] More, Jorge J., Burton S. Garbow, and Kenneth E. Hillstrom.
+ 1980. User Guide for MINPACK-1.
+ .. [2] C. T. Kelley. 1995. Iterative Methods for Linear and Nonlinear
+ Equations. Society for Industrial and Applied Mathematics.
+ :doi:`10.1137/1.9781611970944`
+ .. [3] W. La Cruz, J.M. Martinez, M. Raydan.
+ Math. Comp. 75, 1429 (2006).
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations and its
+ jacobian.
+
+ >>> import numpy as np
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ >>> def jac(x):
+ ... return np.array([[1 + 1.5 * (x[0] - x[1])**2,
+ ... -1.5 * (x[0] - x[1])**2],
+ ... [-1.5 * (x[1] - x[0])**2,
+ ... 1 + 1.5 * (x[1] - x[0])**2]])
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.root(fun, [0, 0], jac=jac, method='hybr')
+ >>> sol.x
+ array([ 0.8411639, 0.1588361])
+
+ **Large problem**
+
+ Suppose that we needed to solve the following integrodifferential
+ equation on the square :math:`[0,1]\times[0,1]`:
+
+ .. math::
+
+ \nabla^2 P = 10 \left(\int_0^1\int_0^1\cosh(P)\,dx\,dy\right)^2
+
+ with :math:`P(x,1) = 1` and :math:`P=0` elsewhere on the boundary of
+ the square.
+
+ The solution can be found using the ``method='krylov'`` solver:
+
+ >>> from scipy import optimize
+ >>> # parameters
+ >>> nx, ny = 75, 75
+ >>> hx, hy = 1./(nx-1), 1./(ny-1)
+
+ >>> P_left, P_right = 0, 0
+ >>> P_top, P_bottom = 1, 0
+
+ >>> def residual(P):
+ ... d2x = np.zeros_like(P)
+ ... d2y = np.zeros_like(P)
+ ...
+ ... d2x[1:-1] = (P[2:] - 2*P[1:-1] + P[:-2]) / hx/hx
+ ... d2x[0] = (P[1] - 2*P[0] + P_left)/hx/hx
+ ... d2x[-1] = (P_right - 2*P[-1] + P[-2])/hx/hx
+ ...
+ ... d2y[:,1:-1] = (P[:,2:] - 2*P[:,1:-1] + P[:,:-2])/hy/hy
+ ... d2y[:,0] = (P[:,1] - 2*P[:,0] + P_bottom)/hy/hy
+ ... d2y[:,-1] = (P_top - 2*P[:,-1] + P[:,-2])/hy/hy
+ ...
+ ... return d2x + d2y - 10*np.cosh(P).mean()**2
+
+ >>> guess = np.zeros((nx, ny), float)
+ >>> sol = optimize.root(residual, guess, method='krylov')
+ >>> print('Residual: %g' % abs(residual(sol.x)).max())
+ Residual: 5.7972e-06 # may vary
+
+ >>> import matplotlib.pyplot as plt
+ >>> x, y = np.mgrid[0:1:(nx*1j), 0:1:(ny*1j)]
+ >>> plt.pcolormesh(x, y, sol.x, shading='gouraud')
+ >>> plt.colorbar()
+ >>> plt.show()
+
+ """
+ def _wrapped_fun(*fargs):
+ """
+ Wrapped `func` to track the number of times
+ the function has been called.
+ """
+ _wrapped_fun.nfev += 1
+ return fun(*fargs)
+
+ _wrapped_fun.nfev = 0
+
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ meth = method.lower()
+ if options is None:
+ options = {}
+
+ if callback is not None and meth in ('hybr', 'lm'):
+ warn(f'Method {method} does not accept callback.',
+ RuntimeWarning, stacklevel=2)
+
+ # fun also returns the Jacobian
+ if not callable(jac) and meth in ('hybr', 'lm'):
+ if bool(jac):
+ fun = MemoizeJac(fun)
+ jac = fun.derivative
+ else:
+ jac = None
+
+ # set default tolerances
+ if tol is not None:
+ options = dict(options)
+ if meth in ('hybr', 'lm'):
+ options.setdefault('xtol', tol)
+ elif meth in ('df-sane',):
+ options.setdefault('ftol', tol)
+ elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing',
+ 'diagbroyden', 'excitingmixing', 'krylov'):
+ options.setdefault('xtol', tol)
+ options.setdefault('xatol', np.inf)
+ options.setdefault('ftol', np.inf)
+ options.setdefault('fatol', np.inf)
+
+ if meth == 'hybr':
+ sol = _root_hybr(_wrapped_fun, x0, args=args, jac=jac, **options)
+ elif meth == 'lm':
+ sol = _root_leastsq(_wrapped_fun, x0, args=args, jac=jac, **options)
+ elif meth == 'df-sane':
+ _warn_jac_unused(jac, method)
+ sol = _root_df_sane(_wrapped_fun, x0, args=args, callback=callback,
+ **options)
+ elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing',
+ 'diagbroyden', 'excitingmixing', 'krylov'):
+ _warn_jac_unused(jac, method)
+ sol = _root_nonlin_solve(_wrapped_fun, x0, args=args, jac=jac,
+ _method=meth, _callback=callback,
+ **options)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ sol.nfev = _wrapped_fun.nfev
+ return sol
+
+
+def _warn_jac_unused(jac, method):
+ if jac is not None:
+ warn(f'Method {method} does not use the jacobian (jac).',
+ RuntimeWarning, stacklevel=2)
+
+
+def _root_leastsq(fun, x0, args=(), jac=None,
+ col_deriv=0, xtol=1.49012e-08, ftol=1.49012e-08,
+ gtol=0.0, maxiter=0, eps=0.0, factor=100, diag=None,
+ **unknown_options):
+ """
+ Solve for least squares with Levenberg-Marquardt
+
+ Options
+ -------
+ col_deriv : bool
+ non-zero to specify that the Jacobian function computes derivatives
+ down the columns (faster, because there is no transpose operation).
+ ftol : float
+ Relative error desired in the sum of squares.
+ xtol : float
+ Relative error desired in the approximate solution.
+ gtol : float
+ Orthogonality desired between the function vector and the columns
+ of the Jacobian.
+ maxiter : int
+ The maximum number of calls to the function. If zero, then
+ 100*(N+1) is the maximum where N is the number of elements in x0.
+ eps : float
+ A suitable step length for the forward-difference approximation of
+ the Jacobian (for Dfun=None). If `eps` is less than the machine
+ precision, it is assumed that the relative errors in the functions
+ are of the order of the machine precision.
+ factor : float
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
+ diag : sequence
+ N positive entries that serve as a scale factors for the variables.
+ """
+ nfev = 0
+ def _wrapped_fun(*fargs):
+ """
+ Wrapped `func` to track the number of times
+ the function has been called.
+ """
+ nonlocal nfev
+ nfev += 1
+ return fun(*fargs)
+
+ _check_unknown_options(unknown_options)
+ x, cov_x, info, msg, ier = leastsq(_wrapped_fun, x0, args=args,
+ Dfun=jac, full_output=True,
+ col_deriv=col_deriv, xtol=xtol,
+ ftol=ftol, gtol=gtol,
+ maxfev=maxiter, epsfcn=eps,
+ factor=factor, diag=diag)
+ sol = OptimizeResult(x=x, message=msg, status=ier,
+ success=ier in (1, 2, 3, 4), cov_x=cov_x,
+ fun=info.pop('fvec'), method="lm")
+ sol.update(info)
+ sol.nfev = nfev
+ return sol
+
+
+def _root_nonlin_solve(fun, x0, args=(), jac=None,
+ _callback=None, _method=None,
+ nit=None, disp=False, maxiter=None,
+ ftol=None, fatol=None, xtol=None, xatol=None,
+ tol_norm=None, line_search='armijo', jac_options=None,
+ **unknown_options):
+ _check_unknown_options(unknown_options)
+
+ f_tol = fatol
+ f_rtol = ftol
+ x_tol = xatol
+ x_rtol = xtol
+ verbose = disp
+ if jac_options is None:
+ jac_options = dict()
+
+ jacobian = {'broyden1': nonlin.BroydenFirst,
+ 'broyden2': nonlin.BroydenSecond,
+ 'anderson': nonlin.Anderson,
+ 'linearmixing': nonlin.LinearMixing,
+ 'diagbroyden': nonlin.DiagBroyden,
+ 'excitingmixing': nonlin.ExcitingMixing,
+ 'krylov': nonlin.KrylovJacobian
+ }[_method]
+
+ if args:
+ if jac is True:
+ def f(x):
+ return fun(x, *args)[0]
+ else:
+ def f(x):
+ return fun(x, *args)
+ else:
+ f = fun
+
+ x, info = nonlin.nonlin_solve(f, x0, jacobian=jacobian(**jac_options),
+ iter=nit, verbose=verbose,
+ maxiter=maxiter, f_tol=f_tol,
+ f_rtol=f_rtol, x_tol=x_tol,
+ x_rtol=x_rtol, tol_norm=tol_norm,
+ line_search=line_search,
+ callback=_callback, full_output=True,
+ raise_exception=False)
+ sol = OptimizeResult(x=x, method=_method)
+ sol.update(info)
+ return sol
+
+def _root_broyden1_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ reduction_method : str or tuple, optional
+ Method used in ensuring that the rank of the Broyden
+ matrix stays low. Can either be a string giving the
+ name of the method, or a tuple of the form ``(method,
+ param1, param2, ...)`` that gives the name of the
+ method and values for additional parameters.
+
+ Methods available:
+
+ - ``restart``: drop all matrix columns. Has no extra parameters.
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
+ - ``svd``: keep only the most significant SVD components.
+ Takes an extra parameter, ``to_retain``, which determines the
+ number of SVD components to retain when rank reduction is done.
+ Default is ``max_rank - 2``.
+
+ max_rank : int, optional
+ Maximum rank for the Broyden matrix.
+ Default is infinity (i.e., no rank reduction).
+
+ Examples
+ --------
+ >>> def func(x):
+ ... return np.cos(x) + x[::-1] - [1, 2, 3, 4]
+ ...
+ >>> from scipy import optimize
+ >>> res = optimize.root(func, [1, 1, 1, 1], method='broyden1', tol=1e-14)
+ >>> x = res.x
+ >>> x
+ array([4.04674914, 3.91158389, 2.71791677, 1.61756251])
+ >>> np.cos(x) + x[::-1]
+ array([1., 2., 3., 4.])
+
+ """
+ pass
+
+
+def _root_broyden2_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ reduction_method : str or tuple, optional
+ Method used in ensuring that the rank of the Broyden
+ matrix stays low. Can either be a string giving the
+ name of the method, or a tuple of the form ``(method,
+ param1, param2, ...)`` that gives the name of the
+ method and values for additional parameters.
+
+ Methods available:
+
+ - ``restart``: drop all matrix columns. Has no extra parameters.
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
+ - ``svd``: keep only the most significant SVD components.
+ Takes an extra parameter, ``to_retain``, which determines the
+ number of SVD components to retain when rank reduction is done.
+ Default is ``max_rank - 2``.
+
+ max_rank : int, optional
+ Maximum rank for the Broyden matrix.
+ Default is infinity (i.e., no rank reduction).
+ """
+ pass
+
+
+def _root_anderson_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ M : float, optional
+ Number of previous vectors to retain. Defaults to 5.
+ w0 : float, optional
+ Regularization parameter for numerical stability.
+ Compared to unity, good values of the order of 0.01.
+ """
+ pass
+
+def _root_linearmixing_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ initial guess for the jacobian is (-1/alpha).
+ """
+ pass
+
+def _root_diagbroyden_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ initial guess for the jacobian is (-1/alpha).
+ """
+ pass
+
+def _root_excitingmixing_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial Jacobian approximation is (-1/alpha).
+ alphamax : float, optional
+ The entries of the diagonal Jacobian are kept in the range
+ ``[alpha, alphamax]``.
+ """
+ pass
+
+def _root_krylov_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ rdiff : float, optional
+ Relative step size to use in numerical differentiation.
+ method : str or callable, optional
+ Krylov method to use to approximate the Jacobian. Can be a string,
+ or a function implementing the same interface as the iterative
+ solvers in `scipy.sparse.linalg`. If a string, needs to be one of:
+ ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``,
+ ``'tfqmr'``.
+
+ The default is `scipy.sparse.linalg.lgmres`.
+ inner_M : LinearOperator or InverseJacobian
+ Preconditioner for the inner Krylov iteration.
+ Note that you can use also inverse Jacobians as (adaptive)
+ preconditioners. For example,
+
+ >>> jac = BroydenFirst()
+ >>> kjac = KrylovJacobian(inner_M=jac.inverse).
+
+ If the preconditioner has a method named 'update', it will
+ be called as ``update(x, f)`` after each nonlinear step,
+ with ``x`` giving the current point, and ``f`` the current
+ function value.
+ inner_rtol, inner_atol, inner_callback, ...
+ Parameters to pass on to the "inner" Krylov solver.
+
+ For a full list of options, see the documentation for the
+ solver you are using. By default this is `scipy.sparse.linalg.lgmres`.
+ If the solver has been overridden through `method`, see the documentation
+ for that solver instead.
+ To use an option for that solver, prepend ``inner_`` to it.
+ For example, to control the ``rtol`` argument to the solver,
+ set the `inner_rtol` option here.
+
+ outer_k : int, optional
+ Size of the subspace kept across LGMRES nonlinear
+ iterations.
+
+ See `scipy.sparse.linalg.lgmres` for details.
+ """
+ pass
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_root_scalar.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_root_scalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..9858a7a47df5ac9c3c67f247dcb24542e8f05642
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_root_scalar.py
@@ -0,0 +1,537 @@
+"""
+Unified interfaces to root finding algorithms for real or complex
+scalar functions.
+
+Functions
+---------
+- root : find a root of a scalar function.
+"""
+import numpy as np
+
+from . import _zeros_py as optzeros
+from ._numdiff import approx_derivative
+
+__all__ = ['root_scalar']
+
+ROOT_SCALAR_METHODS = ['bisect', 'brentq', 'brenth', 'ridder', 'toms748',
+ 'newton', 'secant', 'halley']
+
+
+class MemoizeDer:
+ """Decorator that caches the value and derivative(s) of function each
+ time it is called.
+
+ This is a simplistic memoizer that calls and caches a single value
+ of ``f(x, *args)``.
+ It assumes that `args` does not change between invocations.
+ It supports the use case of a root-finder where `args` is fixed,
+ `x` changes, and only rarely, if at all, does x assume the same value
+ more than once."""
+ def __init__(self, fun):
+ self.fun = fun
+ self.vals = None
+ self.x = None
+ self.n_calls = 0
+
+ def __call__(self, x, *args):
+ r"""Calculate f or use cached value if available"""
+ # Derivative may be requested before the function itself, always check
+ if self.vals is None or x != self.x:
+ fg = self.fun(x, *args)
+ self.x = x
+ self.n_calls += 1
+ self.vals = fg[:]
+ return self.vals[0]
+
+ def fprime(self, x, *args):
+ r"""Calculate f' or use a cached value if available"""
+ if self.vals is None or x != self.x:
+ self(x, *args)
+ return self.vals[1]
+
+ def fprime2(self, x, *args):
+ r"""Calculate f'' or use a cached value if available"""
+ if self.vals is None or x != self.x:
+ self(x, *args)
+ return self.vals[2]
+
+ def ncalls(self):
+ return self.n_calls
+
+
+def root_scalar(f, args=(), method=None, bracket=None,
+ fprime=None, fprime2=None,
+ x0=None, x1=None,
+ xtol=None, rtol=None, maxiter=None,
+ options=None):
+ """
+ Find a root of a scalar function.
+
+ Parameters
+ ----------
+ f : callable
+ A function to find a root of.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its derivative(s).
+ method : str, optional
+ Type of solver. Should be one of
+
+ - 'bisect' :ref:`(see here) `
+ - 'brentq' :ref:`(see here) `
+ - 'brenth' :ref:`(see here) `
+ - 'ridder' :ref:`(see here) `
+ - 'toms748' :ref:`(see here) `
+ - 'newton' :ref:`(see here) `
+ - 'secant' :ref:`(see here) `
+ - 'halley' :ref:`(see here) `
+
+ bracket : A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ fprime : bool or callable, optional
+ If `fprime` is a boolean and is True, `f` is assumed to return the
+ value of the objective function and of the derivative.
+ `fprime` can also be a callable returning the derivative of `f`. In
+ this case, it must accept the same arguments as `f`.
+ fprime2 : bool or callable, optional
+ If `fprime2` is a boolean and is True, `f` is assumed to return the
+ value of the objective function and of the first and second derivatives.
+ `fprime2` can also be a callable returning the second derivative of `f`.
+ In this case, it must accept the same arguments as `f`.
+ x0 : float, optional
+ Initial guess.
+ x1 : float, optional
+ A second guess.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options : dict, optional
+ A dictionary of solver options. E.g., ``k``, see
+ :obj:`show_options()` for details.
+
+ Returns
+ -------
+ sol : RootResults
+ The solution represented as a ``RootResults`` object.
+ Important attributes are: ``root`` the solution , ``converged`` a
+ boolean flag indicating if the algorithm exited successfully and
+ ``flag`` which describes the cause of the termination. See
+ `RootResults` for a description of other attributes.
+
+ See Also
+ --------
+ show_options : Additional options accepted by the solvers
+ root : Find a root of a vector function.
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter.
+
+ The default is to use the best method available for the situation
+ presented.
+ If a bracket is provided, it may use one of the bracketing methods.
+ If a derivative and an initial value are specified, it may
+ select one of the derivative-based methods.
+ If no method is judged applicable, it will raise an Exception.
+
+ Arguments for each method are as follows (x=required, o=optional).
+
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | method | f | args | bracket | x0 | x1 | fprime | fprime2 | xtol | rtol | maxiter | options |
+ +===============================================+===+======+=========+====+====+========+=========+======+======+=========+=========+
+ | :ref:`bisect ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`brentq ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`brenth ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`ridder ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`toms748 ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`secant ` | x | o | | x | o | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`newton ` | x | o | | x | | o | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`halley ` | x | o | | x | | x | x | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+
+ Examples
+ --------
+
+ Find the root of a simple cubic
+
+ >>> from scipy import optimize
+ >>> def f(x):
+ ... return (x**3 - 1) # only one real root at x = 1
+
+ >>> def fprime(x):
+ ... return 3*x**2
+
+ The `brentq` method takes as input a bracket
+
+ >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq')
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 10, 11)
+
+ The `newton` method takes as input a single point and uses the
+ derivative(s).
+
+ >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton')
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 11, 22)
+
+ The function can provide the value and derivative(s) in a single call.
+
+ >>> def f_p_pp(x):
+ ... return (x**3 - 1), 3*x**2, 6*x
+
+ >>> sol = optimize.root_scalar(
+ ... f_p_pp, x0=0.2, fprime=True, method='newton'
+ ... )
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 11, 11)
+
+ >>> sol = optimize.root_scalar(
+ ... f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley'
+ ... )
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 7, 8)
+
+
+ """ # noqa: E501
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ if options is None:
+ options = {}
+
+ # fun also returns the derivative(s)
+ is_memoized = False
+ if fprime2 is not None and not callable(fprime2):
+ if bool(fprime2):
+ f = MemoizeDer(f)
+ is_memoized = True
+ fprime2 = f.fprime2
+ fprime = f.fprime
+ else:
+ fprime2 = None
+ if fprime is not None and not callable(fprime):
+ if bool(fprime):
+ f = MemoizeDer(f)
+ is_memoized = True
+ fprime = f.fprime
+ else:
+ fprime = None
+
+ # respect solver-specific default tolerances - only pass in if actually set
+ kwargs = {}
+ for k in ['xtol', 'rtol', 'maxiter']:
+ v = locals().get(k)
+ if v is not None:
+ kwargs[k] = v
+
+ # Set any solver-specific options
+ if options:
+ kwargs.update(options)
+ # Always request full_output from the underlying method as _root_scalar
+ # always returns a RootResults object
+ kwargs.update(full_output=True, disp=False)
+
+ # Pick a method if not specified.
+ # Use the "best" method available for the situation.
+ if not method:
+ if bracket is not None:
+ method = 'brentq'
+ elif x0 is not None:
+ if fprime:
+ if fprime2:
+ method = 'halley'
+ else:
+ method = 'newton'
+ elif x1 is not None:
+ method = 'secant'
+ else:
+ method = 'newton'
+ if not method:
+ raise ValueError('Unable to select a solver as neither bracket '
+ 'nor starting point provided.')
+
+ meth = method.lower()
+ map2underlying = {'halley': 'newton', 'secant': 'newton'}
+
+ try:
+ methodc = getattr(optzeros, map2underlying.get(meth, meth))
+ except AttributeError as e:
+ raise ValueError(f'Unknown solver {meth}') from e
+
+ if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']:
+ if not isinstance(bracket, list | tuple | np.ndarray):
+ raise ValueError(f'Bracket needed for {method}')
+
+ a, b = bracket[:2]
+ try:
+ r, sol = methodc(f, a, b, args=args, **kwargs)
+ except ValueError as e:
+ # gh-17622 fixed some bugs in low-level solvers by raising an error
+ # (rather than returning incorrect results) when the callable
+ # returns a NaN. It did so by wrapping the callable rather than
+ # modifying compiled code, so the iteration count is not available.
+ if hasattr(e, "_x"):
+ sol = optzeros.RootResults(root=e._x,
+ iterations=np.nan,
+ function_calls=e._function_calls,
+ flag=str(e), method=method)
+ else:
+ raise
+
+ elif meth in ['secant']:
+ if x0 is None:
+ raise ValueError(f'x0 must not be None for {method}')
+ if 'xtol' in kwargs:
+ kwargs['tol'] = kwargs.pop('xtol')
+ r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None,
+ x1=x1, **kwargs)
+ elif meth in ['newton']:
+ if x0 is None:
+ raise ValueError(f'x0 must not be None for {method}')
+ if not fprime:
+ # approximate fprime with finite differences
+
+ def fprime(x, *args):
+ # `root_scalar` doesn't actually seem to support vectorized
+ # use of `newton`. In that case, `approx_derivative` will
+ # always get scalar input. Nonetheless, it always returns an
+ # array, so we extract the element to produce scalar output.
+ # Similarly, `approx_derivative` always passes array input, so
+ # we extract the element to ensure the user's function gets
+ # scalar input.
+ def f_wrapped(x, *args):
+ return f(x[0], *args)
+ return approx_derivative(f_wrapped, x, method='2-point', args=args)[0]
+
+ if 'xtol' in kwargs:
+ kwargs['tol'] = kwargs.pop('xtol')
+ r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None,
+ **kwargs)
+ elif meth in ['halley']:
+ if x0 is None:
+ raise ValueError(f'x0 must not be None for {method}')
+ if not fprime:
+ raise ValueError(f'fprime must be specified for {method}')
+ if not fprime2:
+ raise ValueError(f'fprime2 must be specified for {method}')
+ if 'xtol' in kwargs:
+ kwargs['tol'] = kwargs.pop('xtol')
+ r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ if is_memoized:
+ # Replace the function_calls count with the memoized count.
+ # Avoids double and triple-counting.
+ n_calls = f.n_calls
+ sol.function_calls = n_calls
+
+ return sol
+
+
+def _root_scalar_brentq_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above
+
+ """
+ pass
+
+
+def _root_scalar_brenth_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+def _root_scalar_toms748_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_secant_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ x0 : float, required
+ Initial guess.
+ x1 : float, optional
+ A second guess. Must be different from `x0`. If not specified,
+ a value near `x0` will be chosen.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_newton_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function and its derivative.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ x0 : float, required
+ Initial guess.
+ fprime : bool or callable, optional
+ If `fprime` is a boolean and is True, `f` is assumed to return the
+ value of derivative along with the objective function.
+ `fprime` can also be a callable returning the derivative of `f`. In
+ this case, it must accept the same arguments as `f`.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_halley_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function and its derivatives.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ x0 : float, required
+ Initial guess.
+ fprime : bool or callable, required
+ If `fprime` is a boolean and is True, `f` is assumed to return the
+ value of derivative along with the objective function.
+ `fprime` can also be a callable returning the derivative of `f`. In
+ this case, it must accept the same arguments as `f`.
+ fprime2 : bool or callable, required
+ If `fprime2` is a boolean and is True, `f` is assumed to return the
+ value of 1st and 2nd derivatives along with the objective function.
+ `fprime2` can also be a callable returning the 2nd derivative of `f`.
+ In this case, it must accept the same arguments as `f`.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_ridder_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_bisect_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ab9069facf77b209f2300d8bd398bedcede4952
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo.py
@@ -0,0 +1,1623 @@
+"""shgo: The simplicial homology global optimisation algorithm."""
+from collections import namedtuple
+import time
+import logging
+import warnings
+import sys
+
+import numpy as np
+
+from scipy import spatial
+from scipy.optimize import OptimizeResult, minimize, Bounds
+from scipy.optimize._optimize import MemoizeJac
+from scipy.optimize._constraints import new_bounds_to_old
+from scipy.optimize._minimize import standardize_constraints
+from scipy._lib._util import _FunctionWrapper
+
+from scipy.optimize._shgo_lib._complex import Complex
+
+__all__ = ['shgo']
+
+
+def shgo(
+ func, bounds, args=(), constraints=None, n=100, iters=1, callback=None,
+ minimizer_kwargs=None, options=None, sampling_method='simplicial', *,
+ workers=1
+):
+ """
+ Finds the global minimum of a function using SHG optimization.
+
+ SHGO stands for "simplicial homology global optimization".
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the form
+ ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+ and ``args`` is a tuple of any additional fixed parameters needed to
+ completely specify the function.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`.
+
+ args : tuple, optional
+ Any additional fixed parameters needed to completely specify the
+ objective function.
+ constraints : {Constraint, dict} or List of {Constraint, dict}, optional
+ Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.
+ See the tutorial [5]_ for further details on specifying constraints.
+
+ .. note::
+
+ Only COBYLA, COBYQA, SLSQP, and trust-constr local minimize methods
+ currently support constraint arguments. If the ``constraints``
+ sequence used in the local optimization problem is not defined in
+ ``minimizer_kwargs`` and a constrained method is used then the
+ global ``constraints`` will be used.
+ (Defining a ``constraints`` sequence in ``minimizer_kwargs``
+ means that ``constraints`` will not be added so if equality
+ constraints and so forth need to be added then the inequality
+ functions in ``constraints`` need to be added to
+ ``minimizer_kwargs`` too).
+ COBYLA only supports inequality constraints.
+
+ .. versionchanged:: 1.11.0
+
+ ``constraints`` accepts `NonlinearConstraint`, `LinearConstraint`.
+
+ n : int, optional
+ Number of sampling points used in the construction of the simplicial
+ complex. For the default ``simplicial`` sampling method 2**dim + 1
+ sampling points are generated instead of the default ``n=100``. For all
+ other specified values `n` sampling points are generated. For
+ ``sobol``, ``halton`` and other arbitrary `sampling_methods` ``n=100`` or
+ another specified number of sampling points are generated.
+ iters : int, optional
+ Number of iterations used in the construction of the simplicial
+ complex. Default is 1.
+ callback : callable, optional
+ Called after each iteration, as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ minimizer_kwargs : dict, optional
+ Extra keyword arguments to be passed to the minimizer
+ ``scipy.optimize.minimize``. Some important options could be:
+
+ method : str
+ The minimization method. If not given, chosen to be one of
+ BFGS, L-BFGS-B, SLSQP, depending on whether or not the
+ problem has constraints or bounds.
+ args : tuple
+ Extra arguments passed to the objective function (``func``) and
+ its derivatives (Jacobian, Hessian).
+ options : dict, optional
+ Note that by default the tolerance is specified as
+ ``{ftol: 1e-12}``
+
+ options : dict, optional
+ A dictionary of solver options. Many of the options specified for the
+ global routine are also passed to the ``scipy.optimize.minimize``
+ routine. The options that are also passed to the local routine are
+ marked with "(L)".
+
+ Stopping criteria, the algorithm will terminate if any of the specified
+ criteria are met. However, the default algorithm does not require any
+ to be specified:
+
+ maxfev : int (L)
+ Maximum number of function evaluations in the feasible domain.
+ (Note only methods that support this option will terminate
+ the routine at precisely exact specified value. Otherwise the
+ criterion will only terminate during a global iteration)
+ f_min : float
+ Specify the minimum objective function value, if it is known.
+ f_tol : float
+ Precision goal for the value of f in the stopping
+ criterion. Note that the global routine will also
+ terminate if a sampling point in the global routine is
+ within this tolerance.
+ maxiter : int
+ Maximum number of iterations to perform.
+ maxev : int
+ Maximum number of sampling evaluations to perform (includes
+ searching in infeasible points).
+ maxtime : float
+ Maximum processing runtime allowed
+ minhgrd : int
+ Minimum homology group rank differential. The homology group of the
+ objective function is calculated (approximately) during every
+ iteration. The rank of this group has a one-to-one correspondence
+ with the number of locally convex subdomains in the objective
+ function (after adequate sampling points each of these subdomains
+ contain a unique global minimum). If the difference in the hgr is 0
+ between iterations for ``maxhgrd`` specified iterations the
+ algorithm will terminate.
+
+ Objective function knowledge:
+
+ symmetry : list or bool
+ Specify if the objective function contains symmetric variables.
+ The search space (and therefore performance) is decreased by up to
+ O(n!) times in the fully symmetric case. If `True` is specified
+ then all variables will be set symmetric to the first variable.
+ Default
+ is set to False.
+
+ E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
+
+ In this equation x_2 and x_3 are symmetric to x_1, while x_5 and
+ x_6 are symmetric to x_4, this can be specified to the solver as::
+
+ symmetry = [0, # Variable 1
+ 0, # symmetric to variable 1
+ 0, # symmetric to variable 1
+ 3, # Variable 4
+ 3, # symmetric to variable 4
+ 3, # symmetric to variable 4
+ ]
+
+ jac : bool or callable, optional
+ Jacobian (gradient) of objective function. Only for CG, BFGS,
+ Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg. If ``jac`` is a
+ boolean and is True, ``fun`` is assumed to return the gradient
+ along with the objective function. If False, the gradient will be
+ estimated numerically. ``jac`` can also be a callable returning the
+ gradient of the objective. In this case, it must accept the same
+ arguments as ``fun``. (Passed to `scipy.optimize.minimize`
+ automatically)
+
+ hess, hessp : callable, optional
+ Hessian (matrix of second-order derivatives) of objective function
+ or Hessian of objective function times an arbitrary vector p.
+ Only for Newton-CG, dogleg, trust-ncg. Only one of ``hessp`` or
+ ``hess`` needs to be given. If ``hess`` is provided, then
+ ``hessp`` will be ignored. If neither ``hess`` nor ``hessp`` is
+ provided, then the Hessian product will be approximated using
+ finite differences on ``jac``. ``hessp`` must compute the Hessian
+ times an arbitrary vector. (Passed to `scipy.optimize.minimize`
+ automatically)
+
+ Algorithm settings:
+
+ minimize_every_iter : bool
+ If True then promising global sampling points will be passed to a
+ local minimization routine every iteration. If False then only the
+ final minimizer pool will be run. Defaults to True.
+
+ local_iter : int
+ Only evaluate a few of the best minimizer pool candidates every
+ iteration. If False all potential points are passed to the local
+ minimization routine.
+
+ infty_constraints : bool
+ If True then any sampling points generated which are outside will
+ the feasible domain will be saved and given an objective function
+ value of ``inf``. If False then these points will be discarded.
+ Using this functionality could lead to higher performance with
+ respect to function evaluations before the global minimum is found,
+ specifying False will use less memory at the cost of a slight
+ decrease in performance. Defaults to True.
+
+ Feedback:
+
+ disp : bool (L)
+ Set to True to print convergence messages.
+
+ sampling_method : str or function, optional
+ Current built in sampling method options are ``halton``, ``sobol`` and
+ ``simplicial``. The default ``simplicial`` provides
+ the theoretical guarantee of convergence to the global minimum in
+ finite time. ``halton`` and ``sobol`` method are faster in terms of
+ sampling point generation at the cost of the loss of
+ guaranteed convergence. It is more appropriate for most "easier"
+ problems where the convergence is relatively fast.
+ User defined sampling functions must accept two arguments of ``n``
+ sampling points of dimension ``dim`` per call and output an array of
+ sampling points with shape `n x dim`.
+
+ workers : int or map-like callable, optional
+ Sample and run the local serial minimizations in parallel.
+ Supply -1 to use all available CPU cores, or an int to use
+ that many Processes (uses `multiprocessing.Pool `).
+
+ Alternatively supply a map-like callable, such as
+ `multiprocessing.Pool.map` for parallel evaluation.
+ This evaluation is carried out as ``workers(func, iterable)``.
+ Requires that `func` be pickleable.
+
+ .. versionadded:: 1.11.0
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are:
+ ``x`` the solution array corresponding to the global minimum,
+ ``fun`` the function output at the global solution,
+ ``xl`` an ordered list of local minima solutions,
+ ``funl`` the function output at the corresponding local solutions,
+ ``success`` a Boolean flag indicating if the optimizer exited
+ successfully,
+ ``message`` which describes the cause of the termination,
+ ``nfev`` the total number of objective function evaluations including
+ the sampling calls,
+ ``nlfev`` the total number of objective function evaluations
+ culminating from all local search optimizations,
+ ``nit`` number of iterations performed by the global routine.
+
+ Notes
+ -----
+ Global optimization using simplicial homology global optimization [1]_.
+ Appropriate for solving general purpose NLP and blackbox optimization
+ problems to global optimality (low-dimensional problems).
+
+ In general, the optimization problems are of the form::
+
+ minimize f(x) subject to
+
+ g_i(x) >= 0, i = 1,...,m
+ h_j(x) = 0, j = 1,...,p
+
+ where x is a vector of one or more variables. ``f(x)`` is the objective
+ function ``R^n -> R``, ``g_i(x)`` are the inequality constraints, and
+ ``h_j(x)`` are the equality constraints.
+
+ Optionally, the lower and upper bounds for each element in x can also be
+ specified using the `bounds` argument.
+
+ While most of the theoretical advantages of SHGO are only proven for when
+ ``f(x)`` is a Lipschitz smooth function, the algorithm is also proven to
+ converge to the global optimum for the more general case where ``f(x)`` is
+ non-continuous, non-convex and non-smooth, if the default sampling method
+ is used [1]_.
+
+ The local search method may be specified using the ``minimizer_kwargs``
+ parameter which is passed on to ``scipy.optimize.minimize``. By default,
+ the ``SLSQP`` method is used. In general, it is recommended to use the
+ ``SLSQP``, ``COBYLA``, or ``COBYQA`` local minimization if inequality
+ constraints are defined for the problem since the other methods do not use
+ constraints.
+
+ The ``halton`` and ``sobol`` method points are generated using
+ `scipy.stats.qmc`. Any other QMC method could be used.
+
+ References
+ ----------
+ .. [1] Endres, SC, Sandrock, C, Focke, WW (2018) "A simplicial homology
+ algorithm for lipschitz optimisation", Journal of Global
+ Optimization.
+ .. [2] Joe, SW and Kuo, FY (2008) "Constructing Sobol' sequences with
+ better two-dimensional projections", SIAM J. Sci. Comput. 30,
+ 2635-2654.
+ .. [3] Hock, W and Schittkowski, K (1981) "Test examples for nonlinear
+ programming codes", Lecture Notes in Economics and Mathematical
+ Systems, 187. Springer-Verlag, New York.
+ http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf
+ .. [4] Wales, DJ (2015) "Perspective: Insight into reaction coordinates and
+ dynamics from the potential energy landscape",
+ Journal of Chemical Physics, 142(13), 2015.
+ .. [5] https://docs.scipy.org/doc/scipy/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize
+
+ Examples
+ --------
+ First consider the problem of minimizing the Rosenbrock function, `rosen`:
+
+ >>> from scipy.optimize import rosen, shgo
+ >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
+ >>> result = shgo(rosen, bounds)
+ >>> result.x, result.fun
+ (array([1., 1., 1., 1., 1.]), 2.920392374190081e-18)
+
+ Note that bounds determine the dimensionality of the objective
+ function and is therefore a required input, however you can specify
+ empty bounds using ``None`` or objects like ``np.inf`` which will be
+ converted to large float numbers.
+
+ >>> bounds = [(None, None), ]*4
+ >>> result = shgo(rosen, bounds)
+ >>> result.x
+ array([0.99999851, 0.99999704, 0.99999411, 0.9999882 ])
+
+ Next, we consider the Eggholder function, a problem with several local
+ minima and one global minimum. We will demonstrate the use of arguments and
+ the capabilities of `shgo`.
+ (https://en.wikipedia.org/wiki/Test_functions_for_optimization)
+
+ >>> import numpy as np
+ >>> def eggholder(x):
+ ... return (-(x[1] + 47.0)
+ ... * np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0))))
+ ... - x[0] * np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
+ ... )
+ ...
+ >>> bounds = [(-512, 512), (-512, 512)]
+
+ `shgo` has built-in low discrepancy sampling sequences. First, we will
+ input 64 initial sampling points of the *Sobol'* sequence:
+
+ >>> result = shgo(eggholder, bounds, n=64, sampling_method='sobol')
+ >>> result.x, result.fun
+ (array([512. , 404.23180824]), -959.6406627208397)
+
+ `shgo` also has a return for any other local minima that was found, these
+ can be called using:
+
+ >>> result.xl
+ array([[ 512. , 404.23180824],
+ [ 283.0759062 , -487.12565635],
+ [-294.66820039, -462.01964031],
+ [-105.87688911, 423.15323845],
+ [-242.97926 , 274.38030925],
+ [-506.25823477, 6.3131022 ],
+ [-408.71980731, -156.10116949],
+ [ 150.23207937, 301.31376595],
+ [ 91.00920901, -391.283763 ],
+ [ 202.89662724, -269.38043241],
+ [ 361.66623976, -106.96493868],
+ [-219.40612786, -244.06020508]])
+
+ >>> result.funl
+ array([-959.64066272, -718.16745962, -704.80659592, -565.99778097,
+ -559.78685655, -557.36868733, -507.87385942, -493.9605115 ,
+ -426.48799655, -421.15571437, -419.31194957, -410.98477763])
+
+ These results are useful in applications where there are many global minima
+ and the values of other global minima are desired or where the local minima
+ can provide insight into the system (for example morphologies
+ in physical chemistry [4]_).
+
+ If we want to find a larger number of local minima, we can increase the
+ number of sampling points or the number of iterations. We'll increase the
+ number of sampling points to 64 and the number of iterations from the
+ default of 1 to 3. Using ``simplicial`` this would have given us
+ 64 x 3 = 192 initial sampling points.
+
+ >>> result_2 = shgo(eggholder,
+ ... bounds, n=64, iters=3, sampling_method='sobol')
+ >>> len(result.xl), len(result_2.xl)
+ (12, 23)
+
+ Note the difference between, e.g., ``n=192, iters=1`` and ``n=64,
+ iters=3``.
+ In the first case the promising points contained in the minimiser pool
+ are processed only once. In the latter case it is processed every 64
+ sampling points for a total of 3 times.
+
+ To demonstrate solving problems with non-linear constraints consider the
+ following example from Hock and Schittkowski problem 73 (cattle-feed)
+ [3]_::
+
+ minimize: f = 24.55 * x_1 + 26.75 * x_2 + 39 * x_3 + 40.50 * x_4
+
+ subject to: 2.3 * x_1 + 5.6 * x_2 + 11.1 * x_3 + 1.3 * x_4 - 5 >= 0,
+
+ 12 * x_1 + 11.9 * x_2 + 41.8 * x_3 + 52.1 * x_4 - 21
+ -1.645 * sqrt(0.28 * x_1**2 + 0.19 * x_2**2 +
+ 20.5 * x_3**2 + 0.62 * x_4**2) >= 0,
+
+ x_1 + x_2 + x_3 + x_4 - 1 == 0,
+
+ 1 >= x_i >= 0 for all i
+
+ The approximate answer given in [3]_ is::
+
+ f([0.6355216, -0.12e-11, 0.3127019, 0.05177655]) = 29.894378
+
+ >>> def f(x): # (cattle-feed)
+ ... return 24.55*x[0] + 26.75*x[1] + 39*x[2] + 40.50*x[3]
+ ...
+ >>> def g1(x):
+ ... return 2.3*x[0] + 5.6*x[1] + 11.1*x[2] + 1.3*x[3] - 5 # >=0
+ ...
+ >>> def g2(x):
+ ... return (12*x[0] + 11.9*x[1] +41.8*x[2] + 52.1*x[3] - 21
+ ... - 1.645 * np.sqrt(0.28*x[0]**2 + 0.19*x[1]**2
+ ... + 20.5*x[2]**2 + 0.62*x[3]**2)
+ ... ) # >=0
+ ...
+ >>> def h1(x):
+ ... return x[0] + x[1] + x[2] + x[3] - 1 # == 0
+ ...
+ >>> cons = ({'type': 'ineq', 'fun': g1},
+ ... {'type': 'ineq', 'fun': g2},
+ ... {'type': 'eq', 'fun': h1})
+ >>> bounds = [(0, 1.0),]*4
+ >>> res = shgo(f, bounds, n=150, constraints=cons)
+ >>> res
+ message: Optimization terminated successfully.
+ success: True
+ fun: 29.894378159142136
+ funl: [ 2.989e+01]
+ x: [ 6.355e-01 1.137e-13 3.127e-01 5.178e-02] # may vary
+ xl: [[ 6.355e-01 1.137e-13 3.127e-01 5.178e-02]] # may vary
+ nit: 1
+ nfev: 142 # may vary
+ nlfev: 35 # may vary
+ nljev: 5
+ nlhev: 0
+
+ >>> g1(res.x), g2(res.x), h1(res.x)
+ (-5.062616992290714e-14, -2.9594104944408173e-12, 0.0)
+
+ """
+ # if necessary, convert bounds class to old bounds
+ if isinstance(bounds, Bounds):
+ bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb))
+
+ # Initiate SHGO class
+ # use in context manager to make sure that any parallelization
+ # resources are freed.
+ with SHGO(func, bounds, args=args, constraints=constraints, n=n,
+ iters=iters, callback=callback,
+ minimizer_kwargs=minimizer_kwargs,
+ options=options, sampling_method=sampling_method,
+ workers=workers) as shc:
+ # Run the algorithm, process results and test success
+ shc.iterate_all()
+
+ if not shc.break_routine:
+ if shc.disp:
+ logging.info("Successfully completed construction of complex.")
+
+ # Test post iterations success
+ if len(shc.LMC.xl_maps) == 0:
+ # If sampling failed to find pool, return lowest sampled point
+ # with a warning
+ shc.find_lowest_vertex()
+ shc.break_routine = True
+ shc.fail_routine(mes="Failed to find a feasible minimizer point. "
+ f"Lowest sampling point = {shc.f_lowest}")
+ shc.res.fun = shc.f_lowest
+ shc.res.x = shc.x_lowest
+ shc.res.nfev = shc.fn
+ shc.res.tnev = shc.n_sampled
+ else:
+ # Test that the optimal solutions do not violate any constraints
+ pass # TODO
+
+ # Confirm the routine ran successfully
+ if not shc.break_routine:
+ shc.res.message = 'Optimization terminated successfully.'
+ shc.res.success = True
+
+ # Return the final results
+ return shc.res
+
+
+class SHGO:
+ def __init__(self, func, bounds, args=(), constraints=None, n=None,
+ iters=None, callback=None, minimizer_kwargs=None,
+ options=None, sampling_method='simplicial', workers=1):
+ from scipy.stats import qmc
+ # Input checks
+ methods = ['halton', 'sobol', 'simplicial']
+ if isinstance(sampling_method, str) and sampling_method not in methods:
+ raise ValueError(("Unknown sampling_method specified."
+ " Valid methods: {}").format(', '.join(methods)))
+
+ # copy the options dictionaries so that the user input is not mutated
+ if minimizer_kwargs is not None and isinstance(minimizer_kwargs, dict):
+ minimizer_kwargs = minimizer_kwargs.copy()
+ if options is not None and isinstance(options, dict):
+ options = options.copy()
+
+ if options is not None and options.get('jac', None) is True:
+ if minimizer_kwargs is None:
+ minimizer_kwargs = {}
+ minimizer_kwargs['jac'] = True
+ options.pop('jac')
+
+ # Split obj func if given with Jac
+ try:
+ if ((minimizer_kwargs['jac'] is True) and
+ (not callable(minimizer_kwargs['jac']))):
+ self.func = MemoizeJac(func)
+ jac = self.func.derivative
+ minimizer_kwargs['jac'] = jac
+ func = self.func # fun
+ else:
+ self.func = func # Normal definition of objective function
+ except (TypeError, KeyError):
+ self.func = func # Normal definition of objective function
+
+ # Initiate class
+ self.func = _FunctionWrapper(func, args)
+ self.bounds = bounds
+ self.args = args
+ self.callback = callback
+
+ # Bounds
+ abound = np.array(bounds, float)
+ self.dim = np.shape(abound)[0] # Dimensionality of problem
+
+ # Set none finite values to large floats
+ infind = ~np.isfinite(abound)
+ abound[infind[:, 0], 0] = -1e50
+ abound[infind[:, 1], 1] = 1e50
+
+ # Check if bounds are correctly specified
+ bnderr = abound[:, 0] > abound[:, 1]
+ if bnderr.any():
+ raise ValueError("Error: lb > ub in bounds "
+ f"{', '.join(str(b) for b in bnderr)}.")
+
+ self.bounds = abound
+
+ # Constraints
+ # Process constraint dict sequence:
+ self.constraints = constraints
+ if constraints is not None:
+ self.min_cons = constraints
+ self.g_cons = []
+ self.g_args = []
+
+ # shgo internals deals with old-style constraints
+ # self.constraints is used to create Complex, so need
+ # to be stored internally in old-style.
+ # `minimize` takes care of normalising these constraints
+ # for slsqp/cobyla/cobyqa/trust-constr.
+ self.constraints = standardize_constraints(
+ constraints,
+ np.empty(self.dim, float),
+ 'old'
+ )
+ for cons in self.constraints:
+ if cons['type'] in ('ineq'):
+ self.g_cons.append(cons['fun'])
+ try:
+ self.g_args.append(cons['args'])
+ except KeyError:
+ self.g_args.append(())
+ self.g_cons = tuple(self.g_cons)
+ self.g_args = tuple(self.g_args)
+ else:
+ self.g_cons = None
+ self.g_args = None
+
+ # Define local minimization keyword arguments
+ # Start with defaults
+ self.minimizer_kwargs = {'method': 'SLSQP',
+ 'bounds': self.bounds,
+ 'options': {},
+ 'callback': self.callback
+ }
+ if minimizer_kwargs is not None:
+ # Overwrite with supplied values
+ self.minimizer_kwargs.update(minimizer_kwargs)
+
+ else:
+ self.minimizer_kwargs['options'] = {'ftol': 1e-12}
+
+ if (
+ self.minimizer_kwargs['method'].lower() in ('slsqp', 'cobyla',
+ 'cobyqa',
+ 'trust-constr')
+ and (
+ minimizer_kwargs is not None and
+ 'constraints' not in minimizer_kwargs and
+ constraints is not None
+ ) or
+ (self.g_cons is not None)
+ ):
+ self.minimizer_kwargs['constraints'] = self.min_cons
+
+ # Process options dict
+ if options is not None:
+ self.init_options(options)
+ else: # Default settings:
+ self.f_min_true = None
+ self.minimize_every_iter = True
+
+ # Algorithm limits
+ self.maxiter = None
+ self.maxfev = None
+ self.maxev = None
+ self.maxtime = None
+ self.f_min_true = None
+ self.minhgrd = None
+
+ # Objective function knowledge
+ self.symmetry = None
+
+ # Algorithm functionality
+ self.infty_cons_sampl = True
+ self.local_iter = False
+
+ # Feedback
+ self.disp = False
+
+ # normalize grad + hess calls for args
+ # this has to be done after minimizer_kwargs has finished having its
+ # jac/hess/args edited.
+ _grad = self.minimizer_kwargs.get('jac', None)
+ if callable(_grad):
+ self.minimizer_kwargs['jac'] = _FunctionWrapper(_grad, self.args)
+ _hess = self.minimizer_kwargs.get('hess', None)
+ if callable(_hess):
+ self.minimizer_kwargs['hess'] = _FunctionWrapper(_hess, self.args)
+
+ # we've already wrapped fun, grad, hess, so no need for args
+ self.minimizer_kwargs.pop("args", None)
+ self.minimizer_kwargs["options"].pop("args", None)
+
+ # Remove unknown arguments in self.minimizer_kwargs
+ # Start with arguments all the solvers have in common
+ self.min_solver_args = ['fun', 'x0', 'args',
+ 'callback', 'options', 'method']
+ # then add the ones unique to specific solvers
+ solver_args = {
+ '_custom': ['jac', 'hess', 'hessp', 'bounds', 'constraints'],
+ 'nelder-mead': [],
+ 'powell': [],
+ 'cg': ['jac'],
+ 'bfgs': ['jac'],
+ 'newton-cg': ['jac', 'hess', 'hessp'],
+ 'l-bfgs-b': ['jac', 'bounds'],
+ 'tnc': ['jac', 'bounds'],
+ 'cobyla': ['constraints', 'catol'],
+ 'cobyqa': ['bounds', 'constraints', 'feasibility_tol'],
+ 'slsqp': ['jac', 'bounds', 'constraints'],
+ 'dogleg': ['jac', 'hess'],
+ 'trust-ncg': ['jac', 'hess', 'hessp'],
+ 'trust-krylov': ['jac', 'hess', 'hessp'],
+ 'trust-exact': ['jac', 'hess'],
+ 'trust-constr': ['jac', 'hess', 'hessp', 'constraints'],
+ }
+ method = self.minimizer_kwargs['method']
+ self.min_solver_args += solver_args[method.lower()]
+
+ # Only retain the known arguments
+ def _restrict_to_keys(dictionary, goodkeys):
+ """Remove keys from dictionary if not in goodkeys - inplace"""
+ existingkeys = set(dictionary)
+ for key in existingkeys - set(goodkeys):
+ dictionary.pop(key, None)
+
+ _restrict_to_keys(self.minimizer_kwargs, self.min_solver_args)
+ _restrict_to_keys(self.minimizer_kwargs['options'],
+ self.min_solver_args + ['ftol'])
+
+ # Algorithm controls
+ # Global controls
+ self.stop_global = False # Used in the stopping_criteria method
+ self.break_routine = False # Break the algorithm globally
+ self.iters = iters # Iterations to be ran
+ self.iters_done = 0 # Iterations completed
+ self.n = n # Sampling points per iteration
+ self.nc = 0 # n # Sampling points to sample in current iteration
+ self.n_prc = 0 # Processed points (used to track Delaunay iters)
+ self.n_sampled = 0 # To track no. of sampling points already generated
+ self.fn = 0 # Number of feasible sampling points evaluations performed
+ self.hgr = 0 # Homology group rank
+ # Initially attempt to build the triangulation incrementally:
+ self.qhull_incremental = True
+
+ # Default settings if no sampling criteria.
+ if (self.n is None) and (self.iters is None) \
+ and (sampling_method == 'simplicial'):
+ self.n = 2 ** self.dim + 1
+ self.nc = 0 # self.n
+ if self.iters is None:
+ self.iters = 1
+ if (self.n is None) and not (sampling_method == 'simplicial'):
+ self.n = self.n = 100
+ self.nc = 0 # self.n
+ if (self.n == 100) and (sampling_method == 'simplicial'):
+ self.n = 2 ** self.dim + 1
+
+ if not ((self.maxiter is None) and (self.maxfev is None) and (
+ self.maxev is None)
+ and (self.minhgrd is None) and (self.f_min_true is None)):
+ self.iters = None
+
+ # Set complex construction mode based on a provided stopping criteria:
+ # Initialise sampling Complex and function cache
+ # Note that sfield_args=() since args are already wrapped in self.func
+ # using the_FunctionWrapper class.
+ self.HC = Complex(dim=self.dim, domain=self.bounds,
+ sfield=self.func, sfield_args=(),
+ symmetry=self.symmetry,
+ constraints=self.constraints,
+ workers=workers)
+
+ # Choose complex constructor
+ if sampling_method == 'simplicial':
+ self.iterate_complex = self.iterate_hypercube
+ self.sampling_method = sampling_method
+
+ elif sampling_method in ['halton', 'sobol'] or \
+ not isinstance(sampling_method, str):
+ self.iterate_complex = self.iterate_delaunay
+ # Sampling method used
+ if sampling_method in ['halton', 'sobol']:
+ if sampling_method == 'sobol':
+ self.n = int(2 ** np.ceil(np.log2(self.n)))
+ # self.n #TODO: Should always be self.n, this is
+ # unacceptable for shgo, check that nfev behaves as
+ # expected.
+ self.nc = 0
+ self.sampling_method = 'sobol'
+ self.qmc_engine = qmc.Sobol(d=self.dim, scramble=False,
+ seed=0)
+ else:
+ self.sampling_method = 'halton'
+ self.qmc_engine = qmc.Halton(d=self.dim, scramble=True,
+ seed=0)
+
+ def sampling_method(n, d):
+ return self.qmc_engine.random(n)
+
+ else:
+ # A user defined sampling method:
+ self.sampling_method = 'custom'
+
+ self.sampling = self.sampling_custom
+ self.sampling_function = sampling_method # F(n, d)
+
+ # Local controls
+ self.stop_l_iter = False # Local minimisation iterations
+ self.stop_complex_iter = False # Sampling iterations
+
+ # Initiate storage objects used in algorithm classes
+ self.minimizer_pool = []
+
+ # Cache of local minimizers mapped
+ self.LMC = LMapCache()
+
+ # Initialize return object
+ self.res = OptimizeResult() # scipy.optimize.OptimizeResult object
+ self.res.nfev = 0 # Includes each sampling point as func evaluation
+ self.res.nlfev = 0 # Local function evals for all minimisers
+ self.res.nljev = 0 # Local Jacobian evals for all minimisers
+ self.res.nlhev = 0 # Local Hessian evals for all minimisers
+
+ # Initiation aids
+ def init_options(self, options):
+ """
+ Initiates the options.
+
+ Can also be useful to change parameters after class initiation.
+
+ Parameters
+ ----------
+ options : dict
+
+ Returns
+ -------
+ None
+
+ """
+ # Update 'options' dict passed to optimize.minimize
+ # Do this first so we don't mutate `options` below.
+ self.minimizer_kwargs['options'].update(options)
+
+ # Ensure that 'jac', 'hess', and 'hessp' are passed directly to
+ # `minimize` as keywords, not as part of its 'options' dictionary.
+ for opt in ['jac', 'hess', 'hessp']:
+ if opt in self.minimizer_kwargs['options']:
+ self.minimizer_kwargs[opt] = (
+ self.minimizer_kwargs['options'].pop(opt))
+
+ # Default settings:
+ self.minimize_every_iter = options.get('minimize_every_iter', True)
+
+ # Algorithm limits
+ # Maximum number of iterations to perform.
+ self.maxiter = options.get('maxiter', None)
+ # Maximum number of function evaluations in the feasible domain
+ self.maxfev = options.get('maxfev', None)
+ # Maximum number of sampling evaluations (includes searching in
+ # infeasible points
+ self.maxev = options.get('maxev', None)
+ # Maximum processing runtime allowed
+ self.init = time.time()
+ self.maxtime = options.get('maxtime', None)
+ if 'f_min' in options:
+ # Specify the minimum objective function value, if it is known.
+ self.f_min_true = options['f_min']
+ self.f_tol = options.get('f_tol', 1e-4)
+ else:
+ self.f_min_true = None
+
+ self.minhgrd = options.get('minhgrd', None)
+
+ # Objective function knowledge
+ self.symmetry = options.get('symmetry', False)
+ if self.symmetry:
+ self.symmetry = [0, ]*len(self.bounds)
+ else:
+ self.symmetry = None
+ # Algorithm functionality
+ # Only evaluate a few of the best candidates
+ self.local_iter = options.get('local_iter', False)
+ self.infty_cons_sampl = options.get('infty_constraints', True)
+
+ # Feedback
+ self.disp = options.get('disp', False)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return self.HC.V._mapwrapper.__exit__(*args)
+
+ # Iteration properties
+ # Main construction loop:
+ def iterate_all(self):
+ """
+ Construct for `iters` iterations.
+
+ If uniform sampling is used, every iteration adds 'n' sampling points.
+
+ Iterations if a stopping criteria (e.g., sampling points or
+ processing time) has been met.
+
+ """
+ if self.disp:
+ logging.info('Splitting first generation')
+
+ while not self.stop_global:
+ if self.break_routine:
+ break
+ # Iterate complex, process minimisers
+ self.iterate()
+ self.stopping_criteria()
+
+ # Build minimiser pool
+ # Final iteration only needed if pools weren't minimised every
+ # iteration
+ if not self.minimize_every_iter:
+ if not self.break_routine:
+ self.find_minima()
+
+ self.res.nit = self.iters_done # + 1
+ self.fn = self.HC.V.nfev
+
+ def find_minima(self):
+ """
+ Construct the minimizer pool, map the minimizers to local minima
+ and sort the results into a global return object.
+ """
+ if self.disp:
+ logging.info('Searching for minimizer pool...')
+
+ self.minimizers()
+
+ if len(self.X_min) != 0:
+ # Minimize the pool of minimizers with local minimization methods
+ # Note that if Options['local_iter'] is an `int` instead of default
+ # value False then only that number of candidates will be minimized
+ self.minimise_pool(self.local_iter)
+ # Sort results and build the global return object
+ self.sort_result()
+
+ # Lowest values used to report in case of failures
+ self.f_lowest = self.res.fun
+ self.x_lowest = self.res.x
+ else:
+ self.find_lowest_vertex()
+
+ if self.disp:
+ logging.info(f"Minimiser pool = SHGO.X_min = {self.X_min}")
+
+ def find_lowest_vertex(self):
+ # Find the lowest objective function value on one of
+ # the vertices of the simplicial complex
+ self.f_lowest = np.inf
+ for x in self.HC.V.cache:
+ if self.HC.V[x].f < self.f_lowest:
+ if self.disp:
+ logging.info(f'self.HC.V[x].f = {self.HC.V[x].f}')
+ self.f_lowest = self.HC.V[x].f
+ self.x_lowest = self.HC.V[x].x_a
+ for lmc in self.LMC.cache:
+ if self.LMC[lmc].f_min < self.f_lowest:
+ self.f_lowest = self.LMC[lmc].f_min
+ self.x_lowest = self.LMC[lmc].x_l
+
+ if self.f_lowest == np.inf: # no feasible point
+ self.f_lowest = None
+ self.x_lowest = None
+
+ # Stopping criteria functions:
+ def finite_iterations(self):
+ mi = min(x for x in [self.iters, self.maxiter] if x is not None)
+ if self.disp:
+ logging.info(f'Iterations done = {self.iters_done} / {mi}')
+ if self.iters is not None:
+ if self.iters_done >= (self.iters):
+ self.stop_global = True
+
+ if self.maxiter is not None: # Stop for infeasible sampling
+ if self.iters_done >= (self.maxiter):
+ self.stop_global = True
+ return self.stop_global
+
+ def finite_fev(self):
+ # Finite function evals in the feasible domain
+ if self.disp:
+ logging.info(f'Function evaluations done = {self.fn} / {self.maxfev}')
+ if self.fn >= self.maxfev:
+ self.stop_global = True
+ return self.stop_global
+
+ def finite_ev(self):
+ # Finite evaluations including infeasible sampling points
+ if self.disp:
+ logging.info(f'Sampling evaluations done = {self.n_sampled} '
+ f'/ {self.maxev}')
+ if self.n_sampled >= self.maxev:
+ self.stop_global = True
+
+ def finite_time(self):
+ if self.disp:
+ logging.info(f'Time elapsed = {time.time() - self.init} '
+ f'/ {self.maxtime}')
+ if (time.time() - self.init) >= self.maxtime:
+ self.stop_global = True
+
+ def finite_precision(self):
+ """
+ Stop the algorithm if the final function value is known
+
+ Specify in options (with ``self.f_min_true = options['f_min']``)
+ and the tolerance with ``f_tol = options['f_tol']``
+ """
+ # If no minimizer has been found use the lowest sampling value
+ self.find_lowest_vertex()
+ if self.disp:
+ logging.info(f'Lowest function evaluation = {self.f_lowest}')
+ logging.info(f'Specified minimum = {self.f_min_true}')
+ # If no feasible point was return from test
+ if self.f_lowest is None:
+ return self.stop_global
+
+ # Function to stop algorithm at specified percentage error:
+ if self.f_min_true == 0.0:
+ if self.f_lowest <= self.f_tol:
+ self.stop_global = True
+ else:
+ pe = (self.f_lowest - self.f_min_true) / abs(self.f_min_true)
+ if self.f_lowest <= self.f_min_true:
+ self.stop_global = True
+ # 2if (pe - self.f_tol) <= abs(1.0 / abs(self.f_min_true)):
+ if abs(pe) >= 2 * self.f_tol:
+ warnings.warn(
+ f"A much lower value than expected f* = {self.f_min_true} "
+ f"was found f_lowest = {self.f_lowest}",
+ stacklevel=3
+ )
+ if pe <= self.f_tol:
+ self.stop_global = True
+
+ return self.stop_global
+
+ def finite_homology_growth(self):
+ """
+ Stop the algorithm if homology group rank did not grow in iteration.
+ """
+ if self.LMC.size == 0:
+ return # pass on no reason to stop yet.
+ self.hgrd = self.LMC.size - self.hgr
+
+ self.hgr = self.LMC.size
+ if self.hgrd <= self.minhgrd:
+ self.stop_global = True
+ if self.disp:
+ logging.info(f'Current homology growth = {self.hgrd} '
+ f' (minimum growth = {self.minhgrd})')
+ return self.stop_global
+
+ def stopping_criteria(self):
+ """
+ Various stopping criteria ran every iteration
+
+ Returns
+ -------
+ stop : bool
+ """
+ if self.maxiter is not None:
+ self.finite_iterations()
+ if self.iters is not None:
+ self.finite_iterations()
+ if self.maxfev is not None:
+ self.finite_fev()
+ if self.maxev is not None:
+ self.finite_ev()
+ if self.maxtime is not None:
+ self.finite_time()
+ if self.f_min_true is not None:
+ self.finite_precision()
+ if self.minhgrd is not None:
+ self.finite_homology_growth()
+ return self.stop_global
+
+ def iterate(self):
+ self.iterate_complex()
+
+ # Build minimizer pool
+ if self.minimize_every_iter:
+ if not self.break_routine:
+ self.find_minima() # Process minimizer pool
+
+ # Algorithm updates
+ self.iters_done += 1
+
+ def iterate_hypercube(self):
+ """
+ Iterate a subdivision of the complex
+
+ Note: called with ``self.iterate_complex()`` after class initiation
+ """
+ # Iterate the complex
+ if self.disp:
+ logging.info('Constructing and refining simplicial complex graph '
+ 'structure')
+ if self.n is None:
+ self.HC.refine_all()
+ self.n_sampled = self.HC.V.size() # nevs counted
+ else:
+ self.HC.refine(self.n)
+ self.n_sampled += self.n
+
+ if self.disp:
+ logging.info('Triangulation completed, evaluating all constraints '
+ 'and objective function values.')
+
+ # Re-add minimisers to complex
+ if len(self.LMC.xl_maps) > 0:
+ for xl in self.LMC.cache:
+ v = self.HC.V[xl]
+ v_near = v.star()
+ for v in v.nn:
+ v_near = v_near.union(v.nn)
+ # Reconnect vertices to complex
+ # if self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l),
+ # near=v_near):
+ # continue
+ # else:
+ # If failure to find in v_near, then search all vertices
+ # (very expensive operation:
+ # self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l)
+ # )
+
+ # Evaluate all constraints and functions
+ self.HC.V.process_pools()
+ if self.disp:
+ logging.info('Evaluations completed.')
+
+ # feasible sampling points counted by the triangulation.py routines
+ self.fn = self.HC.V.nfev
+ return
+
+ def iterate_delaunay(self):
+ """
+ Build a complex of Delaunay triangulated points
+
+ Note: called with ``self.iterate_complex()`` after class initiation
+ """
+ self.nc += self.n
+ self.sampled_surface(infty_cons_sampl=self.infty_cons_sampl)
+
+ # Add sampled points to a triangulation, construct self.Tri
+ if self.disp:
+ logging.info(f'self.n = {self.n}')
+ logging.info(f'self.nc = {self.nc}')
+ logging.info('Constructing and refining simplicial complex graph '
+ 'structure from sampling points.')
+
+ if self.dim < 2:
+ self.Ind_sorted = np.argsort(self.C, axis=0)
+ self.Ind_sorted = self.Ind_sorted.flatten()
+ tris = []
+ for ind, ind_s in enumerate(self.Ind_sorted):
+ if ind > 0:
+ tris.append(self.Ind_sorted[ind - 1:ind + 1])
+
+ tris = np.array(tris)
+ # Store 1D triangulation:
+ self.Tri = namedtuple('Tri', ['points', 'simplices'])(self.C, tris)
+ self.points = {}
+ else:
+ if self.C.shape[0] > self.dim + 1: # Ensure a simplex can be built
+ self.delaunay_triangulation(n_prc=self.n_prc)
+ self.n_prc = self.C.shape[0]
+
+ if self.disp:
+ logging.info('Triangulation completed, evaluating all '
+ 'constraints and objective function values.')
+
+ if hasattr(self, 'Tri'):
+ self.HC.vf_to_vv(self.Tri.points, self.Tri.simplices)
+
+ # Process all pools
+ # Evaluate all constraints and functions
+ if self.disp:
+ logging.info('Triangulation completed, evaluating all constraints '
+ 'and objective function values.')
+
+ # Evaluate all constraints and functions
+ self.HC.V.process_pools()
+ if self.disp:
+ logging.info('Evaluations completed.')
+
+ # feasible sampling points counted by the triangulation.py routines
+ self.fn = self.HC.V.nfev
+ self.n_sampled = self.nc # nevs counted in triangulation
+ return
+
+ # Hypercube minimizers
+ def minimizers(self):
+ """
+ Returns the indexes of all minimizers
+ """
+ self.minimizer_pool = []
+ # Note: Can implement parallelization here
+ for x in self.HC.V.cache:
+ in_LMC = False
+ if len(self.LMC.xl_maps) > 0:
+ for xlmi in self.LMC.xl_maps:
+ if np.all(np.array(x) == np.array(xlmi)):
+ in_LMC = True
+ if in_LMC:
+ continue
+
+ if self.HC.V[x].minimiser():
+ if self.disp:
+ logging.info('=' * 60)
+ logging.info(f'v.x = {self.HC.V[x].x_a} is minimizer')
+ logging.info(f'v.f = {self.HC.V[x].f} is minimizer')
+ logging.info('=' * 30)
+
+ if self.HC.V[x] not in self.minimizer_pool:
+ self.minimizer_pool.append(self.HC.V[x])
+
+ if self.disp:
+ logging.info('Neighbors:')
+ logging.info('=' * 30)
+ for vn in self.HC.V[x].nn:
+ logging.info(f'x = {vn.x} || f = {vn.f}')
+
+ logging.info('=' * 60)
+ self.minimizer_pool_F = []
+ self.X_min = []
+ # normalized tuple in the Vertex cache
+ self.X_min_cache = {} # Cache used in hypercube sampling
+
+ for v in self.minimizer_pool:
+ self.X_min.append(v.x_a)
+ self.minimizer_pool_F.append(v.f)
+ self.X_min_cache[tuple(v.x_a)] = v.x
+
+ self.minimizer_pool_F = np.array(self.minimizer_pool_F)
+ self.X_min = np.array(self.X_min)
+
+ # TODO: Only do this if global mode
+ self.sort_min_pool()
+
+ return self.X_min
+
+ # Local minimisation
+ # Minimiser pool processing
+ def minimise_pool(self, force_iter=False):
+ """
+ This processing method can optionally minimise only the best candidate
+ solutions in the minimiser pool
+
+ Parameters
+ ----------
+ force_iter : int
+ Number of starting minimizers to process (can be specified
+ globally or locally)
+
+ """
+ # Find first local minimum
+ # NOTE: Since we always minimize this value regardless it is a waste to
+ # build the topograph first before minimizing
+ lres_f_min = self.minimize(self.X_min[0], ind=self.minimizer_pool[0])
+
+ # Trim minimized point from current minimizer set
+ self.trim_min_pool(0)
+
+ while not self.stop_l_iter:
+ # Global stopping criteria:
+ self.stopping_criteria()
+
+ # Note first iteration is outside loop:
+ if force_iter:
+ force_iter -= 1
+ if force_iter == 0:
+ self.stop_l_iter = True
+ break
+
+ if np.shape(self.X_min)[0] == 0:
+ self.stop_l_iter = True
+ break
+
+ # Construct topograph from current minimizer set
+ # (NOTE: This is a very small topograph using only the minizer pool
+ # , it might be worth using some graph theory tools instead.
+ self.g_topograph(lres_f_min.x, self.X_min)
+
+ # Find local minimum at the miniser with the greatest Euclidean
+ # distance from the current solution
+ ind_xmin_l = self.Z[:, -1]
+ lres_f_min = self.minimize(self.Ss[-1, :], self.minimizer_pool[-1])
+
+ # Trim minimised point from current minimizer set
+ self.trim_min_pool(ind_xmin_l)
+
+ # Reset controls
+ self.stop_l_iter = False
+ return
+
+ def sort_min_pool(self):
+ # Sort to find minimum func value in min_pool
+ self.ind_f_min = np.argsort(self.minimizer_pool_F)
+ self.minimizer_pool = np.array(self.minimizer_pool)[self.ind_f_min]
+ self.minimizer_pool_F = np.array(self.minimizer_pool_F)[
+ self.ind_f_min]
+ return
+
+ def trim_min_pool(self, trim_ind):
+ self.X_min = np.delete(self.X_min, trim_ind, axis=0)
+ self.minimizer_pool_F = np.delete(self.minimizer_pool_F, trim_ind)
+ self.minimizer_pool = np.delete(self.minimizer_pool, trim_ind)
+ return
+
+ def g_topograph(self, x_min, X_min):
+ """
+ Returns the topographical vector stemming from the specified value
+ ``x_min`` for the current feasible set ``X_min`` with True boolean
+ values indicating positive entries and False values indicating
+ negative entries.
+
+ """
+ x_min = np.array([x_min])
+ self.Y = spatial.distance.cdist(x_min, X_min, 'euclidean')
+ # Find sorted indexes of spatial distances:
+ self.Z = np.argsort(self.Y, axis=-1)
+
+ self.Ss = X_min[self.Z][0]
+ self.minimizer_pool = self.minimizer_pool[self.Z]
+ self.minimizer_pool = self.minimizer_pool[0]
+ return self.Ss
+
+ # Local bound functions
+ def construct_lcb_simplicial(self, v_min):
+ """
+ Construct locally (approximately) convex bounds
+
+ Parameters
+ ----------
+ v_min : Vertex object
+ The minimizer vertex
+
+ Returns
+ -------
+ cbounds : list of lists
+ List of size dimension with length-2 list of bounds for each
+ dimension.
+
+ """
+ cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds]
+ # Loop over all bounds
+ for vn in v_min.nn:
+ for i, x_i in enumerate(vn.x_a):
+ # Lower bound
+ if (x_i < v_min.x_a[i]) and (x_i > cbounds[i][0]):
+ cbounds[i][0] = x_i
+
+ # Upper bound
+ if (x_i > v_min.x_a[i]) and (x_i < cbounds[i][1]):
+ cbounds[i][1] = x_i
+
+ if self.disp:
+ logging.info(f'cbounds found for v_min.x_a = {v_min.x_a}')
+ logging.info(f'cbounds = {cbounds}')
+
+ return cbounds
+
+ def construct_lcb_delaunay(self, v_min, ind=None):
+ """
+ Construct locally (approximately) convex bounds
+
+ Parameters
+ ----------
+ v_min : Vertex object
+ The minimizer vertex
+
+ Returns
+ -------
+ cbounds : list of lists
+ List of size dimension with length-2 list of bounds for each
+ dimension.
+ """
+ cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds]
+
+ return cbounds
+
+ # Minimize a starting point locally
+ def minimize(self, x_min, ind=None):
+ """
+ This function is used to calculate the local minima using the specified
+ sampling point as a starting value.
+
+ Parameters
+ ----------
+ x_min : vector of floats
+ Current starting point to minimize.
+
+ Returns
+ -------
+ lres : OptimizeResult
+ The local optimization result represented as a `OptimizeResult`
+ object.
+ """
+ # Use minima maps if vertex was already run
+ if self.disp:
+ logging.info(f'Vertex minimiser maps = {self.LMC.v_maps}')
+
+ if self.LMC[x_min].lres is not None:
+ logging.info(f'Found self.LMC[x_min].lres = '
+ f'{self.LMC[x_min].lres}')
+ return self.LMC[x_min].lres
+
+ if self.callback is not None:
+ logging.info(f'Callback for minimizer starting at {x_min}:')
+
+ if self.disp:
+ logging.info(f'Starting minimization at {x_min}...')
+
+ if self.sampling_method == 'simplicial':
+ x_min_t = tuple(x_min)
+ # Find the normalized tuple in the Vertex cache:
+ x_min_t_norm = self.X_min_cache[tuple(x_min_t)]
+ x_min_t_norm = tuple(x_min_t_norm)
+ g_bounds = self.construct_lcb_simplicial(self.HC.V[x_min_t_norm])
+ if 'bounds' in self.min_solver_args:
+ self.minimizer_kwargs['bounds'] = g_bounds
+ logging.info(self.minimizer_kwargs['bounds'])
+
+ else:
+ g_bounds = self.construct_lcb_delaunay(x_min, ind=ind)
+ if 'bounds' in self.min_solver_args:
+ self.minimizer_kwargs['bounds'] = g_bounds
+ logging.info(self.minimizer_kwargs['bounds'])
+
+ if self.disp and 'bounds' in self.minimizer_kwargs:
+ logging.info('bounds in kwarg:')
+ logging.info(self.minimizer_kwargs['bounds'])
+
+ # Local minimization using scipy.optimize.minimize:
+ lres = minimize(self.func, x_min, **self.minimizer_kwargs)
+
+ if self.disp:
+ logging.info(f'lres = {lres}')
+
+ # Local function evals for all minimizers
+ self.res.nlfev += lres.nfev
+ if 'njev' in lres:
+ self.res.nljev += lres.njev
+ if 'nhev' in lres:
+ self.res.nlhev += lres.nhev
+
+ try: # Needed because of the brain dead 1x1 NumPy arrays
+ lres.fun = lres.fun[0]
+ except (IndexError, TypeError):
+ lres.fun
+
+ # Append minima maps
+ self.LMC[x_min]
+ self.LMC.add_res(x_min, lres, bounds=g_bounds)
+
+ return lres
+
+ # Post local minimization processing
+ def sort_result(self):
+ """
+ Sort results and build the global return object
+ """
+ # Sort results in local minima cache
+ results = self.LMC.sort_cache_result()
+ self.res.xl = results['xl']
+ self.res.funl = results['funl']
+ self.res.x = results['x']
+ self.res.fun = results['fun']
+
+ # Add local func evals to sampling func evals
+ # Count the number of feasible vertices and add to local func evals:
+ self.res.nfev = self.fn + self.res.nlfev
+ return self.res
+
+ # Algorithm controls
+ def fail_routine(self, mes=("Failed to converge")):
+ self.break_routine = True
+ self.res.success = False
+ self.X_min = [None]
+ self.res.message = mes
+
+ def sampled_surface(self, infty_cons_sampl=False):
+ """
+ Sample the function surface.
+
+ There are 2 modes, if ``infty_cons_sampl`` is True then the sampled
+ points that are generated outside the feasible domain will be
+ assigned an ``inf`` value in accordance with SHGO rules.
+ This guarantees convergence and usually requires less objective
+ function evaluations at the computational costs of more Delaunay
+ triangulation points.
+
+ If ``infty_cons_sampl`` is False, then the infeasible points are
+ discarded and only a subspace of the sampled points are used. This
+ comes at the cost of the loss of guaranteed convergence and usually
+ requires more objective function evaluations.
+ """
+ # Generate sampling points
+ if self.disp:
+ logging.info('Generating sampling points')
+ self.sampling(self.nc, self.dim)
+ if len(self.LMC.xl_maps) > 0:
+ self.C = np.vstack((self.C, np.array(self.LMC.xl_maps)))
+ if not infty_cons_sampl:
+ # Find subspace of feasible points
+ if self.g_cons is not None:
+ self.sampling_subspace()
+
+ # Sort remaining samples
+ self.sorted_samples()
+
+ # Find objective function references
+ self.n_sampled = self.nc
+
+ def sampling_custom(self, n, dim):
+ """
+ Generates uniform sampling points in a hypercube and scales the points
+ to the bound limits.
+ """
+ # Generate sampling points.
+ # Generate uniform sample points in [0, 1]^m \subset R^m
+ self.C = self.sampling_function(n, dim)
+ # Distribute over bounds
+ for i in range(len(self.bounds)):
+ self.C[:, i] = (self.C[:, i] *
+ (self.bounds[i][1] - self.bounds[i][0])
+ + self.bounds[i][0])
+ return self.C
+
+ def sampling_subspace(self):
+ """Find subspace of feasible points from g_func definition"""
+ # Subspace of feasible points.
+ for ind, g in enumerate(self.g_cons):
+ # C.shape = (Z, dim) where Z is the number of sampling points to
+ # evaluate and dim is the dimensionality of the problem.
+ # the constraint function may not be vectorised so have to step
+ # through each sampling point sequentially.
+ feasible = np.array(
+ [np.all(g(x_C, *self.g_args[ind]) >= 0.0) for x_C in self.C],
+ dtype=bool
+ )
+ self.C = self.C[feasible]
+
+ if self.C.size == 0:
+ self.res.message = ('No sampling point found within the '
+ + 'feasible set. Increasing sampling '
+ + 'size.')
+ # sampling correctly for both 1-D and >1-D cases
+ if self.disp:
+ logging.info(self.res.message)
+
+ def sorted_samples(self): # Validated
+ """Find indexes of the sorted sampling points"""
+ self.Ind_sorted = np.argsort(self.C, axis=0)
+ self.Xs = self.C[self.Ind_sorted]
+ return self.Ind_sorted, self.Xs
+
+ def delaunay_triangulation(self, n_prc=0):
+ if hasattr(self, 'Tri') and self.qhull_incremental:
+ # TODO: Uncertain if n_prc needs to add len(self.LMC.xl_maps)
+ # in self.sampled_surface
+ self.Tri.add_points(self.C[n_prc:, :])
+ else:
+ try:
+ self.Tri = spatial.Delaunay(self.C,
+ incremental=self.qhull_incremental,
+ )
+ except spatial.QhullError:
+ if str(sys.exc_info()[1])[:6] == 'QH6239':
+ logging.warning('QH6239 Qhull precision error detected, '
+ 'this usually occurs when no bounds are '
+ 'specified, Qhull can only run with '
+ 'handling cocircular/cospherical points'
+ ' and in this case incremental mode is '
+ 'switched off. The performance of shgo '
+ 'will be reduced in this mode.')
+ self.qhull_incremental = False
+ self.Tri = spatial.Delaunay(self.C,
+ incremental=
+ self.qhull_incremental)
+ else:
+ raise
+
+ return self.Tri
+
+
+class LMap:
+ def __init__(self, v):
+ self.v = v
+ self.x_l = None
+ self.lres = None
+ self.f_min = None
+ self.lbounds = []
+
+
+class LMapCache:
+ def __init__(self):
+ self.cache = {}
+
+ # Lists for search queries
+ self.v_maps = []
+ self.xl_maps = []
+ self.xl_maps_set = set()
+ self.f_maps = []
+ self.lbound_maps = []
+ self.size = 0
+
+ def __getitem__(self, v):
+ try:
+ v = np.ndarray.tolist(v)
+ except TypeError:
+ pass
+ v = tuple(v)
+ try:
+ return self.cache[v]
+ except KeyError:
+ xval = LMap(v)
+ self.cache[v] = xval
+
+ return self.cache[v]
+
+ def add_res(self, v, lres, bounds=None):
+ v = np.ndarray.tolist(v)
+ v = tuple(v)
+ self.cache[v].x_l = lres.x
+ self.cache[v].lres = lres
+ self.cache[v].f_min = lres.fun
+ self.cache[v].lbounds = bounds
+
+ # Update cache size
+ self.size += 1
+
+ # Cache lists for search queries
+ self.v_maps.append(v)
+ self.xl_maps.append(lres.x)
+ self.xl_maps_set.add(tuple(lres.x))
+ self.f_maps.append(lres.fun)
+ self.lbound_maps.append(bounds)
+
+ def sort_cache_result(self):
+ """
+ Sort results and build the global return object
+ """
+ results = {}
+ # Sort results and save
+ self.xl_maps = np.array(self.xl_maps)
+ self.f_maps = np.array(self.f_maps)
+
+ # Sorted indexes in Func_min
+ ind_sorted = np.argsort(self.f_maps)
+
+ # Save ordered list of minima
+ results['xl'] = self.xl_maps[ind_sorted] # Ordered x vals
+ self.f_maps = np.array(self.f_maps)
+ results['funl'] = self.f_maps[ind_sorted]
+ results['funl'] = results['funl'].T
+
+ # Find global of all minimizers
+ results['x'] = self.xl_maps[ind_sorted[0]] # Save global minima
+ results['fun'] = self.f_maps[ind_sorted[0]] # Save global fun value
+
+ self.xl_maps = np.ndarray.tolist(self.xl_maps)
+ self.f_maps = np.ndarray.tolist(self.f_maps)
+ return results
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_complex.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_complex.py
new file mode 100644
index 0000000000000000000000000000000000000000..b73b737aaf3513a637d011a1cbc3ed4a5bb2b212
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_complex.py
@@ -0,0 +1,1225 @@
+"""Base classes for low memory simplicial complex structures."""
+import copy
+import logging
+import itertools
+import decimal
+from functools import cache
+
+import numpy as np
+
+from ._vertex import (VertexCacheField, VertexCacheIndex)
+
+
+class Complex:
+ """
+ Base class for a simplicial complex described as a cache of vertices
+ together with their connections.
+
+ Important methods:
+ Domain triangulation:
+ Complex.triangulate, Complex.split_generation
+ Triangulating arbitrary points (must be traingulable,
+ may exist outside domain):
+ Complex.triangulate(sample_set)
+ Converting another simplicial complex structure data type to the
+ structure used in Complex (ex. OBJ wavefront)
+ Complex.convert(datatype, data)
+
+ Important objects:
+ HC.V: The cache of vertices and their connection
+ HC.H: Storage structure of all vertex groups
+
+ Parameters
+ ----------
+ dim : int
+ Spatial dimensionality of the complex R^dim
+ domain : list of tuples, optional
+ The bounds [x_l, x_u]^dim of the hyperrectangle space
+ ex. The default domain is the hyperrectangle [0, 1]^dim
+ Note: The domain must be convex, non-convex spaces can be cut
+ away from this domain using the non-linear
+ g_cons functions to define any arbitrary domain
+ (these domains may also be disconnected from each other)
+ sfield :
+ A scalar function defined in the associated domain f: R^dim --> R
+ sfield_args : tuple
+ Additional arguments to be passed to `sfield`
+ vfield :
+ A scalar function defined in the associated domain
+ f: R^dim --> R^m
+ (for example a gradient function of the scalar field)
+ vfield_args : tuple
+ Additional arguments to be passed to vfield
+ symmetry : None or list
+ Specify if the objective function contains symmetric variables.
+ The search space (and therefore performance) is decreased by up to
+ O(n!) times in the fully symmetric case.
+
+ E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
+
+ In this equation x_2 and x_3 are symmetric to x_1, while x_5 and
+ x_6 are symmetric to x_4, this can be specified to the solver as:
+
+ symmetry = [0, # Variable 1
+ 0, # symmetric to variable 1
+ 0, # symmetric to variable 1
+ 3, # Variable 4
+ 3, # symmetric to variable 4
+ 3, # symmetric to variable 4
+ ]
+
+ constraints : dict or sequence of dict, optional
+ Constraints definition.
+ Function(s) ``R**n`` in the form::
+
+ g(x) <= 0 applied as g : R^n -> R^m
+ h(x) == 0 applied as h : R^n -> R^p
+
+ Each constraint is defined in a dictionary with fields:
+
+ type : str
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
+ fun : callable
+ The function defining the constraint.
+ jac : callable, optional
+ The Jacobian of `fun` (only for SLSQP).
+ args : sequence, optional
+ Extra arguments to be passed to the function and Jacobian.
+
+ Equality constraint means that the constraint function result is to
+ be zero whereas inequality means that it is to be
+ non-negative.constraints : dict or sequence of dict, optional
+ Constraints definition.
+ Function(s) ``R**n`` in the form::
+
+ g(x) <= 0 applied as g : R^n -> R^m
+ h(x) == 0 applied as h : R^n -> R^p
+
+ Each constraint is defined in a dictionary with fields:
+
+ type : str
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
+ fun : callable
+ The function defining the constraint.
+ jac : callable, optional
+ The Jacobian of `fun` (unused).
+ args : sequence, optional
+ Extra arguments to be passed to the function and Jacobian.
+
+ Equality constraint means that the constraint function result is to
+ be zero whereas inequality means that it is to be non-negative.
+
+ workers : int optional
+ Uses `multiprocessing.Pool `) to compute the field
+ functions in parallel.
+ """
+ def __init__(self, dim, domain=None, sfield=None, sfield_args=(),
+ symmetry=None, constraints=None, workers=1):
+ self.dim = dim
+
+ # Domains
+ self.domain = domain
+ if domain is None:
+ self.bounds = [(0.0, 1.0), ] * dim
+ else:
+ self.bounds = domain
+ self.symmetry = symmetry
+ # here in init to avoid if checks
+
+ # Field functions
+ self.sfield = sfield
+ self.sfield_args = sfield_args
+
+ # Process constraints
+ # Constraints
+ # Process constraint dict sequence:
+ if constraints is not None:
+ self.min_cons = constraints
+ self.g_cons = []
+ self.g_args = []
+ if not isinstance(constraints, tuple | list):
+ constraints = (constraints,)
+
+ for cons in constraints:
+ if cons['type'] in ('ineq'):
+ self.g_cons.append(cons['fun'])
+ try:
+ self.g_args.append(cons['args'])
+ except KeyError:
+ self.g_args.append(())
+ self.g_cons = tuple(self.g_cons)
+ self.g_args = tuple(self.g_args)
+ else:
+ self.g_cons = None
+ self.g_args = None
+
+ # Homology properties
+ self.gen = 0
+ self.perm_cycle = 0
+
+ # Every cell is stored in a list of its generation,
+ # ex. the initial cell is stored in self.H[0]
+ # 1st get new cells are stored in self.H[1] etc.
+ # When a cell is sub-generated it is removed from this list
+
+ self.H = [] # Storage structure of vertex groups
+
+ # Cache of all vertices
+ if (sfield is not None) or (self.g_cons is not None):
+ # Initiate a vertex cache and an associated field cache, note that
+ # the field case is always initiated inside the vertex cache if an
+ # associated field scalar field is defined:
+ if sfield is not None:
+ self.V = VertexCacheField(field=sfield, field_args=sfield_args,
+ g_cons=self.g_cons,
+ g_cons_args=self.g_args,
+ workers=workers)
+ elif self.g_cons is not None:
+ self.V = VertexCacheField(field=sfield, field_args=sfield_args,
+ g_cons=self.g_cons,
+ g_cons_args=self.g_args,
+ workers=workers)
+ else:
+ self.V = VertexCacheIndex()
+
+ self.V_non_symm = [] # List of non-symmetric vertices
+ self.split_edge = cache(self._split_edge)
+
+ def __call__(self):
+ return self.H
+
+ # %% Triangulation methods
+ def cyclic_product(self, bounds, origin, supremum, centroid=True):
+ """Generate initial triangulation using cyclic product"""
+ # Define current hyperrectangle
+ vot = tuple(origin)
+ vut = tuple(supremum) # Hyperrectangle supremum
+ self.V[vot]
+ vo = self.V[vot]
+ yield vo.x
+ self.V[vut].connect(self.V[vot])
+ yield vut
+ # Cyclic group approach with second x_l --- x_u operation.
+
+ # These containers store the "lower" and "upper" vertices
+ # corresponding to the origin or supremum of every C2 group.
+ # It has the structure of `dim` times embedded lists each containing
+ # these vertices as the entire complex grows. Bounds[0] has to be done
+ # outside the loops before we have symmetric containers.
+ # NOTE: This means that bounds[0][1] must always exist
+ C0x = [[self.V[vot]]]
+ a_vo = copy.copy(list(origin))
+ a_vo[0] = vut[0] # Update aN Origin
+ a_vo = self.V[tuple(a_vo)]
+ # self.V[vot].connect(self.V[tuple(a_vo)])
+ self.V[vot].connect(a_vo)
+ yield a_vo.x
+ C1x = [[a_vo]]
+ # C1x = [[self.V[tuple(a_vo)]]]
+ ab_C = [] # Container for a + b operations
+
+ # Loop over remaining bounds
+ for i, x in enumerate(bounds[1:]):
+ # Update lower and upper containers
+ C0x.append([])
+ C1x.append([])
+ # try to access a second bound (if not, C1 is symmetric)
+ try:
+ # Early try so that we don't have to copy the cache before
+ # moving on to next C1/C2: Try to add the operation of a new
+ # C2 product by accessing the upper bound
+ x[1]
+ # Copy lists for iteration
+ cC0x = [x[:] for x in C0x[:i + 1]]
+ cC1x = [x[:] for x in C1x[:i + 1]]
+ for j, (VL, VU) in enumerate(zip(cC0x, cC1x)):
+ for k, (vl, vu) in enumerate(zip(VL, VU)):
+ # Build aN vertices for each lower-upper pair in N:
+ a_vl = list(vl.x)
+ a_vu = list(vu.x)
+ a_vl[i + 1] = vut[i + 1]
+ a_vu[i + 1] = vut[i + 1]
+ a_vl = self.V[tuple(a_vl)]
+
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ vl.connect(a_vl)
+
+ yield a_vl.x
+
+ a_vu = self.V[tuple(a_vu)]
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ vu.connect(a_vu)
+
+ # Connect new vertex pair in aN:
+ a_vl.connect(a_vu)
+
+ # Connect lower pair to upper (triangulation
+ # operation of a + b (two arbitrary operations):
+ vl.connect(a_vu)
+ ab_C.append((vl, a_vu))
+
+ # Update the containers
+ C0x[i + 1].append(vl)
+ C0x[i + 1].append(vu)
+ C1x[i + 1].append(a_vl)
+ C1x[i + 1].append(a_vu)
+
+ # Update old containers
+ C0x[j].append(a_vl)
+ C1x[j].append(a_vu)
+
+ # Yield new points
+ yield a_vu.x
+
+ # Try to connect aN lower source of previous a + b
+ # operation with a aN vertex
+ ab_Cc = copy.copy(ab_C)
+
+ for vp in ab_Cc:
+ b_v = list(vp[0].x)
+ ab_v = list(vp[1].x)
+ b_v[i + 1] = vut[i + 1]
+ ab_v[i + 1] = vut[i + 1]
+ b_v = self.V[tuple(b_v)] # b + vl
+ ab_v = self.V[tuple(ab_v)] # b + a_vl
+ # Note o---o is already connected
+ vp[0].connect(ab_v) # o-s
+ b_v.connect(ab_v) # s-s
+
+ # Add new list of cross pairs
+ ab_C.append((vp[0], ab_v))
+ ab_C.append((b_v, ab_v))
+
+ except IndexError:
+ cC0x = C0x[i]
+ cC1x = C1x[i]
+ VL, VU = cC0x, cC1x
+ for k, (vl, vu) in enumerate(zip(VL, VU)):
+ # Build aN vertices for each lower-upper pair in N:
+ a_vu = list(vu.x)
+ a_vu[i + 1] = vut[i + 1]
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ a_vu = self.V[tuple(a_vu)]
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ vu.connect(a_vu)
+ # Connect new vertex pair in aN:
+ # a_vl.connect(a_vu)
+ # Connect lower pair to upper (triangulation
+ # operation of a + b (two arbitrary operations):
+ vl.connect(a_vu)
+ ab_C.append((vl, a_vu))
+ C0x[i + 1].append(vu)
+ C1x[i + 1].append(a_vu)
+ # Yield new points
+ a_vu.connect(self.V[vut])
+ yield a_vu.x
+ ab_Cc = copy.copy(ab_C)
+ for vp in ab_Cc:
+ if vp[1].x[i] == vut[i]:
+ ab_v = list(vp[1].x)
+ ab_v[i + 1] = vut[i + 1]
+ ab_v = self.V[tuple(ab_v)] # b + a_vl
+ # Note o---o is already connected
+ vp[0].connect(ab_v) # o-s
+
+ # Add new list of cross pairs
+ ab_C.append((vp[0], ab_v))
+
+ # Clean class trash
+ try:
+ del C0x
+ del cC0x
+ del C1x
+ del cC1x
+ del ab_C
+ del ab_Cc
+ except UnboundLocalError:
+ pass
+
+ # Extra yield to ensure that the triangulation is completed
+ if centroid:
+ vo = self.V[vot]
+ vs = self.V[vut]
+ # Disconnect the origin and supremum
+ vo.disconnect(vs)
+ # Build centroid
+ vc = self.split_edge(vot, vut)
+ for v in vo.nn:
+ v.connect(vc)
+ yield vc.x
+ return vc.x
+ else:
+ yield vut
+ return vut
+
+ def triangulate(self, n=None, symmetry=None, centroid=True,
+ printout=False):
+ """
+ Triangulate the initial domain, if n is not None then a limited number
+ of points will be generated
+
+ Parameters
+ ----------
+ n : int, Number of points to be sampled.
+ symmetry :
+
+ Ex. Dictionary/hashtable
+ f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
+
+ symmetry = symmetry[0]: 0, # Variable 1
+ symmetry[1]: 0, # symmetric to variable 1
+ symmetry[2]: 0, # symmetric to variable 1
+ symmetry[3]: 3, # Variable 4
+ symmetry[4]: 3, # symmetric to variable 4
+ symmetry[5]: 3, # symmetric to variable 4
+ }
+ centroid : bool, if True add a central point to the hypercube
+ printout : bool, if True print out results
+
+ NOTES:
+ ------
+ Rather than using the combinatorial algorithm to connect vertices we
+ make the following observation:
+
+ The bound pairs are similar a C2 cyclic group and the structure is
+ formed using the cartesian product:
+
+ H = C2 x C2 x C2 ... x C2 (dim times)
+
+ So construct any normal subgroup N and consider H/N first, we connect
+ all vertices within N (ex. N is C2 (the first dimension), then we move
+ to a left coset aN (an operation moving around the defined H/N group by
+ for example moving from the lower bound in C2 (dimension 2) to the
+ higher bound in C2. During this operation connection all the vertices.
+ Now repeat the N connections. Note that these elements can be connected
+ in parallel.
+ """
+ # Inherit class arguments
+ if symmetry is None:
+ symmetry = self.symmetry
+ # Build origin and supremum vectors
+ origin = [i[0] for i in self.bounds]
+ self.origin = origin
+ supremum = [i[1] for i in self.bounds]
+
+ self.supremum = supremum
+
+ if symmetry is None:
+ cbounds = self.bounds
+ else:
+ cbounds = copy.copy(self.bounds)
+ for i, j in enumerate(symmetry):
+ if i is not j:
+ # pop second entry on second symmetry vars
+ cbounds[i] = [self.bounds[symmetry[i]][0]]
+ # Sole (first) entry is the sup value and there is no
+ # origin:
+ cbounds[i] = [self.bounds[symmetry[i]][1]]
+ if (self.bounds[symmetry[i]] is not
+ self.bounds[symmetry[j]]):
+ logging.warning(f"Variable {i} was specified as "
+ f"symmetric to variable {j}, however"
+ f", the bounds {i} ="
+ f" {self.bounds[symmetry[i]]} and {j}"
+ f" ="
+ f" {self.bounds[symmetry[j]]} do not "
+ f"match, the mismatch was ignored in "
+ f"the initial triangulation.")
+ cbounds[i] = self.bounds[symmetry[j]]
+
+ if n is None:
+ # Build generator
+ self.cp = self.cyclic_product(cbounds, origin, supremum, centroid)
+ for i in self.cp:
+ i
+
+ try:
+ self.triangulated_vectors.append((tuple(self.origin),
+ tuple(self.supremum)))
+ except (AttributeError, KeyError):
+ self.triangulated_vectors = [(tuple(self.origin),
+ tuple(self.supremum))]
+
+ else:
+ # Check if generator already exists
+ try:
+ self.cp
+ except (AttributeError, KeyError):
+ self.cp = self.cyclic_product(cbounds, origin, supremum,
+ centroid)
+
+ try:
+ while len(self.V.cache) < n:
+ next(self.cp)
+ except StopIteration:
+ try:
+ self.triangulated_vectors.append((tuple(self.origin),
+ tuple(self.supremum)))
+ except (AttributeError, KeyError):
+ self.triangulated_vectors = [(tuple(self.origin),
+ tuple(self.supremum))]
+
+ if printout:
+ # for v in self.C0():
+ # v.print_out()
+ for v in self.V.cache:
+ self.V[v].print_out()
+
+ return
+
+ def refine(self, n=1):
+ if n is None:
+ try:
+ self.triangulated_vectors
+ self.refine_all()
+ return
+ except AttributeError as ae:
+ if str(ae) == "'Complex' object has no attribute " \
+ "'triangulated_vectors'":
+ self.triangulate(symmetry=self.symmetry)
+ return
+ else:
+ raise
+
+ nt = len(self.V.cache) + n # Target number of total vertices
+ # In the outer while loop we iterate until we have added an extra `n`
+ # vertices to the complex:
+ while len(self.V.cache) < nt: # while loop 1
+ try: # try 1
+ # Try to access triangulated_vectors, this should only be
+ # defined if an initial triangulation has already been
+ # performed:
+ self.triangulated_vectors
+ # Try a usual iteration of the current generator, if it
+ # does not exist or is exhausted then produce a new generator
+ try: # try 2
+ next(self.rls)
+ except (AttributeError, StopIteration, KeyError):
+ vp = self.triangulated_vectors[0]
+ self.rls = self.refine_local_space(*vp, bounds=self.bounds)
+ next(self.rls)
+
+ except (AttributeError, KeyError):
+ # If an initial triangulation has not been completed, then
+ # we start/continue the initial triangulation targeting `nt`
+ # vertices, if nt is greater than the initial number of
+ # vertices then the `refine` routine will move back to try 1.
+ self.triangulate(nt, self.symmetry)
+ return
+
+ def refine_all(self, centroids=True):
+ """Refine the entire domain of the current complex."""
+ try:
+ self.triangulated_vectors
+ tvs = copy.copy(self.triangulated_vectors)
+ for i, vp in enumerate(tvs):
+ self.rls = self.refine_local_space(*vp, bounds=self.bounds)
+ for i in self.rls:
+ i
+ except AttributeError as ae:
+ if str(ae) == "'Complex' object has no attribute " \
+ "'triangulated_vectors'":
+ self.triangulate(symmetry=self.symmetry, centroid=centroids)
+ else:
+ raise
+
+ # This adds a centroid to every new sub-domain generated and defined
+ # by self.triangulated_vectors, in addition the vertices ! to complete
+ # the triangulation
+ return
+
+ def refine_local_space(self, origin, supremum, bounds, centroid=1):
+ # Copy for later removal
+ origin_c = copy.copy(origin)
+ supremum_c = copy.copy(supremum)
+
+ # Initiate local variables redefined in later inner `for` loop:
+ vl, vu, a_vu = None, None, None
+
+ # Change the vector orientation so that it is only increasing
+ s_ov = list(origin)
+ s_origin = list(origin)
+ s_sv = list(supremum)
+ s_supremum = list(supremum)
+ for i, vi in enumerate(s_origin):
+ if s_ov[i] > s_sv[i]:
+ s_origin[i] = s_sv[i]
+ s_supremum[i] = s_ov[i]
+
+ vot = tuple(s_origin)
+ vut = tuple(s_supremum) # Hyperrectangle supremum
+
+ vo = self.V[vot] # initiate if doesn't exist yet
+ vs = self.V[vut]
+ # Start by finding the old centroid of the new space:
+ vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg
+
+ # Find set of extreme vertices in current local space
+ sup_set = copy.copy(vco.nn)
+ # Cyclic group approach with second x_l --- x_u operation.
+
+ # These containers store the "lower" and "upper" vertices
+ # corresponding to the origin or supremum of every C2 group.
+ # It has the structure of `dim` times embedded lists each containing
+ # these vertices as the entire complex grows. Bounds[0] has to be done
+ # outside the loops before we have symmetric containers.
+ # NOTE: This means that bounds[0][1] must always exist
+
+ a_vl = copy.copy(list(vot))
+ a_vl[0] = vut[0] # Update aN Origin
+ if tuple(a_vl) not in self.V.cache:
+ vo = self.V[vot] # initiate if doesn't exist yet
+ vs = self.V[vut]
+ # Start by finding the old centroid of the new space:
+ vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg
+
+ # Find set of extreme vertices in current local space
+ sup_set = copy.copy(vco.nn)
+ a_vl = copy.copy(list(vot))
+ a_vl[0] = vut[0] # Update aN Origin
+ a_vl = self.V[tuple(a_vl)]
+ else:
+ a_vl = self.V[tuple(a_vl)]
+
+ c_v = self.split_edge(vo.x, a_vl.x)
+ c_v.connect(vco)
+ yield c_v.x
+ Cox = [[vo]]
+ Ccx = [[c_v]]
+ Cux = [[a_vl]]
+ ab_C = [] # Container for a + b operations
+ s_ab_C = [] # Container for symmetric a + b operations
+
+ # Loop over remaining bounds
+ for i, x in enumerate(bounds[1:]):
+ # Update lower and upper containers
+ Cox.append([])
+ Ccx.append([])
+ Cux.append([])
+ # try to access a second bound (if not, C1 is symmetric)
+ try:
+ t_a_vl = list(vot)
+ t_a_vl[i + 1] = vut[i + 1]
+
+ # New: lists are used anyway, so copy all
+ # %%
+ # Copy lists for iteration
+ cCox = [x[:] for x in Cox[:i + 1]]
+ cCcx = [x[:] for x in Ccx[:i + 1]]
+ cCux = [x[:] for x in Cux[:i + 1]]
+ # Try to connect aN lower source of previous a + b
+ # operation with a aN vertex
+ ab_Cc = copy.copy(ab_C) # NOTE: We append ab_C in the
+ # (VL, VC, VU) for-loop, but we use the copy of the list in the
+ # ab_Cc for-loop.
+ s_ab_Cc = copy.copy(s_ab_C)
+
+ # Early try so that we don't have to copy the cache before
+ # moving on to next C1/C2: Try to add the operation of a new
+ # C2 product by accessing the upper bound
+ if tuple(t_a_vl) not in self.V.cache:
+ # Raise error to continue symmetric refine
+ raise IndexError
+ t_a_vu = list(vut)
+ t_a_vu[i + 1] = vut[i + 1]
+ if tuple(t_a_vu) not in self.V.cache:
+ # Raise error to continue symmetric refine:
+ raise IndexError
+
+ for vectors in s_ab_Cc:
+ # s_ab_C.append([c_vc, vl, vu, a_vu])
+ bc_vc = list(vectors[0].x)
+ b_vl = list(vectors[1].x)
+ b_vu = list(vectors[2].x)
+ ba_vu = list(vectors[3].x)
+
+ bc_vc[i + 1] = vut[i + 1]
+ b_vl[i + 1] = vut[i + 1]
+ b_vu[i + 1] = vut[i + 1]
+ ba_vu[i + 1] = vut[i + 1]
+
+ bc_vc = self.V[tuple(bc_vc)]
+ bc_vc.connect(vco) # NOTE: Unneeded?
+ yield bc_vc
+
+ # Split to centre, call this centre group "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(bc_vc)
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
+ yield d_bc_vc.x
+ b_vl = self.V[tuple(b_vl)]
+ bc_vc.connect(b_vl) # Connect aN cross pairs
+ d_bc_vc.connect(b_vl) # Connect all to centroid
+
+ yield b_vl
+ b_vu = self.V[tuple(b_vu)]
+ bc_vc.connect(b_vu) # Connect aN cross pairs
+ d_bc_vc.connect(b_vu) # Connect all to centroid
+
+ b_vl_c = self.split_edge(b_vu.x, b_vl.x)
+ bc_vc.connect(b_vl_c)
+
+ yield b_vu
+ ba_vu = self.V[tuple(ba_vu)]
+ bc_vc.connect(ba_vu) # Connect aN cross pairs
+ d_bc_vc.connect(ba_vu) # Connect all to centroid
+
+ # Split the a + b edge of the initial triangulation:
+ os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s
+ ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s
+ b_vu_c = self.split_edge(b_vu.x, ba_vu.x)
+ bc_vc.connect(b_vu_c)
+ yield os_v.x # often equal to vco, but not always
+ yield ss_v.x # often equal to bc_vu, but not always
+ yield ba_vu
+ # Split remaining to centre, call this centre group
+ # "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ yield d_bc_vc.x
+ d_b_vl = self.split_edge(vectors[1].x, b_vl.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vl) # Connect dN cross pairs
+ yield d_b_vl.x
+ d_b_vu = self.split_edge(vectors[2].x, b_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vu) # Connect dN cross pairs
+ yield d_b_vu.x
+ d_ba_vu = self.split_edge(vectors[3].x, ba_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs
+ yield d_ba_vu
+
+ # comb = [c_vc, vl, vu, a_vl, a_vu,
+ # bc_vc, b_vl, b_vu, ba_vl, ba_vu]
+ comb = [vl, vu, a_vu,
+ b_vl, b_vu, ba_vu]
+ comb_iter = itertools.combinations(comb, 2)
+ for vecs in comb_iter:
+ self.split_edge(vecs[0].x, vecs[1].x)
+ # Add new list of cross pairs
+ ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu))
+ ab_C.append((d_bc_vc, vl, b_vl, a_vu, ba_vu)) # = prev
+
+ for vectors in ab_Cc:
+ bc_vc = list(vectors[0].x)
+ b_vl = list(vectors[1].x)
+ b_vu = list(vectors[2].x)
+ ba_vl = list(vectors[3].x)
+ ba_vu = list(vectors[4].x)
+ bc_vc[i + 1] = vut[i + 1]
+ b_vl[i + 1] = vut[i + 1]
+ b_vu[i + 1] = vut[i + 1]
+ ba_vl[i + 1] = vut[i + 1]
+ ba_vu[i + 1] = vut[i + 1]
+ bc_vc = self.V[tuple(bc_vc)]
+ bc_vc.connect(vco) # NOTE: Unneeded?
+ yield bc_vc
+
+ # Split to centre, call this centre group "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(bc_vc)
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
+ d_bc_vc.connect(vectors[4]) # Connect all to centroid
+ yield d_bc_vc.x
+ b_vl = self.V[tuple(b_vl)]
+ bc_vc.connect(b_vl) # Connect aN cross pairs
+ d_bc_vc.connect(b_vl) # Connect all to centroid
+ yield b_vl
+ b_vu = self.V[tuple(b_vu)]
+ bc_vc.connect(b_vu) # Connect aN cross pairs
+ d_bc_vc.connect(b_vu) # Connect all to centroid
+ yield b_vu
+ ba_vl = self.V[tuple(ba_vl)]
+ bc_vc.connect(ba_vl) # Connect aN cross pairs
+ d_bc_vc.connect(ba_vl) # Connect all to centroid
+ self.split_edge(b_vu.x, ba_vl.x)
+ yield ba_vl
+ ba_vu = self.V[tuple(ba_vu)]
+ bc_vc.connect(ba_vu) # Connect aN cross pairs
+ d_bc_vc.connect(ba_vu) # Connect all to centroid
+ # Split the a + b edge of the initial triangulation:
+ os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s
+ ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s
+ yield os_v.x # often equal to vco, but not always
+ yield ss_v.x # often equal to bc_vu, but not always
+ yield ba_vu
+ # Split remaining to centre, call this centre group
+ # "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ yield d_bc_vc.x
+ d_b_vl = self.split_edge(vectors[1].x, b_vl.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vl) # Connect dN cross pairs
+ yield d_b_vl.x
+ d_b_vu = self.split_edge(vectors[2].x, b_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vu) # Connect dN cross pairs
+ yield d_b_vu.x
+ d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_ba_vl) # Connect dN cross pairs
+ yield d_ba_vl
+ d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs
+ yield d_ba_vu
+ c_vc, vl, vu, a_vl, a_vu = vectors
+
+ comb = [vl, vu, a_vl, a_vu,
+ b_vl, b_vu, ba_vl, ba_vu]
+ comb_iter = itertools.combinations(comb, 2)
+ for vecs in comb_iter:
+ self.split_edge(vecs[0].x, vecs[1].x)
+
+ # Add new list of cross pairs
+ ab_C.append((bc_vc, b_vl, b_vu, ba_vl, ba_vu))
+ ab_C.append((d_bc_vc, d_b_vl, d_b_vu, d_ba_vl, d_ba_vu))
+ ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu))
+ ab_C.append((d_bc_vc, vu, b_vu, a_vl, ba_vl))
+
+ for j, (VL, VC, VU) in enumerate(zip(cCox, cCcx, cCux)):
+ for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)):
+ # Build aN vertices for each lower-upper C3 group in N:
+ a_vl = list(vl.x)
+ a_vu = list(vu.x)
+ a_vl[i + 1] = vut[i + 1]
+ a_vu[i + 1] = vut[i + 1]
+ a_vl = self.V[tuple(a_vl)]
+ a_vu = self.V[tuple(a_vu)]
+ # Note, build (a + vc) later for consistent yields
+ # Split the a + b edge of the initial triangulation:
+ c_vc = self.split_edge(vl.x, a_vu.x)
+ self.split_edge(vl.x, vu.x) # Equal to vc
+ # Build cN vertices for each lower-upper C3 group in N:
+ c_vc.connect(vco)
+ c_vc.connect(vc)
+ c_vc.connect(vl) # Connect c + ac operations
+ c_vc.connect(vu) # Connect c + ac operations
+ c_vc.connect(a_vl) # Connect c + ac operations
+ c_vc.connect(a_vu) # Connect c + ac operations
+ yield c_vc.x
+ c_vl = self.split_edge(vl.x, a_vl.x)
+ c_vl.connect(vco)
+ c_vc.connect(c_vl) # Connect cN group vertices
+ yield c_vl.x
+ # yield at end of loop:
+ c_vu = self.split_edge(vu.x, a_vu.x)
+ c_vu.connect(vco)
+ # Connect remaining cN group vertices
+ c_vc.connect(c_vu) # Connect cN group vertices
+ yield c_vu.x
+
+ a_vc = self.split_edge(a_vl.x, a_vu.x) # is (a + vc) ?
+ a_vc.connect(vco)
+ a_vc.connect(c_vc)
+
+ # Storage for connecting c + ac operations:
+ ab_C.append((c_vc, vl, vu, a_vl, a_vu))
+
+ # Update the containers
+ Cox[i + 1].append(vl)
+ Cox[i + 1].append(vc)
+ Cox[i + 1].append(vu)
+ Ccx[i + 1].append(c_vl)
+ Ccx[i + 1].append(c_vc)
+ Ccx[i + 1].append(c_vu)
+ Cux[i + 1].append(a_vl)
+ Cux[i + 1].append(a_vc)
+ Cux[i + 1].append(a_vu)
+
+ # Update old containers
+ Cox[j].append(c_vl) # !
+ Cox[j].append(a_vl)
+ Ccx[j].append(c_vc) # !
+ Ccx[j].append(a_vc) # !
+ Cux[j].append(c_vu) # !
+ Cux[j].append(a_vu)
+
+ # Yield new points
+ yield a_vc.x
+
+ except IndexError:
+ for vectors in ab_Cc:
+ ba_vl = list(vectors[3].x)
+ ba_vu = list(vectors[4].x)
+ ba_vl[i + 1] = vut[i + 1]
+ ba_vu[i + 1] = vut[i + 1]
+ ba_vu = self.V[tuple(ba_vu)]
+ yield ba_vu
+ d_bc_vc = self.split_edge(vectors[1].x, ba_vu.x) # o-s
+ yield ba_vu
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
+ d_bc_vc.connect(vectors[4]) # Connect all to centroid
+ yield d_bc_vc.x
+ ba_vl = self.V[tuple(ba_vl)]
+ yield ba_vl
+ d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x)
+ d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x)
+ d_ba_vc = self.split_edge(d_ba_vl.x, d_ba_vu.x)
+ yield d_ba_vl
+ yield d_ba_vu
+ yield d_ba_vc
+ c_vc, vl, vu, a_vl, a_vu = vectors
+ comb = [vl, vu, a_vl, a_vu,
+ ba_vl,
+ ba_vu]
+ comb_iter = itertools.combinations(comb, 2)
+ for vecs in comb_iter:
+ self.split_edge(vecs[0].x, vecs[1].x)
+
+ # Copy lists for iteration
+ cCox = Cox[i]
+ cCcx = Ccx[i]
+ cCux = Cux[i]
+ VL, VC, VU = cCox, cCcx, cCux
+ for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)):
+ # Build aN vertices for each lower-upper pair in N:
+ a_vu = list(vu.x)
+ a_vu[i + 1] = vut[i + 1]
+
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ a_vu = self.V[tuple(a_vu)]
+ yield a_vl.x
+ # Split the a + b edge of the initial triangulation:
+ c_vc = self.split_edge(vl.x, a_vu.x)
+ self.split_edge(vl.x, vu.x) # Equal to vc
+ c_vc.connect(vco)
+ c_vc.connect(vc)
+ c_vc.connect(vl) # Connect c + ac operations
+ c_vc.connect(vu) # Connect c + ac operations
+ c_vc.connect(a_vu) # Connect c + ac operations
+ yield (c_vc.x)
+ c_vu = self.split_edge(vu.x,
+ a_vu.x) # yield at end of loop
+ c_vu.connect(vco)
+ # Connect remaining cN group vertices
+ c_vc.connect(c_vu) # Connect cN group vertices
+ yield (c_vu.x)
+
+ # Update the containers
+ Cox[i + 1].append(vu)
+ Ccx[i + 1].append(c_vu)
+ Cux[i + 1].append(a_vu)
+
+ # Update old containers
+ s_ab_C.append([c_vc, vl, vu, a_vu])
+
+ yield a_vu.x
+
+ # Clean class trash
+ try:
+ del Cox
+ del Ccx
+ del Cux
+ del ab_C
+ del ab_Cc
+ except UnboundLocalError:
+ pass
+
+ try:
+ self.triangulated_vectors.remove((tuple(origin_c),
+ tuple(supremum_c)))
+ except ValueError:
+ # Turn this into a logging warning?
+ pass
+ # Add newly triangulated vectors:
+ for vs in sup_set:
+ self.triangulated_vectors.append((tuple(vco.x), tuple(vs.x)))
+
+ # Extra yield to ensure that the triangulation is completed
+ if centroid:
+ vcn_set = set()
+ c_nn_lists = []
+ for vs in sup_set:
+ # Build centroid
+ c_nn = self.vpool(vco.x, vs.x)
+ try:
+ c_nn.remove(vcn_set)
+ except KeyError:
+ pass
+ c_nn_lists.append(c_nn)
+
+ for c_nn in c_nn_lists:
+ try:
+ c_nn.remove(vcn_set)
+ except KeyError:
+ pass
+
+ for vs, c_nn in zip(sup_set, c_nn_lists):
+ # Build centroid
+ vcn = self.split_edge(vco.x, vs.x)
+ vcn_set.add(vcn)
+ try: # Shouldn't be needed?
+ c_nn.remove(vcn_set)
+ except KeyError:
+ pass
+ for vnn in c_nn:
+ vcn.connect(vnn)
+ yield vcn.x
+ else:
+ pass
+
+ yield vut
+ return
+
+ def refine_star(self, v):
+ """Refine the star domain of a vertex `v`."""
+ # Copy lists before iteration
+ vnn = copy.copy(v.nn)
+ v1nn = []
+ d_v0v1_set = set()
+ for v1 in vnn:
+ v1nn.append(copy.copy(v1.nn))
+
+ for v1, v1nn in zip(vnn, v1nn):
+ vnnu = v1nn.intersection(vnn)
+
+ d_v0v1 = self.split_edge(v.x, v1.x)
+ for o_d_v0v1 in d_v0v1_set:
+ d_v0v1.connect(o_d_v0v1)
+ d_v0v1_set.add(d_v0v1)
+ for v2 in vnnu:
+ d_v1v2 = self.split_edge(v1.x, v2.x)
+ d_v0v1.connect(d_v1v2)
+ return
+
+ def _split_edge(self, v1, v2):
+ v1 = self.V[v1]
+ v2 = self.V[v2]
+ # Destroy original edge, if it exists:
+ v1.disconnect(v2)
+ # Compute vertex on centre of edge:
+ try:
+ vct = (v2.x_a - v1.x_a) / 2.0 + v1.x_a
+ except TypeError: # Allow for decimal operations
+ vct = (v2.x_a - v1.x_a) / decimal.Decimal(2.0) + v1.x_a
+
+ vc = self.V[tuple(vct)]
+ # Connect to original 2 vertices to the new centre vertex
+ vc.connect(v1)
+ vc.connect(v2)
+ return vc
+
+ def vpool(self, origin, supremum):
+ vot = tuple(origin)
+ vst = tuple(supremum)
+ # Initiate vertices in case they don't exist
+ vo = self.V[vot]
+ vs = self.V[vst]
+
+ # Remove origin - supremum disconnect
+
+ # Find the lower/upper bounds of the refinement hyperrectangle
+ bl = list(vot)
+ bu = list(vst)
+ for i, (voi, vsi) in enumerate(zip(vot, vst)):
+ if bl[i] > vsi:
+ bl[i] = vsi
+ if bu[i] < voi:
+ bu[i] = voi
+
+ # NOTE: This is mostly done with sets/lists because we aren't sure
+ # how well the numpy arrays will scale to thousands of
+ # dimensions.
+ vn_pool = set()
+ vn_pool.update(vo.nn)
+ vn_pool.update(vs.nn)
+ cvn_pool = copy.copy(vn_pool)
+ for vn in cvn_pool:
+ for i, xi in enumerate(vn.x):
+ if bl[i] <= xi <= bu[i]:
+ pass
+ else:
+ try:
+ vn_pool.remove(vn)
+ except KeyError:
+ pass # NOTE: Not all neighbours are in initial pool
+ return vn_pool
+
+ def vf_to_vv(self, vertices, simplices):
+ """
+ Convert a vertex-face mesh to a vertex-vertex mesh used by this class
+
+ Parameters
+ ----------
+ vertices : list
+ Vertices
+ simplices : list
+ Simplices
+ """
+ if self.dim > 1:
+ for s in simplices:
+ edges = itertools.combinations(s, self.dim)
+ for e in edges:
+ self.V[tuple(vertices[e[0]])].connect(
+ self.V[tuple(vertices[e[1]])])
+ else:
+ for e in simplices:
+ self.V[tuple(vertices[e[0]])].connect(
+ self.V[tuple(vertices[e[1]])])
+ return
+
+ def connect_vertex_non_symm(self, v_x, near=None):
+ """
+ Adds a vertex at coords v_x to the complex that is not symmetric to the
+ initial triangulation and sub-triangulation.
+
+ If near is specified (for example; a star domain or collections of
+ cells known to contain v) then only those simplices containd in near
+ will be searched, this greatly speeds up the process.
+
+ If near is not specified this method will search the entire simplicial
+ complex structure.
+
+ Parameters
+ ----------
+ v_x : tuple
+ Coordinates of non-symmetric vertex
+ near : set or list
+ List of vertices, these are points near v to check for
+ """
+ if near is None:
+ star = self.V
+ else:
+ star = near
+ # Create the vertex origin
+ if tuple(v_x) in self.V.cache:
+ if self.V[v_x] in self.V_non_symm:
+ pass
+ else:
+ return
+
+ self.V[v_x]
+ found_nn = False
+ S_rows = []
+ for v in star:
+ S_rows.append(v.x)
+
+ S_rows = np.array(S_rows)
+ A = np.array(S_rows) - np.array(v_x)
+ # Iterate through all the possible simplices of S_rows
+ for s_i in itertools.combinations(range(S_rows.shape[0]),
+ r=self.dim + 1):
+ # Check if connected, else s_i is not a simplex
+ valid_simplex = True
+ for i in itertools.combinations(s_i, r=2):
+ # Every combination of vertices must be connected, we check of
+ # the current iteration of all combinations of s_i are
+ # connected we break the loop if it is not.
+ if ((self.V[tuple(S_rows[i[1]])] not in
+ self.V[tuple(S_rows[i[0]])].nn)
+ and (self.V[tuple(S_rows[i[0]])] not in
+ self.V[tuple(S_rows[i[1]])].nn)):
+ valid_simplex = False
+ break
+
+ S = S_rows[tuple([s_i])]
+ if valid_simplex:
+ if self.deg_simplex(S, proj=None):
+ valid_simplex = False
+
+ # If s_i is a valid simplex we can test if v_x is inside si
+ if valid_simplex:
+ # Find the A_j0 value from the precalculated values
+ A_j0 = A[tuple([s_i])]
+ if self.in_simplex(S, v_x, A_j0):
+ found_nn = True
+ # breaks the main for loop, s_i is the target simplex:
+ break
+
+ # Connect the simplex to point
+ if found_nn:
+ for i in s_i:
+ self.V[v_x].connect(self.V[tuple(S_rows[i])])
+ # Attached the simplex to storage for all non-symmetric vertices
+ self.V_non_symm.append(self.V[v_x])
+ # this bool value indicates a successful connection if True:
+ return found_nn
+
+ def in_simplex(self, S, v_x, A_j0=None):
+ """Check if a vector v_x is in simplex `S`.
+
+ Parameters
+ ----------
+ S : array_like
+ Array containing simplex entries of vertices as rows
+ v_x :
+ A candidate vertex
+ A_j0 : array, optional,
+ Allows for A_j0 to be pre-calculated
+
+ Returns
+ -------
+ res : bool
+ True if `v_x` is in `S`
+ """
+ A_11 = np.delete(S, 0, 0) - S[0]
+
+ sign_det_A_11 = np.sign(np.linalg.det(A_11))
+ if sign_det_A_11 == 0:
+ # NOTE: We keep the variable A_11, but we loop through A_jj
+ # ind=
+ # while sign_det_A_11 == 0:
+ # A_11 = np.delete(S, ind, 0) - S[ind]
+ # sign_det_A_11 = np.sign(np.linalg.det(A_11))
+
+ sign_det_A_11 = -1 # TODO: Choose another det of j instead?
+ # TODO: Unlikely to work in many cases
+
+ if A_j0 is None:
+ A_j0 = S - v_x
+
+ for d in range(self.dim + 1):
+ det_A_jj = (-1)**d * sign_det_A_11
+ # TODO: Note that scipy might be faster to add as an optional
+ # dependency
+ sign_det_A_j0 = np.sign(np.linalg.det(np.delete(A_j0, d,
+ 0)))
+ # TODO: Note if sign_det_A_j0 == then the point is coplanar to the
+ # current simplex facet, so perhaps return True and attach?
+ if det_A_jj == sign_det_A_j0:
+ continue
+ else:
+ return False
+
+ return True
+
+ def deg_simplex(self, S, proj=None):
+ """Test a simplex S for degeneracy (linear dependence in R^dim).
+
+ Parameters
+ ----------
+ S : np.array
+ Simplex with rows as vertex vectors
+ proj : array, optional,
+ If the projection S[1:] - S[0] is already
+ computed it can be added as an optional argument.
+ """
+ # Strategy: we test all combination of faces, if any of the
+ # determinants are zero then the vectors lie on the same face and is
+ # therefore linearly dependent in the space of R^dim
+ if proj is None:
+ proj = S[1:] - S[0]
+
+ # TODO: Is checking the projection of one vertex against faces of other
+ # vertices sufficient? Or do we need to check more vertices in
+ # dimensions higher than 2?
+ # TODO: Literature seems to suggest using proj.T, but why is this
+ # needed?
+ if np.linalg.det(proj) == 0.0: # TODO: Replace with tolerance?
+ return True # Simplex is degenerate
+ else:
+ return False # Simplex is not degenerate
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_vertex.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_vertex.py
new file mode 100644
index 0000000000000000000000000000000000000000..e47558ee7b9a181638841c34bb63603b5d37e221
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_vertex.py
@@ -0,0 +1,460 @@
+import collections
+from abc import ABC, abstractmethod
+
+import numpy as np
+
+from scipy._lib._util import MapWrapper
+
+
+class VertexBase(ABC):
+ """
+ Base class for a vertex.
+ """
+ def __init__(self, x, nn=None, index=None):
+ """
+ Initiation of a vertex object.
+
+ Parameters
+ ----------
+ x : tuple or vector
+ The geometric location (domain).
+ nn : list, optional
+ Nearest neighbour list.
+ index : int, optional
+ Index of vertex.
+ """
+ self.x = x
+ self.hash = hash(self.x) # Save precomputed hash
+
+ if nn is not None:
+ self.nn = set(nn) # can use .indexupdate to add a new list
+ else:
+ self.nn = set()
+
+ self.index = index
+
+ def __hash__(self):
+ return self.hash
+
+ def __getattr__(self, item):
+ if item not in ['x_a']:
+ raise AttributeError(f"{type(self)} object has no attribute "
+ f"'{item}'")
+ if item == 'x_a':
+ self.x_a = np.array(self.x)
+ return self.x_a
+
+ @abstractmethod
+ def connect(self, v):
+ raise NotImplementedError("This method is only implemented with an "
+ "associated child of the base class.")
+
+ @abstractmethod
+ def disconnect(self, v):
+ raise NotImplementedError("This method is only implemented with an "
+ "associated child of the base class.")
+
+ def star(self):
+ """Returns the star domain ``st(v)`` of the vertex.
+
+ Parameters
+ ----------
+ v :
+ The vertex ``v`` in ``st(v)``
+
+ Returns
+ -------
+ st : set
+ A set containing all the vertices in ``st(v)``
+ """
+ self.st = self.nn
+ self.st.add(self)
+ return self.st
+
+
+class VertexScalarField(VertexBase):
+ """
+ Add homology properties of a scalar field f: R^n --> R associated with
+ the geometry built from the VertexBase class
+ """
+
+ def __init__(self, x, field=None, nn=None, index=None, field_args=(),
+ g_cons=None, g_cons_args=()):
+ """
+ Parameters
+ ----------
+ x : tuple,
+ vector of vertex coordinates
+ field : callable, optional
+ a scalar field f: R^n --> R associated with the geometry
+ nn : list, optional
+ list of nearest neighbours
+ index : int, optional
+ index of the vertex
+ field_args : tuple, optional
+ additional arguments to be passed to field
+ g_cons : callable, optional
+ constraints on the vertex
+ g_cons_args : tuple, optional
+ additional arguments to be passed to g_cons
+
+ """
+ super().__init__(x, nn=nn, index=index)
+
+ # Note Vertex is only initiated once for all x so only
+ # evaluated once
+ # self.feasible = None
+
+ # self.f is externally defined by the cache to allow parallel
+ # processing
+ # None type that will break arithmetic operations unless defined
+ # self.f = None
+
+ self.check_min = True
+ self.check_max = True
+
+ def connect(self, v):
+ """Connects self to another vertex object v.
+
+ Parameters
+ ----------
+ v : VertexBase or VertexScalarField object
+ """
+ if v is not self and v not in self.nn:
+ self.nn.add(v)
+ v.nn.add(self)
+
+ # Flags for checking homology properties:
+ self.check_min = True
+ self.check_max = True
+ v.check_min = True
+ v.check_max = True
+
+ def disconnect(self, v):
+ if v in self.nn:
+ self.nn.remove(v)
+ v.nn.remove(self)
+
+ # Flags for checking homology properties:
+ self.check_min = True
+ self.check_max = True
+ v.check_min = True
+ v.check_max = True
+
+ def minimiser(self):
+ """Check whether this vertex is strictly less than all its
+ neighbours"""
+ if self.check_min:
+ self._min = all(self.f < v.f for v in self.nn)
+ self.check_min = False
+
+ return self._min
+
+ def maximiser(self):
+ """
+ Check whether this vertex is strictly greater than all its
+ neighbours.
+ """
+ if self.check_max:
+ self._max = all(self.f > v.f for v in self.nn)
+ self.check_max = False
+
+ return self._max
+
+
+class VertexVectorField(VertexBase):
+ """
+ Add homology properties of a scalar field f: R^n --> R^m associated with
+ the geometry built from the VertexBase class.
+ """
+
+ def __init__(self, x, sfield=None, vfield=None, field_args=(),
+ vfield_args=(), g_cons=None,
+ g_cons_args=(), nn=None, index=None):
+ super().__init__(x, nn=nn, index=index)
+
+ raise NotImplementedError("This class is still a work in progress")
+
+
+class VertexCacheBase:
+ """Base class for a vertex cache for a simplicial complex."""
+ def __init__(self):
+
+ self.cache = collections.OrderedDict()
+ self.nfev = 0 # Feasible points
+ self.index = -1
+
+ def __iter__(self):
+ for v in self.cache:
+ yield self.cache[v]
+ return
+
+ def size(self):
+ """Returns the size of the vertex cache."""
+ return self.index + 1
+
+ def print_out(self):
+ headlen = len(f"Vertex cache of size: {len(self.cache)}:")
+ print('=' * headlen)
+ print(f"Vertex cache of size: {len(self.cache)}:")
+ print('=' * headlen)
+ for v in self.cache:
+ self.cache[v].print_out()
+
+
+class VertexCube(VertexBase):
+ """Vertex class to be used for a pure simplicial complex with no associated
+ differential geometry (single level domain that exists in R^n)"""
+ def __init__(self, x, nn=None, index=None):
+ super().__init__(x, nn=nn, index=index)
+
+ def connect(self, v):
+ if v is not self and v not in self.nn:
+ self.nn.add(v)
+ v.nn.add(self)
+
+ def disconnect(self, v):
+ if v in self.nn:
+ self.nn.remove(v)
+ v.nn.remove(self)
+
+
+class VertexCacheIndex(VertexCacheBase):
+ def __init__(self):
+ """
+ Class for a vertex cache for a simplicial complex without an associated
+ field. Useful only for building and visualising a domain complex.
+
+ Parameters
+ ----------
+ """
+ super().__init__()
+ self.Vertex = VertexCube
+
+ def __getitem__(self, x, nn=None):
+ try:
+ return self.cache[x]
+ except KeyError:
+ self.index += 1
+ xval = self.Vertex(x, index=self.index)
+ # logging.info("New generated vertex at x = {}".format(x))
+ # NOTE: Surprisingly high performance increase if logging
+ # is commented out
+ self.cache[x] = xval
+ return self.cache[x]
+
+
+class VertexCacheField(VertexCacheBase):
+ def __init__(self, field=None, field_args=(), g_cons=None, g_cons_args=(),
+ workers=1):
+ """
+ Class for a vertex cache for a simplicial complex with an associated
+ field.
+
+ Parameters
+ ----------
+ field : callable
+ Scalar or vector field callable.
+ field_args : tuple, optional
+ Any additional fixed parameters needed to completely specify the
+ field function
+ g_cons : dict or sequence of dict, optional
+ Constraints definition.
+ Function(s) ``R**n`` in the form::
+ g_cons_args : tuple, optional
+ Any additional fixed parameters needed to completely specify the
+ constraint functions
+ workers : int optional
+ Uses `multiprocessing.Pool `) to compute the field
+ functions in parallel.
+
+ """
+ super().__init__()
+ self.index = -1
+ self.Vertex = VertexScalarField
+ self.field = field
+ self.field_args = field_args
+ self.wfield = FieldWrapper(field, field_args) # if workers is not 1
+
+ self.g_cons = g_cons
+ self.g_cons_args = g_cons_args
+ self.wgcons = ConstraintWrapper(g_cons, g_cons_args)
+ self.gpool = set() # A set of tuples to process for feasibility
+
+ # Field processing objects
+ self.fpool = set() # A set of tuples to process for scalar function
+ self.sfc_lock = False # True if self.fpool is non-Empty
+
+ self.workers = workers
+ self._mapwrapper = MapWrapper(workers)
+
+ if workers == 1:
+ self.process_gpool = self.proc_gpool
+ if g_cons is None:
+ self.process_fpool = self.proc_fpool_nog
+ else:
+ self.process_fpool = self.proc_fpool_g
+ else:
+ self.process_gpool = self.pproc_gpool
+ if g_cons is None:
+ self.process_fpool = self.pproc_fpool_nog
+ else:
+ self.process_fpool = self.pproc_fpool_g
+
+ def __getitem__(self, x, nn=None):
+ try:
+ return self.cache[x]
+ except KeyError:
+ self.index += 1
+ xval = self.Vertex(x, field=self.field, nn=nn, index=self.index,
+ field_args=self.field_args,
+ g_cons=self.g_cons,
+ g_cons_args=self.g_cons_args)
+
+ self.cache[x] = xval # Define in cache
+ self.gpool.add(xval) # Add to pool for processing feasibility
+ self.fpool.add(xval) # Add to pool for processing field values
+ return self.cache[x]
+
+ def __getstate__(self):
+ self_dict = self.__dict__.copy()
+ del self_dict['pool']
+ return self_dict
+
+ def process_pools(self):
+ if self.g_cons is not None:
+ self.process_gpool()
+ self.process_fpool()
+ self.proc_minimisers()
+
+ def feasibility_check(self, v):
+ v.feasible = True
+ for g, args in zip(self.g_cons, self.g_cons_args):
+ # constraint may return more than 1 value.
+ if np.any(g(v.x_a, *args) < 0.0):
+ v.f = np.inf
+ v.feasible = False
+ break
+
+ def compute_sfield(self, v):
+ """Compute the scalar field values of a vertex object `v`.
+
+ Parameters
+ ----------
+ v : VertexBase or VertexScalarField object
+ """
+ try:
+ v.f = self.field(v.x_a, *self.field_args)
+ self.nfev += 1
+ except AttributeError:
+ v.f = np.inf
+ # logging.warning(f"Field function not found at x = {self.x_a}")
+ if np.isnan(v.f):
+ v.f = np.inf
+
+ def proc_gpool(self):
+ """Process all constraints."""
+ if self.g_cons is not None:
+ for v in self.gpool:
+ self.feasibility_check(v)
+ # Clean the pool
+ self.gpool = set()
+
+ def pproc_gpool(self):
+ """Process all constraints in parallel."""
+ gpool_l = []
+ for v in self.gpool:
+ gpool_l.append(v.x_a)
+
+ G = self._mapwrapper(self.wgcons.gcons, gpool_l)
+ for v, g in zip(self.gpool, G):
+ v.feasible = g # set vertex object attribute v.feasible = g (bool)
+
+ def proc_fpool_g(self):
+ """Process all field functions with constraints supplied."""
+ for v in self.fpool:
+ if v.feasible:
+ self.compute_sfield(v)
+ # Clean the pool
+ self.fpool = set()
+
+ def proc_fpool_nog(self):
+ """Process all field functions with no constraints supplied."""
+ for v in self.fpool:
+ self.compute_sfield(v)
+ # Clean the pool
+ self.fpool = set()
+
+ def pproc_fpool_g(self):
+ """
+ Process all field functions with constraints supplied in parallel.
+ """
+ self.wfield.func
+ fpool_l = []
+ for v in self.fpool:
+ if v.feasible:
+ fpool_l.append(v.x_a)
+ else:
+ v.f = np.inf
+ F = self._mapwrapper(self.wfield.func, fpool_l)
+ for va, f in zip(fpool_l, F):
+ vt = tuple(va)
+ self[vt].f = f # set vertex object attribute v.f = f
+ self.nfev += 1
+ # Clean the pool
+ self.fpool = set()
+
+ def pproc_fpool_nog(self):
+ """
+ Process all field functions with no constraints supplied in parallel.
+ """
+ self.wfield.func
+ fpool_l = []
+ for v in self.fpool:
+ fpool_l.append(v.x_a)
+ F = self._mapwrapper(self.wfield.func, fpool_l)
+ for va, f in zip(fpool_l, F):
+ vt = tuple(va)
+ self[vt].f = f # set vertex object attribute v.f = f
+ self.nfev += 1
+ # Clean the pool
+ self.fpool = set()
+
+ def proc_minimisers(self):
+ """Check for minimisers."""
+ for v in self:
+ v.minimiser()
+ v.maximiser()
+
+
+class ConstraintWrapper:
+ """Object to wrap constraints to pass to `multiprocessing.Pool`."""
+ def __init__(self, g_cons, g_cons_args):
+ self.g_cons = g_cons
+ self.g_cons_args = g_cons_args
+
+ def gcons(self, v_x_a):
+ vfeasible = True
+ for g, args in zip(self.g_cons, self.g_cons_args):
+ # constraint may return more than 1 value.
+ if np.any(g(v_x_a, *args) < 0.0):
+ vfeasible = False
+ break
+ return vfeasible
+
+
+class FieldWrapper:
+ """Object to wrap field to pass to `multiprocessing.Pool`."""
+ def __init__(self, field, field_args):
+ self.field = field
+ self.field_args = field_args
+
+ def func(self, v_x_a):
+ try:
+ v_f = self.field(v_x_a, *self.field_args)
+ except Exception:
+ v_f = np.inf
+ if np.isnan(v_f):
+ v_f = np.inf
+
+ return v_f
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_slsqp_py.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_slsqp_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d335830162a9c51d7ce79fb3d48870a6bffdca5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_slsqp_py.py
@@ -0,0 +1,617 @@
+"""
+This module implements the Sequential Least Squares Programming optimization
+algorithm (SLSQP), originally developed by Dieter Kraft.
+See http://www.netlib.org/toms/733
+
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ approx_jacobian
+ fmin_slsqp
+
+"""
+
+__all__ = ['approx_jacobian', 'fmin_slsqp']
+
+import numpy as np
+from ._slsqplib import slsqp
+from scipy.linalg import norm as lanorm
+from scipy.linalg.lapack import HAS_ILP64
+from ._optimize import (OptimizeResult, _check_unknown_options,
+ _prepare_scalar_function, _clip_x_for_func,
+ _check_clip_x, _wrap_callback)
+from ._numdiff import approx_derivative
+from ._constraints import old_bound_to_new, _arr_to_scalar
+from scipy._lib._array_api import array_namespace
+from scipy._external import array_api_extra as xpx
+from scipy._lib._util import _call_callback_maybe_halt
+from numpy.typing import NDArray
+
+__docformat__ = "restructuredtext en"
+
+_epsilon = np.sqrt(np.finfo(np.float64).eps)
+
+
+def approx_jacobian(x, func, epsilon, *args):
+ """
+ Approximate the Jacobian matrix of a callable function.
+
+ Parameters
+ ----------
+ x : array_like
+ The state vector at which to compute the Jacobian matrix.
+ func : callable f(x,*args)
+ The vector-valued function.
+ epsilon : float
+ The perturbation used to determine the partial derivatives.
+ args : sequence
+ Additional arguments passed to func.
+
+ Returns
+ -------
+ An array of dimensions ``(lenf, lenx)`` where ``lenf`` is the length
+ of the outputs of `func`, and ``lenx`` is the number of elements in
+ `x`.
+
+ Notes
+ -----
+ The approximation is done using forward differences.
+
+ """
+ # approx_derivative returns (m, n) == (lenf, lenx)
+ jac = approx_derivative(func, x, method='2-point', abs_step=epsilon,
+ args=args)
+ # if func returns a scalar jac.shape will be (lenx,). Make sure
+ # it's at least a 2D array.
+ return np.atleast_2d(jac)
+
+
+def fmin_slsqp(func, x0, eqcons=(), f_eqcons=None, ieqcons=(), f_ieqcons=None,
+ bounds=(), fprime=None, fprime_eqcons=None,
+ fprime_ieqcons=None, args=(), iter=100, acc=1.0E-6,
+ iprint=1, disp=None, full_output=0, epsilon=_epsilon,
+ callback=None):
+ """
+ Minimize a function using Sequential Least Squares Programming.
+
+ Python interface function for the SLSQP Optimization subroutine
+ originally implemented by Dieter Kraft.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function. Must return a scalar.
+ x0 : 1-D ndarray of float
+ Initial guess for the independent variable(s).
+ eqcons : list, optional
+ A list of functions of length n such that
+ eqcons[j](x,*args) == 0.0 in a successfully optimized
+ problem.
+ f_eqcons : callable f(x,*args), optional
+ Returns a 1-D array in which each element must equal 0.0 in a
+ successfully optimized problem. If f_eqcons is specified,
+ eqcons is ignored.
+ ieqcons : list, optional
+ A list of functions of length n such that
+ ieqcons[j](x,*args) >= 0.0 in a successfully optimized
+ problem.
+ f_ieqcons : callable f(x,*args), optional
+ Returns a 1-D ndarray in which each element must be greater or
+ equal to 0.0 in a successfully optimized problem. If
+ f_ieqcons is specified, ieqcons is ignored.
+ bounds : list, optional
+ A list of tuples specifying the lower and upper bound
+ for each independent variable [(xl0, xu0),(xl1, xu1),...]
+ Infinite values will be interpreted as large floating values.
+ fprime : callable ``f(x,*args)``, optional
+ A function that evaluates the partial derivatives of func.
+ fprime_eqcons : callable ``f(x,*args)``, optional
+ A function of the form ``f(x, *args)`` that returns the m by n
+ array of equality constraint normals. If not provided,
+ the normals will be approximated. The array returned by
+ fprime_eqcons should be sized as ( len(eqcons), len(x0) ).
+ fprime_ieqcons : callable ``f(x,*args)``, optional
+ A function of the form ``f(x, *args)`` that returns the m by n
+ array of inequality constraint normals. If not provided,
+ the normals will be approximated. The array returned by
+ fprime_ieqcons should be sized as ( len(ieqcons), len(x0) ).
+ args : sequence, optional
+ Additional arguments passed to func and fprime.
+ iter : int, optional
+ The maximum number of iterations.
+ acc : float, optional
+ Requested accuracy.
+ iprint : int, optional
+ The verbosity of fmin_slsqp :
+
+ * iprint <= 0 : Silent operation
+ * iprint == 1 : Print summary upon completion (default)
+ * iprint >= 2 : Print status of each iterate and summary
+ disp : int, optional
+ Overrides the iprint interface (preferred).
+ full_output : bool, optional
+ If False, return only the minimizer of func (default).
+ Otherwise, output final objective function and summary
+ information.
+ epsilon : float, optional
+ The step size for finite-difference derivative estimates.
+ callback : callable, optional
+ Called after each iteration, as ``callback(x)``, where ``x`` is the
+ current parameter vector.
+
+ Returns
+ -------
+ out : ndarray of float
+ The final minimizer of func.
+ fx : ndarray of float, if full_output is true
+ The final value of the objective function.
+ its : int, if full_output is true
+ The number of iterations.
+ imode : int, if full_output is true
+ The exit mode from the optimizer (see below).
+ smode : str, if full_output is true
+ Message describing the exit mode from the optimizer.
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'SLSQP' `method` in particular.
+
+ Notes
+ -----
+ Exit modes are defined as follows:
+
+ - ``-1`` : Gradient evaluation required (g & a)
+ - ``0`` : Optimization terminated successfully
+ - ``1`` : Function evaluation required (f & c)
+ - ``2`` : More equality constraints than independent variables
+ - ``3`` : More than 3*n iterations in LSQ subproblem
+ - ``4`` : Inequality constraints incompatible
+ - ``5`` : Singular matrix E in LSQ subproblem
+ - ``6`` : Singular matrix C in LSQ subproblem
+ - ``7`` : Rank-deficient equality constraint subproblem HFTI
+ - ``8`` : Positive directional derivative for linesearch
+ - ``9`` : Iteration limit reached
+
+ Examples
+ --------
+ Examples are given :ref:`in the tutorial `.
+
+ """
+ if disp is not None:
+ iprint = disp
+
+ # selects whether to use callback(x) or callback(intermediate_result)
+ callback = _wrap_callback(callback, "slsqp")
+
+ opts = {'maxiter': iter,
+ 'ftol': acc,
+ 'iprint': iprint,
+ 'disp': iprint != 0,
+ 'eps': epsilon,
+ 'callback': callback}
+
+ # Build the constraints as a tuple of dictionaries
+ cons = ()
+ # 1. constraints of the 1st kind (eqcons, ieqcons); no Jacobian; take
+ # the same extra arguments as the objective function.
+ cons += tuple({'type': 'eq', 'fun': c, 'args': args} for c in eqcons)
+ cons += tuple({'type': 'ineq', 'fun': c, 'args': args} for c in ieqcons)
+ # 2. constraints of the 2nd kind (f_eqcons, f_ieqcons) and their Jacobian
+ # (fprime_eqcons, fprime_ieqcons); also take the same extra arguments
+ # as the objective function.
+ if f_eqcons:
+ cons += ({'type': 'eq', 'fun': f_eqcons, 'jac': fprime_eqcons,
+ 'args': args}, )
+ if f_ieqcons:
+ cons += ({'type': 'ineq', 'fun': f_ieqcons, 'jac': fprime_ieqcons,
+ 'args': args}, )
+
+ res = _minimize_slsqp(func, x0, args, jac=fprime, bounds=bounds,
+ constraints=cons, **opts)
+ if full_output:
+ return res['x'], res['fun'], res['nit'], res['status'], res['message']
+ else:
+ return res['x']
+
+
+def _minimize_slsqp(func, x0, args=(), jac=None, bounds=None,
+ constraints=(),
+ maxiter=100, ftol=1.0E-6, iprint=1, disp=False,
+ eps=_epsilon, callback=None, finite_diff_rel_step=None,
+ workers=None, **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using Sequential
+ Least Squares Programming (SLSQP).
+
+ Parameters
+ ----------
+ ftol : float
+ Precision target for the value of f in the stopping criterion. This value
+ controls the final accuracy for checking various optimality conditions;
+ gradient of the lagrangian and absolute sum of the constraint violations
+ should be lower than ``ftol``. Similarly, computed step size and the
+ objective function changes are checked against this value. Default is 1e-6.
+ eps : float
+ Step size used for numerical approximation of the Jacobian.
+ disp : bool
+ Set to True to print convergence messages. If False,
+ `verbosity` is ignored and set to 0.
+ maxiter : int, optional
+ Maximum number of iterations. Default value is 100.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of `jac`. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as an `OptimizeResult` object.
+ In this dict-like object the following fields are of particular importance:
+ ``x`` the solution array, ``success`` a Boolean flag indicating if the
+ optimizer exited successfully, ``message`` which describes the reason for
+ termination, and ``multipliers`` which contains the Karush-Kuhn-Tucker
+ (KKT) multipliers for the QP approximation used in solving the original
+ nonlinear problem. See ``Notes`` below. See also `OptimizeResult` for a
+ description of other attributes.
+
+ Notes
+ -----
+ The KKT multipliers are returned in the ``OptimizeResult.multipliers``
+ attribute as a NumPy array. Denoting the dimension of the equality constraints
+ with ``meq``, and of inequality constraints with ``mineq``, then the returned
+ array slice ``m[:meq]`` contains the multipliers for the equality constraints,
+ and the remaining ``m[meq:meq + mineq]`` contains the multipliers for the
+ inequality constraints. The multipliers corresponding to bound inequalities
+ are not returned. See [1]_ pp. 321 or [2]_ for an explanation of how to interpret
+ these multipliers. The internal QP problem is solved using the methods given
+ in [3]_ Chapter 25.
+
+ Note that if new-style `NonlinearConstraint` or `LinearConstraint` were
+ used, then ``minimize`` converts them first to old-style constraint dicts.
+ It is possible for a single new-style constraint to simultaneously contain
+ both inequality and equality constraints. This means that if there is mixing
+ within a single constraint, then the returned list of multipliers will have
+ a different length than the original new-style constraints.
+
+ References
+ ----------
+ .. [1] Nocedal, J., and S J Wright, 2006, "Numerical Optimization", Springer,
+ New York.
+ .. [2] Kraft, D., "A software package for sequential quadratic programming",
+ 1988, Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace Center, Germany.
+ .. [3] Lawson, C. L., and R. J. Hanson, 1995, "Solving Least Squares Problems",
+ SIAM, Philadelphia, PA.
+
+ """
+ _check_unknown_options(unknown_options)
+ acc = ftol
+ epsilon = eps
+
+ if not disp:
+ iprint = 0
+
+ # Transform x0 into an array.
+ xp = array_namespace(x0)
+ x0 = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ dtype = xp.float64
+ if xp.isdtype(x0.dtype, "real floating"):
+ dtype = x0.dtype
+ x = xp.reshape(xp.astype(x0, dtype), -1)
+
+ # SLSQP is sent 'old-style' bounds, 'new-style' bounds are required by
+ # ScalarFunction
+ if bounds is None or len(bounds) == 0:
+ new_bounds = (-np.inf, np.inf)
+ else:
+ new_bounds = old_bound_to_new(bounds)
+
+ # clip the initial guess to bounds, otherwise ScalarFunction doesn't work
+ x = np.clip(x, new_bounds[0], new_bounds[1])
+
+ # Constraints are triaged per type into a dictionary of tuples
+ if isinstance(constraints, dict):
+ constraints = (constraints, )
+
+ cons = {'eq': (), 'ineq': ()}
+ for ic, con in enumerate(constraints):
+ # check type
+ try:
+ ctype = con['type'].lower()
+ except KeyError as e:
+ raise KeyError(f'Constraint {ic} has no type defined.') from e
+ except TypeError as e:
+ raise TypeError('Constraints must be defined using a '
+ 'dictionary.') from e
+ except AttributeError as e:
+ raise TypeError("Constraint's type must be a string.") from e
+ else:
+ if ctype not in ['eq', 'ineq']:
+ raise ValueError(f"Unknown constraint type '{con['type']}'.")
+
+ # check function
+ if 'fun' not in con:
+ raise ValueError(f'Constraint {ic} has no function defined.')
+
+ # check Jacobian
+ cjac = con.get('jac')
+ if cjac is None:
+ # approximate Jacobian function. The factory function is needed
+ # to keep a reference to `fun`, see gh-4240.
+ def cjac_factory(fun):
+ def cjac(x, *args):
+ x = _check_clip_x(x, new_bounds)
+
+ if jac in ['2-point', '3-point', 'cs']:
+ return approx_derivative(fun, x, method=jac, args=args,
+ rel_step=finite_diff_rel_step,
+ bounds=new_bounds)
+ else:
+ return approx_derivative(fun, x, method='2-point',
+ abs_step=epsilon, args=args,
+ bounds=new_bounds)
+
+ return cjac
+ cjac = cjac_factory(con['fun'])
+
+ # update constraints' dictionary
+ cons[ctype] += ({'fun': con['fun'],
+ 'jac': cjac,
+ 'args': con.get('args', ())}, )
+
+ exit_modes = {-1: "Gradient evaluation required (g & a)",
+ 0: "Optimization terminated successfully",
+ 1: "Function evaluation required (f & c)",
+ 2: "More equality constraints than independent variables",
+ 3: "More than 3*n iterations in LSQ subproblem",
+ 4: "Inequality constraints incompatible",
+ 5: "Singular matrix E in LSQ subproblem",
+ 6: "Singular matrix C in LSQ subproblem",
+ 7: "Rank-deficient equality constraint subproblem HFTI",
+ 8: "Positive directional derivative for linesearch",
+ 9: "Iteration limit reached"}
+
+ # Set the parameters that SLSQP will need
+ # meq, mieq: number of equality and inequality constraints
+ meq = sum(map(len, [np.atleast_1d(c['fun'](x, *c['args']))
+ for c in cons['eq']]))
+ mieq = sum(map(len, [np.atleast_1d(c['fun'](x, *c['args']))
+ for c in cons['ineq']]))
+ # m = The total number of constraints
+ m = meq + mieq
+ # n = The number of independent variables
+ n = len(x)
+
+ # Decompose bounds into xl and xu
+ if bounds is None or len(bounds) == 0:
+ xl = np.empty(n, dtype=float)
+ xu = np.empty(n, dtype=float)
+ xl.fill(np.nan)
+ xu.fill(np.nan)
+ else:
+ bnds = np.array([(_arr_to_scalar(lo), _arr_to_scalar(up))
+ for (lo, up) in bounds], float)
+ if bnds.shape[0] != n:
+ raise IndexError('SLSQP Error: the length of bounds is not '
+ 'compatible with that of x0.')
+
+ with np.errstate(invalid='ignore'):
+ bnderr = bnds[:, 0] > bnds[:, 1]
+
+ if bnderr.any():
+ raise ValueError("SLSQP Error: lb > ub in bounds "
+ f"{', '.join(str(b) for b in bnderr)}.")
+ xl, xu = bnds[:, 0].copy(), bnds[:, 1].copy()
+
+ # Mark infinite bounds with nans; the C code expects this
+ infbnd = ~np.isfinite(bnds)
+ xl[infbnd[:, 0]] = np.nan
+ xu[infbnd[:, 1]] = np.nan
+
+ # ScalarFunction provides function and gradient evaluation
+ sf = _prepare_scalar_function(func, x, jac=jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ bounds=new_bounds, workers=workers)
+ # gh11403 SLSQP sometimes exceeds bounds by 1 or 2 ULP, make sure this
+ # doesn't get sent to the func/grad evaluator.
+ wrapped_fun = _clip_x_for_func(sf.fun, new_bounds)
+ wrapped_grad = _clip_x_for_func(sf.grad, new_bounds)
+
+ # Initialize internal SLSQP state variables dictionary
+ # This dictionary is passed to the SLSQP matching the C struct defined as
+ #
+ # struct SLSQP_static_vars {
+ # double acc, alpha, f0, gs, h1, h2, h3, h4, t, t0, tol;
+ # int exact, inconsistent, reset, iter, itermax, line, mode, meq;
+ # };
+ #
+ # exact : a dummy variable and should be kept 0 since the underlying code
+ # always uses an inexact search.
+ # inconsistent: a boolean set to 1 if the linearized QP is not well-defined
+ # while the original nonlinear problem is still solvable. Then
+ # the problem is augmented with a regularizing dummy variable.
+ # reset: holds the count of resetting bfgs to identity matrix.
+ # iter : the current and itermax is the maximum number of iterations.
+ # line : the current line search iteration.
+ # mode : the exit mode of the solver.
+ # alpha, f0, gs, h1, h2, h3, h4, t, t0 : internal variables used by the solver.
+ #
+ # The dict holds the intermediate state of the solver. The keys are the same
+ # as the C struct members and will be modified in-place.
+ state_dict = {
+ "acc": acc,
+ "alpha": 0.0,
+ "f0": 0.0,
+ "gs": 0.0,
+ "h1": 0.0,
+ "h2": 0.0,
+ "h3": 0.0,
+ "h4": 0.0,
+ "t": 0.0,
+ "t0": 0.0,
+ "tol": 10.0*acc,
+ "exact": 0,
+ "inconsistent": 0,
+ "reset": 0,
+ "iter": 0,
+ "itermax": int(maxiter),
+ "line": 0,
+ "m": m,
+ "meq": meq,
+ "mode": 0,
+ "n": n
+ }
+
+ # Print the header if iprint >= 2
+ if iprint >= 2:
+ print(f"{'NIT':>5} {'FC':>5} {'OBJFUN':>16} {'GNORM':>16}")
+
+ # XXX: check problem size too large for LP64?
+
+ # Internal buffer and int array
+ indices = np.zeros(
+ [max(m + 2*n + 2, 1)], dtype=np.int64 if HAS_ILP64 else np.int32
+ )
+
+ # The worst case workspace requirements for the buffer are:
+
+ # n*(n+1)//2 + m + 4*n + 3 # SLSQP
+ # (n+1)*(n+2) + (n+1)*meq + m + (mineq + 2*n + 2)*(n+1) + 3*n + 3 # LSQ
+ # mineq + 2n + 2 + 2*meq + (n+1) + (mineq + 3n + 3)*(n + 1 - meq) # LSEI
+ # (mineq + 2n + 2 + 2)*(n + 2) + mineq + 2n + 2 # LDP
+ # mineq + 2n + 2 # NNLS
+
+ # If we sum all up and simplify by the help of sympy we get the following
+ buffer_size = (
+ n*(n+1)//2 + 3*m*n - (m + 5*n + 7)*meq + 9*m + 8*n*n + 35*n + meq*meq + 28
+ )
+ # If no inequality constraints are given, top up workspace for the missing
+ # terms.
+ if mieq == 0:
+ buffer_size += 2*n*(n + 1)
+ buffer = np.zeros(max(buffer_size, 1), dtype=np.float64)
+
+ # mode is zero on entry, so call objective, constraints and gradients
+ # there should be no func evaluations here because it's cached from
+ # ScalarFunction
+ fx = wrapped_fun(x)
+ g = wrapped_grad(x)
+
+ # Allocate the multiplier array both for constraints and user specified
+ # bounds (extra +2 is for a possible augmented problem).
+ mult = np.zeros([max(1, m + 2*n + 2)], dtype=np.float64)
+
+ # Allocate the constraints and normals once and repopulate as needed
+ C = np.zeros([max(1, m), n], dtype=np.float64, order='F')
+ d = np.zeros([max(1, m)], dtype=np.float64)
+ _eval_con_normals(C, x, cons, m, meq)
+ _eval_constraint(d, x, cons, m, meq)
+
+ iter_prev = 0
+
+ while True:
+ # Call SLSQP
+ slsqp(state_dict, fx, g, C, d, x, mult, xl, xu, buffer, indices)
+
+ if state_dict['mode'] == 1: # objective and constraint evaluation required
+ fx = sf.fun(x)
+ _eval_constraint(d, x, cons, m, meq)
+
+ if state_dict['mode'] == -1: # gradient evaluation required
+ g = sf.grad(x)
+ _eval_con_normals(C, x, cons, m, meq)
+
+ if state_dict['iter'] > iter_prev:
+ # call callback if major iteration has incremented
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=np.copy(x),
+ fun=fx
+ )
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ # Print the status of the current iterate if iprint > 2
+ if iprint >= 2:
+ print(f"{state_dict['iter']:5d} {sf.nfev:5d} "
+ f"{fx:16.6E} {lanorm(g):16.6E}")
+
+ # If exit mode is not -1 or 1, slsqp has completed
+ if abs(state_dict['mode']) != 1:
+ break
+
+ iter_prev = state_dict['iter']
+
+ # Optimization loop complete. Print status if requested
+ if iprint >= 1:
+ print(
+ exit_modes[state_dict['mode']] + f" (Exit mode {state_dict['mode']})"
+ )
+ print(" Current function value:", fx)
+ print(" Iterations:", state_dict['iter'])
+ print(" Function evaluations:", sf.nfev)
+ print(" Gradient evaluations:", sf.ngev)
+
+ return OptimizeResult(
+ x=x, fun=fx, jac=g, nit=state_dict['iter'], nfev=sf.nfev, njev=sf.ngev,
+ status=state_dict['mode'], message=exit_modes[state_dict['mode']],
+ success=(state_dict['mode'] == 0), multipliers=mult[:m]
+ )
+
+# The following functions modify their first input argument in-place.
+def _eval_constraint(d: NDArray, x: NDArray, cons: dict, m: int, meq: int):
+ if m == 0:
+ return
+
+ # The reason why we don't use regular increments with a sane for loop is that
+ # the constraint evaluations do not necessarily return scalars. Their
+ # output length needs to be taken into account while placing them in d.
+
+ if meq > 0:
+ row = 0
+ for con in cons['eq']:
+ temp = np.atleast_1d(con['fun'](x, *con['args'])).ravel()
+ d[row:row + len(temp)] = temp
+ row += len(temp)
+
+ if m > meq:
+ row = meq
+ for con in cons['ineq']:
+ temp = np.atleast_1d(con['fun'](x, *con['args'])).ravel()
+ d[row:row + len(temp)] = temp
+ row += len(temp)
+
+ return
+
+
+def _eval_con_normals(C: NDArray, x: NDArray, cons: dict, m: int, meq: int):
+ if m == 0:
+ return
+
+ if meq > 0:
+ row = 0
+ for con in cons['eq']:
+ temp = np.atleast_2d(con['jac'](x, *con['args']))
+ C[row:row + temp.shape[0], :] = temp
+ row += temp.shape[0]
+
+ if m > meq:
+ row = meq
+ for con in cons['ineq']:
+ temp = np.atleast_2d(con['jac'](x, *con['args']))
+ C[row:row + temp.shape[0], :] = temp
+ row += temp.shape[0]
+
+ return
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..030b06b855183ed1b26a31100f9f4dd1f76d9d1e
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_spectral.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..42f281944fd746d5892c901ef9a852c40e763775
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_spectral.py
@@ -0,0 +1,260 @@
+"""
+Spectral Algorithm for Nonlinear Equations
+"""
+import collections
+
+import numpy as np
+from scipy.optimize import OptimizeResult
+from scipy.optimize._optimize import _check_unknown_options
+from ._linesearch import _nonmonotone_line_search_cruz, _nonmonotone_line_search_cheng
+
+class _NoConvergence(Exception):
+ pass
+
+
+def _root_df_sane(func, x0, args=(), ftol=1e-8, fatol=1e-300, maxfev=1000,
+ fnorm=None, callback=None, disp=False, M=10, eta_strategy=None,
+ sigma_eps=1e-10, sigma_0=1.0, line_search='cruz', **unknown_options):
+ r"""
+ Solve nonlinear equation with the DF-SANE method
+
+ Options
+ -------
+ ftol : float, optional
+ Relative norm tolerance.
+ fatol : float, optional
+ Absolute norm tolerance.
+ Algorithm terminates when ``||func(x)|| < fatol + ftol ||func(x_0)||``.
+ fnorm : callable, optional
+ Norm to use in the convergence check. If None, 2-norm is used.
+ maxfev : int, optional
+ Maximum number of function evaluations.
+ disp : bool, optional
+ Whether to print convergence process to stdout.
+ eta_strategy : callable, optional
+ Choice of the ``eta_k`` parameter, which gives slack for growth
+ of ``||F||**2``. Called as ``eta_k = eta_strategy(k, x, F)`` with
+ `k` the iteration number, `x` the current iterate and `F` the current
+ residual. Should satisfy ``eta_k > 0`` and ``sum(eta, k=0..inf) < inf``.
+ Default: ``||F||**2 / (1 + k)**2``.
+ sigma_eps : float, optional
+ The spectral coefficient is constrained to ``sigma_eps < sigma < 1/sigma_eps``.
+ Default: 1e-10
+ sigma_0 : float, optional
+ Initial spectral coefficient.
+ Default: 1.0
+ M : int, optional
+ Number of iterates to include in the nonmonotonic line search.
+ Default: 10
+ line_search : {'cruz', 'cheng'}
+ Type of line search to employ. 'cruz' is the original one defined in
+ [Martinez & Raydan. Math. Comp. 75, 1429 (2006)], 'cheng' is
+ a modified search defined in [Cheng & Li. IMA J. Numer. Anal. 29, 814 (2009)].
+ Default: 'cruz'
+
+ References
+ ----------
+ .. [1] "Spectral residual method without gradient information for solving
+ large-scale nonlinear systems of equations." W. La Cruz,
+ J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006).
+ .. [2] W. La Cruz, Opt. Meth. Software, 29, 24 (2014).
+ .. [3] W. Cheng, D.-H. Li. IMA J. Numer. Anal. **29**, 814 (2009).
+
+ """
+ _check_unknown_options(unknown_options)
+
+ if line_search not in ('cheng', 'cruz'):
+ raise ValueError(f"Invalid value {line_search!r} for 'line_search'")
+
+ nexp = 2
+
+ if eta_strategy is None:
+ # Different choice from [1], as their eta is not invariant
+ # vs. scaling of F.
+ def eta_strategy(k, x, F):
+ # Obtain squared 2-norm of the initial residual from the outer scope
+ return f_0 / (1 + k)**2
+
+ if fnorm is None:
+ def fnorm(F):
+ # Obtain squared 2-norm of the current residual from the outer scope
+ return f_k**(1.0/nexp)
+
+ def fmerit(F):
+ return np.linalg.norm(F)**nexp
+
+ nfev = [0]
+ f, x_k, x_shape, f_k, F_k, is_complex = _wrap_func(func, x0, fmerit,
+ nfev, maxfev, args)
+
+ k = 0
+ f_0 = f_k
+ sigma_k = sigma_0
+
+ F_0_norm = fnorm(F_k)
+
+ # For the 'cruz' line search
+ prev_fs = collections.deque([f_k], M)
+
+ # For the 'cheng' line search
+ Q = 1.0
+ C = f_0
+
+ converged = False
+ message = "too many function evaluations required"
+
+ while True:
+ F_k_norm = fnorm(F_k)
+
+ if disp:
+ print(f"iter {k}: ||F|| = {F_k_norm:g}, sigma = {sigma_k:g}")
+
+ if callback is not None:
+ callback(x_k, F_k)
+
+ if F_k_norm < ftol * F_0_norm + fatol:
+ # Converged!
+ message = "successful convergence"
+ converged = True
+ break
+
+ # Control spectral parameter, from [2]
+ if abs(sigma_k) > 1/sigma_eps:
+ sigma_k = 1/sigma_eps * np.sign(sigma_k)
+ elif abs(sigma_k) < sigma_eps:
+ sigma_k = sigma_eps
+
+ # Line search direction
+ d = -sigma_k * F_k
+
+ # Nonmonotone line search
+ eta = eta_strategy(k, x_k, F_k)
+ try:
+ if line_search == 'cruz':
+ alpha, xp, fp, Fp = _nonmonotone_line_search_cruz(f, x_k, d, prev_fs,
+ eta=eta)
+ elif line_search == 'cheng':
+ alpha, xp, fp, Fp, C, Q = _nonmonotone_line_search_cheng(f, x_k, d, f_k,
+ C, Q, eta=eta)
+ except _NoConvergence:
+ break
+
+ # Update spectral parameter
+ s_k = xp - x_k
+ y_k = Fp - F_k
+ sigma_k = np.vdot(s_k, s_k) / np.vdot(s_k, y_k)
+
+ # Take step
+ x_k = xp
+ F_k = Fp
+ f_k = fp
+
+ # Store function value
+ if line_search == 'cruz':
+ prev_fs.append(fp)
+
+ k += 1
+
+ x = _wrap_result(x_k, is_complex, shape=x_shape)
+ F = _wrap_result(F_k, is_complex)
+
+ result = OptimizeResult(x=x, success=converged,
+ message=message,
+ fun=F, nfev=nfev[0], nit=k, method="df-sane")
+
+ return result
+
+
+def _wrap_func(func, x0, fmerit, nfev_list, maxfev, args=()):
+ """
+ Wrap a function and an initial value so that (i) complex values
+ are wrapped to reals, and (ii) value for a merit function
+ fmerit(x, f) is computed at the same time, (iii) iteration count
+ is maintained and an exception is raised if it is exceeded.
+
+ Parameters
+ ----------
+ func : callable
+ Function to wrap
+ x0 : ndarray
+ Initial value
+ fmerit : callable
+ Merit function fmerit(f) for computing merit value from residual.
+ nfev_list : list
+ List to store number of evaluations in. Should be [0] in the beginning.
+ maxfev : int
+ Maximum number of evaluations before _NoConvergence is raised.
+ args : tuple
+ Extra arguments to func
+
+ Returns
+ -------
+ wrap_func : callable
+ Wrapped function, to be called as
+ ``F, fp = wrap_func(x0)``
+ x0_wrap : ndarray of float
+ Wrapped initial value; raveled to 1-D and complex
+ values mapped to reals.
+ x0_shape : tuple
+ Shape of the initial value array
+ f : float
+ Merit function at F
+ F : ndarray of float
+ Residual at x0_wrap
+ is_complex : bool
+ Whether complex values were mapped to reals
+
+ """
+ x0 = np.asarray(x0)
+ x0_shape = x0.shape
+ F = np.asarray(func(x0, *args)).ravel()
+ is_complex = np.iscomplexobj(x0) or np.iscomplexobj(F)
+ x0 = x0.ravel()
+
+ nfev_list[0] = 1
+
+ if is_complex:
+ def wrap_func(x):
+ if nfev_list[0] >= maxfev:
+ raise _NoConvergence()
+ nfev_list[0] += 1
+ z = _real2complex(x).reshape(x0_shape)
+ v = np.asarray(func(z, *args)).ravel()
+ F = _complex2real(v)
+ f = fmerit(F)
+ return f, F
+
+ x0 = _complex2real(x0)
+ F = _complex2real(F)
+ else:
+ def wrap_func(x):
+ if nfev_list[0] >= maxfev:
+ raise _NoConvergence()
+ nfev_list[0] += 1
+ x = x.reshape(x0_shape)
+ F = np.asarray(func(x, *args)).ravel()
+ f = fmerit(F)
+ return f, F
+
+ return wrap_func, x0, x0_shape, fmerit(F), F, is_complex
+
+
+def _wrap_result(result, is_complex, shape=None):
+ """
+ Convert from real to complex and reshape result arrays.
+ """
+ if is_complex:
+ z = _real2complex(result)
+ else:
+ z = result
+ if shape is not None:
+ z = z.reshape(shape)
+ return z
+
+
+def _real2complex(x):
+ return np.ascontiguousarray(x, dtype=float).view(np.complex128)
+
+
+def _complex2real(z):
+ return np.ascontiguousarray(z, dtype=complex).view(np.float64)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_tnc.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..bba9de72a6336736cf992ea1c3df868f2941bef5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_tnc.py
@@ -0,0 +1,438 @@
+# TNC Python interface
+# @(#) $Jeannot: tnc.py,v 1.11 2005/01/28 18:27:31 js Exp $
+
+# Copyright (c) 2004-2005, Jean-Sebastien Roy (js@jeannot.org)
+
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"""
+TNC: A Python interface to the TNC non-linear optimizer
+
+TNC is a non-linear optimizer. To use it, you must provide a function to
+minimize. The function must take one argument: the list of coordinates where to
+evaluate the function; and it must return either a tuple, whose first element is the
+value of the function, and whose second argument is the gradient of the function
+(as a list of values); or None, to abort the minimization.
+"""
+
+from scipy.optimize import _moduleTNC as moduleTNC
+from ._optimize import (MemoizeJac, OptimizeResult, _check_unknown_options,
+ _prepare_scalar_function)
+from ._constraints import old_bound_to_new
+from scipy._lib._array_api import array_namespace
+from scipy._external import array_api_extra as xpx
+
+from numpy import inf, array, zeros
+
+__all__ = ['fmin_tnc']
+
+
+MSG_NONE = 0 # No messages
+MSG_ITER = 1 # One line per iteration
+MSG_INFO = 2 # Informational messages
+MSG_VERS = 4 # Version info
+MSG_EXIT = 8 # Exit reasons
+MSG_ALL = MSG_ITER + MSG_INFO + MSG_VERS + MSG_EXIT
+
+MSGS = {
+ MSG_NONE: "No messages",
+ MSG_ITER: "One line per iteration",
+ MSG_INFO: "Informational messages",
+ MSG_VERS: "Version info",
+ MSG_EXIT: "Exit reasons",
+ MSG_ALL: "All messages"
+}
+
+INFEASIBLE = -1 # Infeasible (lower bound > upper bound)
+LOCALMINIMUM = 0 # Local minimum reached (|pg| ~= 0)
+FCONVERGED = 1 # Converged (|f_n-f_(n-1)| ~= 0)
+XCONVERGED = 2 # Converged (|x_n-x_(n-1)| ~= 0)
+MAXFUN = 3 # Max. number of function evaluations reached
+LSFAIL = 4 # Linear search failed
+CONSTANT = 5 # All lower bounds are equal to the upper bounds
+NOPROGRESS = 6 # Unable to progress
+USERABORT = 7 # User requested end of minimization
+
+RCSTRINGS = {
+ INFEASIBLE: "Infeasible (lower bound > upper bound)",
+ LOCALMINIMUM: "Local minimum reached (|pg| ~= 0)",
+ FCONVERGED: "Converged (|f_n-f_(n-1)| ~= 0)",
+ XCONVERGED: "Converged (|x_n-x_(n-1)| ~= 0)",
+ MAXFUN: "Max. number of function evaluations reached",
+ LSFAIL: "Linear search failed",
+ CONSTANT: "All lower bounds are equal to the upper bounds",
+ NOPROGRESS: "Unable to progress",
+ USERABORT: "User requested end of minimization"
+}
+
+# Changes to interface made by Travis Oliphant, Apr. 2004 for inclusion in
+# SciPy
+
+
+def fmin_tnc(func, x0, fprime=None, args=(), approx_grad=0,
+ bounds=None, epsilon=1e-8, scale=None, offset=None,
+ messages=MSG_ALL, maxCGit=-1, maxfun=None, eta=-1,
+ stepmx=0, accuracy=0, fmin=0, ftol=-1, xtol=-1, pgtol=-1,
+ rescale=-1, disp=None, callback=None):
+ r"""
+ Minimize a function with variables subject to bounds, using
+ gradient information in a truncated Newton algorithm. This
+ method wraps a C implementation of the algorithm.
+
+ Parameters
+ ----------
+ func : callable ``func(x, *args)``
+ Function to minimize. Must do one of:
+
+ 1. Return f and g, where f is the value of the function and g its
+ gradient (a list of floats).
+
+ 2. Return the function value but supply gradient function
+ separately as `fprime`.
+
+ 3. Return the function value and set ``approx_grad=True``.
+
+ If the function returns None, the minimization
+ is aborted.
+ x0 : array_like
+ Initial estimate of minimum.
+ fprime : callable ``fprime(x, *args)``, optional
+ Gradient of `func`. If None, then either `func` must return the
+ function value and the gradient (``f,g = func(x, *args)``)
+ or `approx_grad` must be True.
+ args : tuple, optional
+ Arguments to pass to function.
+ approx_grad : bool, optional
+ If true, approximate the gradient numerically.
+ bounds : list, optional
+ (min, max) pairs for each element in x0, defining the
+ bounds on that parameter. Use None or +/-inf for one of
+ min or max when there is no bound in that direction.
+ epsilon : float, optional
+ Used if approx_grad is True. The stepsize in a finite
+ difference approximation for fprime.
+ scale : array_like, optional
+ Scaling factors to apply to each variable. If None, the
+ factors are up-low for interval bounded variables and
+ 1+|x| for the others. Defaults to None.
+ offset : array_like, optional
+ Value to subtract from each variable. If None, the
+ offsets are (up+low)/2 for interval bounded variables
+ and x for the others.
+ messages : int, optional
+ Bit mask used to select messages display during
+ minimization values defined in the MSGS dict. Defaults to
+ MGS_ALL.
+ disp : int, optional
+ Integer interface to messages. 0 = no message, 5 = all messages
+ maxCGit : int, optional
+ Maximum number of hessian*vector evaluations per main
+ iteration. If maxCGit == 0, the direction chosen is
+ -gradient if maxCGit < 0, maxCGit is set to
+ max(1,min(50,n/2)). Defaults to -1.
+ maxfun : int, optional
+ Maximum number of function evaluation. If None, maxfun is
+ set to max(100, 10*len(x0)). Defaults to None. Note that this function
+ may violate the limit because of evaluating gradients by numerical
+ differentiation.
+ eta : float, optional
+ Severity of the line search. If < 0 or > 1, set to 0.25.
+ Defaults to -1.
+ stepmx : float, optional
+ Maximum step for the line search. May be increased during
+ call. If too small, it will be set to 10.0. Defaults to 0.
+ accuracy : float, optional
+ Relative precision for finite difference calculations. If
+ <= machine_precision, set to sqrt(machine_precision).
+ Defaults to 0.
+ fmin : float, optional
+ Minimum function value estimate. Defaults to 0.
+ ftol : float, optional
+ Precision goal for the value of f in the stopping criterion.
+ If ftol < 0.0, ftol is set to 0.0 defaults to -1.
+ xtol : float, optional
+ Precision goal for the value of x in the stopping
+ criterion (after applying x scaling factors). If xtol <
+ 0.0, xtol is set to sqrt(machine_precision). Defaults to
+ -1.
+ pgtol : float, optional
+ Precision goal for the value of the projected gradient in
+ the stopping criterion (after applying x scaling factors).
+ If pgtol < 0.0, pgtol is set to 1e-2 * sqrt(accuracy).
+ Setting it to 0.0 is not recommended. Defaults to -1.
+ rescale : float, optional
+ Scaling factor (in log10) used to trigger f value
+ rescaling. If 0, rescale at each iteration. If a large
+ value, never rescale. If < 0, rescale is set to 1.3.
+ callback : callable, optional
+ Called after each iteration, as callback(xk), where xk is the
+ current parameter vector.
+
+ Returns
+ -------
+ x : ndarray
+ The solution.
+ nfeval : int
+ The number of function evaluations.
+ rc : int
+ Return code, see below
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'TNC' `method` in particular.
+
+ Notes
+ -----
+ The underlying algorithm is truncated Newton, also called
+ Newton Conjugate-Gradient. This method differs from
+ scipy.optimize.fmin_ncg in that
+
+ 1. it wraps a C implementation of the algorithm
+ 2. it allows each variable to be given an upper and lower bound.
+
+ The algorithm incorporates the bound constraints by determining
+ the descent direction as in an unconstrained truncated Newton,
+ but never taking a step-size large enough to leave the space
+ of feasible x's. The algorithm keeps track of a set of
+ currently active constraints, and ignores them when computing
+ the minimum allowable step size. (The x's associated with the
+ active constraint are kept fixed.) If the maximum allowable
+ step size is zero then a new constraint is added. At the end
+ of each iteration one of the constraints may be deemed no
+ longer active and removed. A constraint is considered
+ no longer active is if it is currently active
+ but the gradient for that variable points inward from the
+ constraint. The specific constraint removed is the one
+ associated with the variable of largest index whose
+ constraint is no longer active.
+
+ Return codes are defined as follows:
+
+ - ``-1`` : Infeasible (lower bound > upper bound)
+ - ``0`` : Local minimum reached (:math:`|pg| \approx 0`)
+ - ``1`` : Converged (:math:`|f_n-f_(n-1)| \approx 0`)
+ - ``2`` : Converged (:math:`|x_n-x_(n-1)| \approx 0`)
+ - ``3`` : Max. number of function evaluations reached
+ - ``4`` : Linear search failed
+ - ``5`` : All lower bounds are equal to the upper bounds
+ - ``6`` : Unable to progress
+ - ``7`` : User requested end of minimization
+
+ References
+ ----------
+ Wright S., Nocedal J. (2006), 'Numerical Optimization'
+
+ Nash S.G. (1984), "Newton-Type Minimization Via the Lanczos Method",
+ SIAM Journal of Numerical Analysis 21, pp. 770-778
+
+ """
+ # handle fprime/approx_grad
+ if approx_grad:
+ fun = func
+ jac = None
+ elif fprime is None:
+ fun = MemoizeJac(func)
+ jac = fun.derivative
+ else:
+ fun = func
+ jac = fprime
+
+ if disp is not None: # disp takes precedence over messages
+ mesg_num = disp
+ else:
+ mesg_num = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS,
+ 4:MSG_EXIT, 5:MSG_ALL}.get(messages, MSG_ALL)
+ # build options
+ opts = {'eps': epsilon,
+ 'scale': scale,
+ 'offset': offset,
+ 'mesg_num': mesg_num,
+ 'maxCGit': maxCGit,
+ 'maxfun': maxfun,
+ 'eta': eta,
+ 'stepmx': stepmx,
+ 'accuracy': accuracy,
+ 'minfev': fmin,
+ 'ftol': ftol,
+ 'xtol': xtol,
+ 'gtol': pgtol,
+ 'rescale': rescale,
+ 'disp': False}
+
+ res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback, **opts)
+
+ return res['x'], res['nfev'], res['status']
+
+
+def _minimize_tnc(fun, x0, args=(), jac=None, bounds=None,
+ eps=1e-8, scale=None, offset=None, mesg_num=None,
+ maxCGit=-1, eta=-1, stepmx=0, accuracy=0,
+ minfev=0, ftol=-1, xtol=-1, gtol=-1, rescale=-1, disp=False,
+ callback=None, finite_diff_rel_step=None, maxfun=None,
+ workers=None,
+ **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using a truncated
+ Newton (TNC) algorithm.
+
+ Options
+ -------
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ scale : list of floats
+ Scaling factors to apply to each variable. If None, the
+ factors are up-low for interval bounded variables and
+ 1+|x] for the others. Defaults to None.
+ offset : float
+ Value to subtract from each variable. If None, the
+ offsets are (up+low)/2 for interval bounded variables
+ and x for the others.
+ disp : bool
+ Set to True to print convergence messages.
+ maxCGit : int
+ Maximum number of hessian*vector evaluations per main
+ iteration. If maxCGit == 0, the direction chosen is
+ -gradient if maxCGit < 0, maxCGit is set to
+ max(1,min(50,n/2)). Defaults to -1.
+ eta : float
+ Severity of the line search. If < 0 or > 1, set to 0.25.
+ Defaults to -1.
+ stepmx : float
+ Maximum step for the line search. May be increased during
+ call. If too small, it will be set to 10.0. Defaults to 0.
+ accuracy : float
+ Relative precision for finite difference calculations. If
+ <= machine_precision, set to sqrt(machine_precision).
+ Defaults to 0.
+ minfev : float
+ Minimum function value estimate. Defaults to 0.
+ ftol : float
+ Precision goal for the value of f in the stopping criterion.
+ If ftol < 0.0, ftol is set to 0.0 defaults to -1.
+ xtol : float
+ Precision goal for the value of x in the stopping
+ criterion (after applying x scaling factors). If xtol <
+ 0.0, xtol is set to sqrt(machine_precision). Defaults to
+ -1.
+ gtol : float
+ Precision goal for the value of the projected gradient in
+ the stopping criterion (after applying x scaling factors).
+ If gtol < 0.0, gtol is set to 1e-2 * sqrt(accuracy).
+ Setting it to 0.0 is not recommended. Defaults to -1.
+ rescale : float
+ Scaling factor (in log10) used to trigger f value
+ rescaling. If 0, rescale at each iteration. If a large
+ value, never rescale. If < 0, rescale is set to 1.3.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ maxfun : int
+ Maximum number of function evaluations. If None, `maxfun` is
+ set to max(100, 10*len(x0)). Defaults to None.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+ """
+ _check_unknown_options(unknown_options)
+ fmin = minfev
+ pgtol = gtol
+
+ xp = array_namespace(x0)
+ x0 = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ dtype = xp.float64
+ if xp.isdtype(x0.dtype, "real floating"):
+ dtype = x0.dtype
+ x0 = xp.reshape(xp.astype(x0, dtype), -1)
+
+ n = len(x0)
+
+ if bounds is None:
+ bounds = [(None,None)] * n
+ if len(bounds) != n:
+ raise ValueError('length of x0 != length of bounds')
+ new_bounds = old_bound_to_new(bounds)
+
+ if mesg_num is not None:
+ messages = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS,
+ 4:MSG_EXIT, 5:MSG_ALL}.get(mesg_num, MSG_ALL)
+ elif disp:
+ messages = MSG_ALL
+ else:
+ messages = MSG_NONE
+
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ bounds=new_bounds, workers=workers)
+ func_and_grad = sf.fun_and_grad
+
+ """
+ low, up : the bounds (lists of floats)
+ if low is None, the lower bounds are removed.
+ if up is None, the upper bounds are removed.
+ low and up defaults to None
+ """
+ low = zeros(n)
+ up = zeros(n)
+ for i in range(n):
+ if bounds[i] is None:
+ l, u = -inf, inf
+ else:
+ l,u = bounds[i]
+ if l is None:
+ low[i] = -inf
+ else:
+ low[i] = l
+ if u is None:
+ up[i] = inf
+ else:
+ up[i] = u
+
+ if scale is None:
+ scale = array([])
+
+ if offset is None:
+ offset = array([])
+
+ if maxfun is None:
+ maxfun = max(100, 10*len(x0))
+
+ rc, nf, nit, x, funv, jacv = moduleTNC.tnc_minimize(
+ func_and_grad, x0, low, up, scale,
+ offset, messages, maxCGit, maxfun,
+ eta, stepmx, accuracy, fmin, ftol,
+ xtol, pgtol, rescale, callback
+ )
+ # the TNC documentation states: "On output, x, f and g may be very
+ # slightly out of sync because of scaling". Therefore re-evaluate
+ # func_and_grad so they are synced.
+ funv, jacv = func_and_grad(x)
+
+ return OptimizeResult(x=x, fun=funv, jac=jacv, nfev=sf.nfev,
+ nit=nit, status=rc, message=RCSTRINGS[rc],
+ success=(-1 < rc < 3))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trlib/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trlib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..537b73b3aeb36df09863a0cd24957e5612deb030
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trlib/__init__.py
@@ -0,0 +1,12 @@
+from ._trlib import TRLIBQuadraticSubproblem
+
+__all__ = ['TRLIBQuadraticSubproblem', 'get_trlib_quadratic_subproblem']
+
+
+def get_trlib_quadratic_subproblem(tol_rel_i=-2.0, tol_rel_b=-3.0, disp=False):
+ def subproblem_factory(x, fun, jac, hess, hessp):
+ return TRLIBQuadraticSubproblem(x, fun, jac, hess, hessp,
+ tol_rel_i=tol_rel_i,
+ tol_rel_b=tol_rel_b,
+ disp=disp)
+ return subproblem_factory
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8e8fc3b1d61270a0c704d48c3e3764e90651aaf5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a2e573ef1df540a59a1edd08ff790ca73e8ce60dd50ec99f53c5d233d3abc853
+size 224849
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9021bfc51c7f06195748a190a997be9a208f7ba
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion.py
@@ -0,0 +1,329 @@
+"""Trust-region optimization."""
+import math
+import warnings
+
+import numpy as np
+import scipy.linalg
+from ._optimize import (_check_unknown_options, _status_message,
+ OptimizeResult, _prepare_scalar_function,
+ _call_callback_maybe_halt)
+from scipy.optimize._hessian_update_strategy import HessianUpdateStrategy
+from scipy.optimize._differentiable_functions import FD_METHODS
+__all__ = []
+
+
+def _wrap_function(function, args):
+ # wraps a minimizer function to count number of evaluations
+ # and to easily provide an args kwd.
+ ncalls = [0]
+ if function is None:
+ return ncalls, None
+
+ def function_wrapper(x, *wrapper_args):
+ ncalls[0] += 1
+ # A copy of x is sent to the user function (gh13740)
+ return function(np.copy(x), *(wrapper_args + args))
+
+ return ncalls, function_wrapper
+
+
+class BaseQuadraticSubproblem:
+ """
+ Base/abstract class defining the quadratic model for trust-region
+ minimization. Child classes must implement the ``solve`` method.
+
+ Values of the objective function, Jacobian and Hessian (if provided) at
+ the current iterate ``x`` are evaluated on demand and then stored as
+ attributes ``fun``, ``jac``, ``hess``.
+ """
+
+ def __init__(self, x, fun, jac, hess=None, hessp=None):
+ self._x = x
+ self._f = None
+ self._g = None
+ self._h = None
+ self._g_mag = None
+ self._cauchy_point = None
+ self._newton_point = None
+ self._fun = fun
+ self._jac = jac
+ self._hess = hess
+ self._hessp = hessp
+
+ def __call__(self, p):
+ return self.fun + np.dot(self.jac, p) + 0.5 * np.dot(p, self.hessp(p))
+
+ @property
+ def fun(self):
+ """Value of objective function at current iteration."""
+ if self._f is None:
+ self._f = self._fun(self._x)
+ return self._f
+
+ @property
+ def jac(self):
+ """Value of Jacobian of objective function at current iteration."""
+ if self._g is None:
+ self._g = self._jac(self._x)
+ return self._g
+
+ @property
+ def hess(self):
+ """Value of Hessian of objective function at current iteration."""
+ if self._h is None:
+ self._h = self._hess(self._x)
+ return self._h
+
+ def hessp(self, p):
+ if self._hessp is not None:
+ return self._hessp(self._x, p)
+ else:
+ return np.dot(self.hess, p)
+
+ @property
+ def jac_mag(self):
+ """Magnitude of jacobian of objective function at current iteration."""
+ if self._g_mag is None:
+ self._g_mag = scipy.linalg.norm(self.jac)
+ return self._g_mag
+
+ def get_boundaries_intersections(self, z, d, trust_radius):
+ """
+ Solve the scalar quadratic equation ``||z + t d|| == trust_radius``.
+ This is like a line-sphere intersection.
+ Return the two values of t, sorted from low to high.
+ """
+ a = np.dot(d, d)
+ b = 2 * np.dot(z, d)
+ c = np.dot(z, z) - trust_radius**2
+ sqrt_discriminant = math.sqrt(b*b - 4*a*c)
+
+ # The following calculation is mathematically
+ # equivalent to:
+ # ta = (-b - sqrt_discriminant) / (2*a)
+ # tb = (-b + sqrt_discriminant) / (2*a)
+ # but produce smaller round off errors.
+ # Look at Matrix Computation p.97
+ # for a better justification.
+ aux = b + math.copysign(sqrt_discriminant, b)
+ ta = -aux / (2*a)
+ tb = -2*c / aux
+ return sorted([ta, tb])
+
+ def solve(self, trust_radius, /):
+ raise NotImplementedError('The solve method should be implemented by '
+ 'the child class')
+
+
+def _minimize_trust_region(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ subproblem=None, initial_trust_radius=1.0,
+ max_trust_radius=1000.0, eta=0.15, gtol=1e-4,
+ maxiter=None, disp=False, return_all=False,
+ callback=None, inexact=True, workers=None,
+ subproblem_maxiter=None, **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using a
+ trust-region algorithm.
+
+ Options for the trust-region algorithm are:
+ initial_trust_radius : float
+ Initial trust radius.
+ max_trust_radius : float
+ Never propose steps that are longer than this value.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than `gtol`
+ before successful termination.
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ If True, print convergence message.
+ inexact : bool
+ Accuracy to solve subproblems. If True requires less nonlinear
+ iterations, but more vector products. Only effective for method
+ trust-krylov.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+ Only for 'trust-krylov', 'trust-ncg'.
+
+ .. versionadded:: 1.16.0
+ subproblem_maxiter : int, optional
+ Maximum number of iterations to perform per subproblem. Only affects
+ trust-exact. Default is 25.
+
+ .. versionadded:: 1.17.0
+
+
+ This function is called by the `minimize` function.
+ It is not supposed to be called directly.
+ """
+ _check_unknown_options(unknown_options)
+
+ if jac is None:
+ raise ValueError('Jacobian is currently required for trust-region '
+ 'methods')
+ if hess is None and hessp is None:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is currently required for trust-region methods')
+ if subproblem is None:
+ raise ValueError('A subproblem solving strategy is required for '
+ 'trust-region methods')
+ if not (0 <= eta < 0.25):
+ raise Exception('invalid acceptance stringency')
+ if max_trust_radius <= 0:
+ raise Exception('the max trust radius must be positive')
+ if initial_trust_radius <= 0:
+ raise ValueError('the initial trust radius must be positive')
+ if initial_trust_radius >= max_trust_radius:
+ raise ValueError('the initial trust radius must be less than the '
+ 'max trust radius')
+
+ # force the initial guess into a nice format
+ x0 = np.asarray(x0).flatten()
+
+ # A ScalarFunction representing the problem. This caches calls to fun, jac,
+ # hess.
+ # the workers kwd only has an effect for trust-ncg, trust-krylov when
+ # estimating the Hessian with finite-differences. It's never used
+ # during calculation of jacobian, because callables are required for all
+ # methods.
+ sf = _prepare_scalar_function(
+ fun, x0, jac=jac, hess=hess, args=args, workers=workers
+ )
+ fun = sf.fun
+ jac = sf.grad
+ if callable(hess):
+ hess = sf.hess
+ elif callable(hessp):
+ # this elif statement must come before examining whether hess
+ # is estimated by FD methods or a HessianUpdateStrategy
+ pass
+ elif (hess in FD_METHODS or isinstance(hess, HessianUpdateStrategy)):
+ # If the Hessian is being estimated by finite differences or a
+ # Hessian update strategy then ScalarFunction.hess returns a
+ # LinearOperator or a HessianUpdateStrategy. This enables the
+ # calculation/creation of a hessp. BUT you only want to do this
+ # if the user *hasn't* provided a callable(hessp) function.
+ hess = None
+
+ def hessp(x, p, *args):
+ return sf.hess(x).dot(p)
+ else:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is currently required for trust-region methods')
+
+ # ScalarFunction doesn't represent hessp
+ nhessp, hessp = _wrap_function(hessp, args)
+
+ # limit the number of iterations
+ if maxiter is None:
+ maxiter = len(x0)*200
+
+ # init the search status
+ warnflag = 0
+
+ # initialize the search
+ trust_radius = initial_trust_radius
+ x = x0
+ if return_all:
+ allvecs = [x]
+
+ subproblem_init_kw = {}
+ if hasattr(subproblem, 'MAXITER_DEFAULT'):
+ subproblem_init_kw['maxiter'] = subproblem_maxiter
+
+ m = subproblem(x, fun, jac, hess, hessp, **subproblem_init_kw)
+ k = 0
+
+ # search for the function min
+ # do not even start if the gradient is small enough
+ while m.jac_mag >= gtol:
+
+ # Solve the sub-problem.
+ # This gives us the proposed step relative to the current position
+ # and it tells us whether the proposed step
+ # has reached the trust region boundary or not.
+ try:
+ p, hits_boundary = m.solve(trust_radius)
+ except np.linalg.LinAlgError:
+ warnflag = 3
+ break
+
+ # calculate the predicted value at the proposed point
+ predicted_value = m(p)
+
+ # define the local approximation at the proposed point
+ x_proposed = x + p
+ m_proposed = subproblem(x_proposed, fun, jac, hess, hessp, **subproblem_init_kw)
+
+ # evaluate the ratio defined in equation (4.4)
+ actual_reduction = m.fun - m_proposed.fun
+ predicted_reduction = m.fun - predicted_value
+ if predicted_reduction <= 0:
+ warnflag = 2
+ break
+ rho = actual_reduction / predicted_reduction
+
+ # update the trust radius according to the actual/predicted ratio
+ if rho < 0.25:
+ trust_radius *= 0.25
+ elif rho > 0.75 and hits_boundary:
+ trust_radius = min(2*trust_radius, max_trust_radius)
+
+ # if the ratio is high enough then accept the proposed step
+ if rho > eta:
+ x = x_proposed
+ m = m_proposed
+
+ # append the best guess, call back, increment the iteration count
+ if return_all:
+ allvecs.append(np.copy(x))
+ k += 1
+
+ intermediate_result = OptimizeResult(x=x, fun=m.fun)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ # check if the gradient is small enough to stop
+ if m.jac_mag < gtol:
+ warnflag = 0
+ break
+
+ # check if we have looked at enough iterations
+ if k >= maxiter:
+ warnflag = 1
+ break
+
+ # print some stuff if requested
+ status_messages = (
+ _status_message['success'],
+ _status_message['maxiter'],
+ 'A bad approximation caused failure to predict improvement.',
+ 'A linalg error occurred, such as a non-psd Hessian.',
+ )
+ if disp:
+ if warnflag == 0:
+ print(status_messages[warnflag])
+ else:
+ warnings.warn(status_messages[warnflag], RuntimeWarning, stacklevel=3)
+ print(f" Current function value: {m.fun:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+ print(f" Hessian evaluations: {sf.nhev + nhessp[0]:d}")
+
+ result = OptimizeResult(x=x, success=(warnflag == 0), status=warnflag,
+ fun=m.fun, jac=m.jac, nfev=sf.nfev, njev=sf.ngev,
+ nhev=sf.nhev + nhessp[0], nit=k,
+ message=status_messages[warnflag])
+
+ if hess is not None:
+ result['hess'] = m.hess
+
+ if return_all:
+ result['allvecs'] = allvecs
+
+ return result
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..549cfb9760dda474cb858b7b36d236af48111067
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/__init__.py
@@ -0,0 +1,6 @@
+"""This module contains the equality constrained SQP solver."""
+
+
+from .minimize_trustregion_constr import _minimize_trustregion_constr
+
+__all__ = ['_minimize_trustregion_constr']
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..475f7ba970d0952af31e2b30fb03841725397e9c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py
@@ -0,0 +1,390 @@
+import numpy as np
+import scipy.sparse as sps
+
+
+class CanonicalConstraint:
+ """Canonical constraint to use with trust-constr algorithm.
+
+ It represents the set of constraints of the form::
+
+ f_eq(x) = 0
+ f_ineq(x) <= 0
+
+ where ``f_eq`` and ``f_ineq`` are evaluated by a single function, see
+ below.
+
+ The class is supposed to be instantiated by factory methods, which
+ should prepare the parameters listed below.
+
+ Parameters
+ ----------
+ n_eq, n_ineq : int
+ Number of equality and inequality constraints respectively.
+ fun : callable
+ Function defining the constraints. The signature is
+ ``fun(x) -> c_eq, c_ineq``, where ``c_eq`` is ndarray with `n_eq`
+ components and ``c_ineq`` is ndarray with `n_ineq` components.
+ jac : callable
+ Function to evaluate the Jacobian of the constraint. The signature
+ is ``jac(x) -> J_eq, J_ineq``, where ``J_eq`` and ``J_ineq`` are
+ either ndarray of csr_array of shapes (n_eq, n) and (n_ineq, n),
+ respectively.
+ hess : callable
+ Function to evaluate the Hessian of the constraints multiplied
+ by Lagrange multipliers, that is
+ ``dot(f_eq, v_eq) + dot(f_ineq, v_ineq)``. The signature is
+ ``hess(x, v_eq, v_ineq) -> H``, where ``H`` has an implied
+ shape (n, n) and provide a matrix-vector product operation
+ ``H.dot(p)``.
+ keep_feasible : ndarray, shape (n_ineq,)
+ Mask indicating which inequality constraints should be kept feasible.
+ """
+ def __init__(self, n_eq, n_ineq, fun, jac, hess, keep_feasible):
+ self.n_eq = n_eq
+ self.n_ineq = n_ineq
+ self.fun = fun
+ self.jac = jac
+ self.hess = hess
+ self.keep_feasible = keep_feasible
+
+ @classmethod
+ def from_PreparedConstraint(cls, constraint):
+ """Create an instance from `PreparedConstrained` object."""
+ lb, ub = constraint.bounds
+ cfun = constraint.fun
+ keep_feasible = constraint.keep_feasible
+
+ if np.all(lb == -np.inf) and np.all(ub == np.inf):
+ return cls.empty(cfun.n)
+
+ if np.all(lb == -np.inf) and np.all(ub == np.inf):
+ return cls.empty(cfun.n)
+ elif np.all(lb == ub):
+ return cls._equal_to_canonical(cfun, lb)
+ elif np.all(lb == -np.inf):
+ return cls._less_to_canonical(cfun, ub, keep_feasible)
+ elif np.all(ub == np.inf):
+ return cls._greater_to_canonical(cfun, lb, keep_feasible)
+ else:
+ return cls._interval_to_canonical(cfun, lb, ub, keep_feasible)
+
+ @classmethod
+ def empty(cls, n):
+ """Create an "empty" instance.
+
+ This "empty" instance is required to allow working with unconstrained
+ problems as if they have some constraints.
+ """
+ empty_fun = np.empty(0)
+ empty_jac = np.empty((0, n))
+ empty_hess = sps.csr_array((n, n))
+
+ def fun(x):
+ return empty_fun, empty_fun
+
+ def jac(x):
+ return empty_jac, empty_jac
+
+ def hess(x, v_eq, v_ineq):
+ return empty_hess
+
+ return cls(0, 0, fun, jac, hess, np.empty(0, dtype=np.bool_))
+
+ @classmethod
+ def concatenate(cls, canonical_constraints, sparse_jacobian):
+ """Concatenate multiple `CanonicalConstraint` into one.
+
+ `sparse_jacobian` (bool) determines the Jacobian format of the
+ concatenated constraint. Note that items in `canonical_constraints`
+ must have their Jacobians in the same format.
+ """
+ def fun(x):
+ if canonical_constraints:
+ eq_all, ineq_all = zip(
+ *[c.fun(x) for c in canonical_constraints])
+ else:
+ eq_all, ineq_all = [], []
+
+ return np.hstack(eq_all), np.hstack(ineq_all)
+
+ if sparse_jacobian:
+ vstack = sps.vstack
+ else:
+ vstack = np.vstack
+
+ def jac(x):
+ if canonical_constraints:
+ eq_all, ineq_all = zip(
+ *[c.jac(x) for c in canonical_constraints])
+ else:
+ eq_all, ineq_all = [], []
+
+ return vstack(eq_all), vstack(ineq_all)
+
+ def hess(x, v_eq, v_ineq):
+ hess_all = []
+ index_eq = 0
+ index_ineq = 0
+ for c in canonical_constraints:
+ vc_eq = v_eq[index_eq:index_eq + c.n_eq]
+ vc_ineq = v_ineq[index_ineq:index_ineq + c.n_ineq]
+ hess_all.append(c.hess(x, vc_eq, vc_ineq))
+ index_eq += c.n_eq
+ index_ineq += c.n_ineq
+
+ def matvec(p):
+ result = np.zeros_like(p, dtype=float)
+ for h in hess_all:
+ result += h.dot(p)
+ return result
+
+ n = x.shape[0]
+ return sps.linalg.LinearOperator((n, n), matvec, dtype=float)
+
+ n_eq = sum(c.n_eq for c in canonical_constraints)
+ n_ineq = sum(c.n_ineq for c in canonical_constraints)
+ keep_feasible = np.hstack([c.keep_feasible for c in
+ canonical_constraints])
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _equal_to_canonical(cls, cfun, value):
+ empty_fun = np.empty(0)
+ n = cfun.n
+
+ n_eq = value.shape[0]
+ n_ineq = 0
+ keep_feasible = np.empty(0, dtype=bool)
+
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ def fun(x):
+ return cfun.fun(x) - value, empty_fun
+
+ def jac(x):
+ return cfun.jac(x), empty_jac
+
+ def hess(x, v_eq, v_ineq):
+ return cfun.hess(x, v_eq)
+
+ empty_fun = np.empty(0)
+ n = cfun.n
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _less_to_canonical(cls, cfun, ub, keep_feasible):
+ empty_fun = np.empty(0)
+ n = cfun.n
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ finite_ub = ub < np.inf
+ n_eq = 0
+ n_ineq = np.sum(finite_ub)
+
+ if np.all(finite_ub):
+ def fun(x):
+ return empty_fun, cfun.fun(x) - ub
+
+ def jac(x):
+ return empty_jac, cfun.jac(x)
+
+ def hess(x, v_eq, v_ineq):
+ return cfun.hess(x, v_ineq)
+ else:
+ finite_ub = np.nonzero(finite_ub)[0]
+ keep_feasible = keep_feasible[finite_ub]
+ ub = ub[finite_ub]
+
+ def fun(x):
+ return empty_fun, cfun.fun(x)[finite_ub] - ub
+
+ def jac(x):
+ return empty_jac, cfun.jac(x)[finite_ub]
+
+ def hess(x, v_eq, v_ineq):
+ v = np.zeros(cfun.m)
+ v[finite_ub] = v_ineq
+ return cfun.hess(x, v)
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _greater_to_canonical(cls, cfun, lb, keep_feasible):
+ empty_fun = np.empty(0)
+ n = cfun.n
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ finite_lb = lb > -np.inf
+ n_eq = 0
+ n_ineq = np.sum(finite_lb)
+
+ if np.all(finite_lb):
+ def fun(x):
+ return empty_fun, lb - cfun.fun(x)
+
+ def jac(x):
+ return empty_jac, -cfun.jac(x)
+
+ def hess(x, v_eq, v_ineq):
+ return cfun.hess(x, -v_ineq)
+ else:
+ finite_lb = np.nonzero(finite_lb)[0]
+ keep_feasible = keep_feasible[finite_lb]
+ lb = lb[finite_lb]
+
+ def fun(x):
+ return empty_fun, lb - cfun.fun(x)[finite_lb]
+
+ def jac(x):
+ return empty_jac, -cfun.jac(x)[finite_lb]
+
+ def hess(x, v_eq, v_ineq):
+ v = np.zeros(cfun.m)
+ v[finite_lb] = -v_ineq
+ return cfun.hess(x, v)
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _interval_to_canonical(cls, cfun, lb, ub, keep_feasible):
+ lb_inf = lb == -np.inf
+ ub_inf = ub == np.inf
+ equal = lb == ub
+ less = lb_inf & ~ub_inf
+ greater = ub_inf & ~lb_inf
+ interval = ~equal & ~lb_inf & ~ub_inf
+
+ equal = np.nonzero(equal)[0]
+ less = np.nonzero(less)[0]
+ greater = np.nonzero(greater)[0]
+ interval = np.nonzero(interval)[0]
+ n_less = less.shape[0]
+ n_greater = greater.shape[0]
+ n_interval = interval.shape[0]
+ n_ineq = n_less + n_greater + 2 * n_interval
+ n_eq = equal.shape[0]
+
+ keep_feasible = np.hstack((keep_feasible[less],
+ keep_feasible[greater],
+ keep_feasible[interval],
+ keep_feasible[interval]))
+
+ def fun(x):
+ f = cfun.fun(x)
+ eq = f[equal] - lb[equal]
+ le = f[less] - ub[less]
+ ge = lb[greater] - f[greater]
+ il = f[interval] - ub[interval]
+ ig = lb[interval] - f[interval]
+ return eq, np.hstack((le, ge, il, ig))
+
+ def jac(x):
+ J = cfun.jac(x)
+ eq = J[equal]
+ le = J[less]
+ ge = -J[greater]
+ il = J[interval]
+ ig = -il
+ if sps.issparse(J):
+ ineq = sps.vstack((le, ge, il, ig))
+ else:
+ ineq = np.vstack((le, ge, il, ig))
+ return eq, ineq
+
+ def hess(x, v_eq, v_ineq):
+ n_start = 0
+ v_l = v_ineq[n_start:n_start + n_less]
+ n_start += n_less
+ v_g = v_ineq[n_start:n_start + n_greater]
+ n_start += n_greater
+ v_il = v_ineq[n_start:n_start + n_interval]
+ n_start += n_interval
+ v_ig = v_ineq[n_start:n_start + n_interval]
+
+ v = np.zeros_like(lb)
+ v[equal] = v_eq
+ v[less] = v_l
+ v[greater] = -v_g
+ v[interval] = v_il - v_ig
+
+ return cfun.hess(x, v)
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+
+def initial_constraints_as_canonical(n, prepared_constraints, sparse_jacobian):
+ """Convert initial values of the constraints to the canonical format.
+
+ The purpose to avoid one additional call to the constraints at the initial
+ point. It takes saved values in `PreparedConstraint`, modifies and
+ concatenates them to the canonical constraint format.
+ """
+ c_eq = []
+ c_ineq = []
+ J_eq = []
+ J_ineq = []
+
+ for c in prepared_constraints:
+ f = c.fun.f
+ J = c.fun.J
+ lb, ub = c.bounds
+ if np.all(lb == ub):
+ c_eq.append(f - lb)
+ J_eq.append(J)
+ elif np.all(lb == -np.inf):
+ finite_ub = ub < np.inf
+ c_ineq.append(f[finite_ub] - ub[finite_ub])
+ J_ineq.append(J[finite_ub])
+ elif np.all(ub == np.inf):
+ finite_lb = lb > -np.inf
+ c_ineq.append(lb[finite_lb] - f[finite_lb])
+ J_ineq.append(-J[finite_lb])
+ else:
+ lb_inf = lb == -np.inf
+ ub_inf = ub == np.inf
+ equal = lb == ub
+ less = lb_inf & ~ub_inf
+ greater = ub_inf & ~lb_inf
+ interval = ~equal & ~lb_inf & ~ub_inf
+
+ c_eq.append(f[equal] - lb[equal])
+ c_ineq.append(f[less] - ub[less])
+ c_ineq.append(lb[greater] - f[greater])
+ c_ineq.append(f[interval] - ub[interval])
+ c_ineq.append(lb[interval] - f[interval])
+
+ J_eq.append(J[equal])
+ J_ineq.append(J[less])
+ J_ineq.append(-J[greater])
+ J_ineq.append(J[interval])
+ J_ineq.append(-J[interval])
+
+ c_eq = np.hstack(c_eq) if c_eq else np.empty(0)
+ c_ineq = np.hstack(c_ineq) if c_ineq else np.empty(0)
+
+ if sparse_jacobian:
+ vstack = sps.vstack
+ empty = sps.csr_array((0, n))
+ else:
+ vstack = np.vstack
+ empty = np.empty((0, n))
+
+ J_eq = vstack(J_eq) if J_eq else empty
+ J_ineq = vstack(J_ineq) if J_ineq else empty
+
+ return c_eq, c_ineq, J_eq, J_ineq
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..20cb069f11be9541ac9fd7dfdd68c0177a0aa685
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py
@@ -0,0 +1,231 @@
+"""Byrd-Omojokun Trust-Region SQP method."""
+
+from scipy.sparse import eye_array as speye
+from .projections import projections
+from .qp_subproblem import modified_dogleg, projected_cg, box_intersections
+import numpy as np
+from numpy.linalg import norm
+
+__all__ = ['equality_constrained_sqp']
+
+
+def default_scaling(x):
+ n, = np.shape(x)
+ return speye(n)
+
+
+def equality_constrained_sqp(fun_and_constr, grad_and_jac, lagr_hess,
+ x0, fun0, grad0, constr0,
+ jac0, stop_criteria,
+ state,
+ initial_penalty,
+ initial_trust_radius,
+ factorization_method,
+ trust_lb=None,
+ trust_ub=None,
+ scaling=default_scaling):
+ """Solve nonlinear equality-constrained problem using trust-region SQP.
+
+ Solve optimization problem:
+
+ minimize fun(x)
+ subject to: constr(x) = 0
+
+ using Byrd-Omojokun Trust-Region SQP method described in [1]_. Several
+ implementation details are based on [2]_ and [3]_, p. 549.
+
+ References
+ ----------
+ .. [1] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. "On the
+ implementation of an algorithm for large-scale equality
+ constrained optimization." SIAM Journal on
+ Optimization 8.3 (1998): 682-706.
+ .. [2] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
+ "An interior point algorithm for large-scale nonlinear
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
+ .. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+ PENALTY_FACTOR = 0.3 # Rho from formula (3.51), reference [2]_, p.891.
+ LARGE_REDUCTION_RATIO = 0.9
+ INTERMEDIARY_REDUCTION_RATIO = 0.3
+ SUFFICIENT_REDUCTION_RATIO = 1e-8 # Eta from reference [2]_, p.892.
+ TRUST_ENLARGEMENT_FACTOR_L = 7.0
+ TRUST_ENLARGEMENT_FACTOR_S = 2.0
+ MAX_TRUST_REDUCTION = 0.5
+ MIN_TRUST_REDUCTION = 0.1
+ SOC_THRESHOLD = 0.1
+ TR_FACTOR = 0.8 # Zeta from formula (3.21), reference [2]_, p.885.
+ BOX_FACTOR = 0.5
+
+ n, = np.shape(x0) # Number of parameters
+
+ # Set default lower and upper bounds.
+ if trust_lb is None:
+ trust_lb = np.full(n, -np.inf)
+ if trust_ub is None:
+ trust_ub = np.full(n, np.inf)
+
+ # Initial values
+ x = np.copy(x0)
+ trust_radius = initial_trust_radius
+ penalty = initial_penalty
+ # Compute Values
+ f = fun0
+ c = grad0
+ b = constr0
+ A = jac0
+ S = scaling(x)
+ # Get projections
+ try:
+ Z, LS, Y = projections(A, factorization_method)
+ except ValueError as e:
+ if str(e) == "expected square matrix":
+ # can be the case if there are more equality
+ # constraints than independent variables
+ raise ValueError(
+ "The 'expected square matrix' error can occur if there are"
+ " more equality constraints than independent variables."
+ " Consider how your constraints are set up, or use"
+ " factorization_method='SVDFactorization'."
+ ) from e
+ else:
+ raise e
+
+ # Compute least-square lagrange multipliers
+ v = -LS.dot(c)
+ # Compute Hessian
+ H = lagr_hess(x, v)
+
+ # Update state parameters
+ optimality = norm(c + A.T.dot(v), np.inf)
+ constr_violation = norm(b, np.inf) if len(b) > 0 else 0
+ cg_info = {'niter': 0, 'stop_cond': 0,
+ 'hits_boundary': False}
+
+ last_iteration_failed = False
+ while not stop_criteria(state, x, last_iteration_failed,
+ optimality, constr_violation,
+ trust_radius, penalty, cg_info):
+ # Normal Step - `dn`
+ # minimize 1/2*||A dn + b||^2
+ # subject to:
+ # ||dn|| <= TR_FACTOR * trust_radius
+ # BOX_FACTOR * lb <= dn <= BOX_FACTOR * ub.
+ dn = modified_dogleg(A, Y, b,
+ TR_FACTOR*trust_radius,
+ BOX_FACTOR*trust_lb,
+ BOX_FACTOR*trust_ub)
+
+ # Tangential Step - `dt`
+ # Solve the QP problem:
+ # minimize 1/2 dt.T H dt + dt.T (H dn + c)
+ # subject to:
+ # A dt = 0
+ # ||dt|| <= sqrt(trust_radius**2 - ||dn||**2)
+ # lb - dn <= dt <= ub - dn
+ c_t = H.dot(dn) + c
+ b_t = np.zeros_like(b)
+ trust_radius_t = np.sqrt(trust_radius**2 - np.linalg.norm(dn)**2)
+ lb_t = trust_lb - dn
+ ub_t = trust_ub - dn
+ dt, cg_info = projected_cg(H, c_t, Z, Y, b_t,
+ trust_radius_t,
+ lb_t, ub_t)
+
+ # Compute update (normal + tangential steps).
+ d = dn + dt
+
+ # Compute second order model: 1/2 d H d + c.T d + f.
+ quadratic_model = 1/2*(H.dot(d)).dot(d) + c.T.dot(d)
+ # Compute linearized constraint: l = A d + b.
+ linearized_constr = A.dot(d)+b
+ # Compute new penalty parameter according to formula (3.52),
+ # reference [2]_, p.891.
+ vpred = norm(b) - norm(linearized_constr)
+ # Guarantee `vpred` always positive,
+ # regardless of roundoff errors.
+ vpred = max(1e-16, vpred)
+ previous_penalty = penalty
+ if quadratic_model > 0:
+ new_penalty = quadratic_model / ((1-PENALTY_FACTOR)*vpred)
+ penalty = max(penalty, new_penalty)
+ # Compute predicted reduction according to formula (3.52),
+ # reference [2]_, p.891.
+ predicted_reduction = -quadratic_model + penalty*vpred
+
+ # Compute merit function at current point
+ merit_function = f + penalty*norm(b)
+ # Evaluate function and constraints at trial point
+ x_next = x + S.dot(d)
+ f_next, b_next = fun_and_constr(x_next)
+ # Compute merit function at trial point
+ merit_function_next = f_next + penalty*norm(b_next)
+ # Compute actual reduction according to formula (3.54),
+ # reference [2]_, p.892.
+ actual_reduction = merit_function - merit_function_next
+ # Compute reduction ratio
+ reduction_ratio = actual_reduction / predicted_reduction
+
+ # Second order correction (SOC), reference [2]_, p.892.
+ if reduction_ratio < SUFFICIENT_REDUCTION_RATIO and \
+ norm(dn) <= SOC_THRESHOLD * norm(dt):
+ # Compute second order correction
+ y = -Y.dot(b_next)
+ # Make sure increment is inside box constraints
+ _, t, intersect = box_intersections(d, y, trust_lb, trust_ub)
+ # Compute tentative point
+ x_soc = x + S.dot(d + t*y)
+ f_soc, b_soc = fun_and_constr(x_soc)
+ # Recompute actual reduction
+ merit_function_soc = f_soc + penalty*norm(b_soc)
+ actual_reduction_soc = merit_function - merit_function_soc
+ # Recompute reduction ratio
+ reduction_ratio_soc = actual_reduction_soc / predicted_reduction
+ if intersect and reduction_ratio_soc >= SUFFICIENT_REDUCTION_RATIO:
+ x_next = x_soc
+ f_next = f_soc
+ b_next = b_soc
+ reduction_ratio = reduction_ratio_soc
+
+ # Readjust trust region step, formula (3.55), reference [2]_, p.892.
+ if reduction_ratio >= LARGE_REDUCTION_RATIO:
+ trust_radius = max(TRUST_ENLARGEMENT_FACTOR_L * norm(d),
+ trust_radius)
+ elif reduction_ratio >= INTERMEDIARY_REDUCTION_RATIO:
+ trust_radius = max(TRUST_ENLARGEMENT_FACTOR_S * norm(d),
+ trust_radius)
+ # Reduce trust region step, according to reference [3]_, p.696.
+ elif reduction_ratio < SUFFICIENT_REDUCTION_RATIO:
+ trust_reduction = ((1-SUFFICIENT_REDUCTION_RATIO) /
+ (1-reduction_ratio))
+ new_trust_radius = trust_reduction * norm(d)
+ if new_trust_radius >= MAX_TRUST_REDUCTION * trust_radius:
+ trust_radius *= MAX_TRUST_REDUCTION
+ elif new_trust_radius >= MIN_TRUST_REDUCTION * trust_radius:
+ trust_radius = new_trust_radius
+ else:
+ trust_radius *= MIN_TRUST_REDUCTION
+
+ # Update iteration
+ if reduction_ratio >= SUFFICIENT_REDUCTION_RATIO:
+ x = x_next
+ f, b = f_next, b_next
+ c, A = grad_and_jac(x)
+ S = scaling(x)
+ # Get projections
+ Z, LS, Y = projections(A, factorization_method)
+ # Compute least-square lagrange multipliers
+ v = -LS.dot(c)
+ # Compute Hessian
+ H = lagr_hess(x, v)
+ # Set Flag
+ last_iteration_failed = False
+ # Optimality values
+ optimality = norm(c + A.T.dot(v), np.inf)
+ constr_violation = norm(b, np.inf) if len(b) > 0 else 0
+ else:
+ penalty = previous_penalty
+ last_iteration_failed = True
+
+ return x, state
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py
new file mode 100644
index 0000000000000000000000000000000000000000..39cc93c2d9697168ad5ef66df9f9ea1dedeb353e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py
@@ -0,0 +1,586 @@
+import time
+import numpy as np
+from scipy.sparse.linalg import LinearOperator
+from .._differentiable_functions import VectorFunction
+from .._constraints import (
+ NonlinearConstraint, LinearConstraint, PreparedConstraint, Bounds, strict_bounds)
+from .._hessian_update_strategy import BFGS
+from .._optimize import OptimizeResult
+from .._differentiable_functions import ScalarFunction
+from .equality_constrained_sqp import equality_constrained_sqp
+from .canonical_constraint import (CanonicalConstraint,
+ initial_constraints_as_canonical)
+from .tr_interior_point import tr_interior_point
+from .report import BasicReport, SQPReport, IPReport
+
+
+TERMINATION_MESSAGES = {
+ 0: "The maximum number of function evaluations is exceeded.",
+ 1: "`gtol` termination condition is satisfied.",
+ 2: "`xtol` termination condition is satisfied.",
+ 3: "`callback` raised `StopIteration`.",
+ 4: "Constraint violation exceeds 'gtol'"
+}
+
+
+class HessianLinearOperator:
+ """Build LinearOperator from hessp"""
+ def __init__(self, hessp, n):
+ self.hessp = hessp
+ self.n = n
+
+ def __call__(self, x, *args):
+ def matvec(p):
+ return self.hessp(x, p, *args)
+
+ return LinearOperator((self.n, self.n), matvec=matvec)
+
+
+class LagrangianHessian:
+ """The Hessian of the Lagrangian as LinearOperator.
+
+ The Lagrangian is computed as the objective function plus all the
+ constraints multiplied with some numbers (Lagrange multipliers).
+ """
+ def __init__(self, n, objective_hess, constraints_hess):
+ self.n = n
+ self.objective_hess = objective_hess
+ self.constraints_hess = constraints_hess
+
+ def __call__(self, x, v_eq, v_ineq=None):
+ if v_ineq is None:
+ v_ineq = np.empty(0)
+ H_objective = self.objective_hess(x)
+ H_constraints = self.constraints_hess(x, v_eq, v_ineq)
+
+ def matvec(p):
+ return H_objective.dot(p) + H_constraints.dot(p)
+
+ return LinearOperator((self.n, self.n), matvec)
+
+
+def update_state_sqp(state, x, last_iteration_failed, objective, prepared_constraints,
+ start_time, tr_radius, constr_penalty, cg_info):
+ state.nit += 1
+ state.nfev = objective.nfev
+ state.njev = objective.ngev
+ state.nhev = objective.nhev
+ state.constr_nfev = [c.fun.nfev if isinstance(c.fun, VectorFunction) else 0
+ for c in prepared_constraints]
+ state.constr_njev = [c.fun.njev if isinstance(c.fun, VectorFunction) else 0
+ for c in prepared_constraints]
+ state.constr_nhev = [c.fun.nhev if isinstance(c.fun, VectorFunction) else 0
+ for c in prepared_constraints]
+
+ if not last_iteration_failed:
+ state.x = x
+ state.fun = objective.f
+ state.grad = objective.g
+ state.v = [c.fun.v for c in prepared_constraints]
+ state.constr = [c.fun.f for c in prepared_constraints]
+ state.jac = [c.fun.J for c in prepared_constraints]
+ # Compute Lagrangian Gradient
+ state.lagrangian_grad = np.copy(state.grad)
+ for c in prepared_constraints:
+ state.lagrangian_grad += c.fun.J.T.dot(c.fun.v)
+ state.optimality = np.linalg.norm(state.lagrangian_grad, np.inf)
+ # Compute maximum constraint violation
+ state.constr_violation = 0
+ for i in range(len(prepared_constraints)):
+ lb, ub = prepared_constraints[i].bounds
+ c = state.constr[i]
+ state.constr_violation = np.max([state.constr_violation,
+ np.max(lb - c),
+ np.max(c - ub)])
+
+ state.execution_time = time.time() - start_time
+ state.tr_radius = tr_radius
+ state.constr_penalty = constr_penalty
+ state.cg_niter += cg_info["niter"]
+ state.cg_stop_cond = cg_info["stop_cond"]
+
+ return state
+
+
+def update_state_ip(state, x, last_iteration_failed, objective,
+ prepared_constraints, start_time,
+ tr_radius, constr_penalty, cg_info,
+ barrier_parameter, barrier_tolerance):
+ state = update_state_sqp(state, x, last_iteration_failed, objective,
+ prepared_constraints, start_time, tr_radius,
+ constr_penalty, cg_info)
+ state.barrier_parameter = barrier_parameter
+ state.barrier_tolerance = barrier_tolerance
+ return state
+
+
+def _minimize_trustregion_constr(fun, x0, args, grad,
+ hess, hessp, bounds, constraints,
+ xtol=1e-8, gtol=1e-8,
+ barrier_tol=1e-8,
+ sparse_jacobian=None,
+ callback=None, maxiter=1000,
+ verbose=0, finite_diff_rel_step=None,
+ initial_constr_penalty=1.0, initial_tr_radius=1.0,
+ initial_barrier_parameter=0.1,
+ initial_barrier_tolerance=0.1,
+ factorization_method=None,
+ disp=False,
+ workers=None):
+ """Minimize a scalar function subject to constraints.
+
+ Parameters
+ ----------
+ gtol : float, optional
+ Tolerance for termination by the norm of the Lagrangian gradient.
+ The algorithm will terminate when both the infinity norm (i.e., max
+ abs value) of the Lagrangian gradient and the constraint violation
+ are smaller than ``gtol``. Default is 1e-8.
+ xtol : float, optional
+ Tolerance for termination by the change of the independent variable.
+ The algorithm will terminate when ``tr_radius < xtol``, where
+ ``tr_radius`` is the radius of the trust region used in the algorithm.
+ Default is 1e-8.
+ barrier_tol : float, optional
+ Threshold on the barrier parameter for the algorithm termination.
+ When inequality constraints are present, the algorithm will terminate
+ only when the barrier parameter is less than `barrier_tol`.
+ Default is 1e-8.
+ sparse_jacobian : {bool, None}, optional
+ Determines how to represent Jacobians of the constraints. If bool,
+ then Jacobians of all the constraints will be converted to the
+ corresponding format. If None (default), then Jacobians won't be
+ converted, but the algorithm can proceed only if they all have the
+ same format.
+ initial_tr_radius: float, optional
+ Initial trust radius. The trust radius gives the maximum distance
+ between solution points in consecutive iterations. It reflects the
+ trust the algorithm puts in the local approximation of the optimization
+ problem. For an accurate local approximation the trust-region should be
+ large and for an approximation valid only close to the current point it
+ should be a small one. The trust radius is automatically updated throughout
+ the optimization process, with ``initial_tr_radius`` being its initial value.
+ Default is 1 (recommended in [1]_, p. 19).
+ initial_constr_penalty : float, optional
+ Initial constraints penalty parameter. The penalty parameter is used for
+ balancing the requirements of decreasing the objective function
+ and satisfying the constraints. It is used for defining the merit function:
+ ``merit_function(x) = fun(x) + constr_penalty * constr_norm_l2(x)``,
+ where ``constr_norm_l2(x)`` is the l2 norm of a vector containing all
+ the constraints. The merit function is used for accepting or rejecting
+ trial points and ``constr_penalty`` weights the two conflicting goals
+ of reducing objective function and constraints. The penalty is automatically
+ updated throughout the optimization process, with
+ ``initial_constr_penalty`` being its initial value. Default is 1
+ (recommended in [1]_, p 19).
+ initial_barrier_parameter, initial_barrier_tolerance: float, optional
+ Initial barrier parameter and initial tolerance for the barrier subproblem.
+ Both are used only when inequality constraints are present. For dealing with
+ optimization problems ``min_x f(x)`` subject to inequality constraints
+ ``c(x) <= 0`` the algorithm introduces slack variables, solving the problem
+ ``min_(x,s) f(x) + barrier_parameter*sum(ln(s))`` subject to the equality
+ constraints ``c(x) + s = 0`` instead of the original problem. This subproblem
+ is solved for decreasing values of ``barrier_parameter`` and with decreasing
+ tolerances for the termination, starting with ``initial_barrier_parameter``
+ for the barrier parameter and ``initial_barrier_tolerance`` for the
+ barrier tolerance. Default is 0.1 for both values (recommended in [1]_ p. 19).
+ Also note that ``barrier_parameter`` and ``barrier_tolerance`` are updated
+ with the same prefactor.
+ factorization_method : str or None, optional
+ Method to factorize the Jacobian of the constraints. Use None (default)
+ for the auto selection or one of:
+
+ - 'NormalEquation' (requires scikit-sparse)
+ - 'AugmentedSystem'
+ - 'QRFactorization'
+ - 'SVDFactorization'
+
+ The methods 'NormalEquation' and 'AugmentedSystem' can be used only
+ with sparse constraints. The projections required by the algorithm
+ will be computed using, respectively, the normal equation and the
+ augmented system approaches explained in [1]_. 'NormalEquation'
+ computes the Cholesky factorization of ``A A.T`` and 'AugmentedSystem'
+ performs the LU factorization of an augmented system. They usually
+ provide similar results. 'AugmentedSystem' is used by default for
+ sparse matrices.
+
+ The methods 'QRFactorization' and 'SVDFactorization' can be used
+ only with dense constraints. They compute the required projections
+ using, respectively, QR and SVD factorizations. The 'SVDFactorization'
+ method can cope with Jacobian matrices with deficient row rank and will
+ be used whenever other factorization methods fail (which may imply the
+ conversion of sparse matrices to a dense format when required).
+ By default, 'QRFactorization' is used for dense matrices.
+ finite_diff_rel_step : None or array_like, optional
+ Relative step size for the finite difference approximation.
+ maxiter : int, optional
+ Maximum number of algorithm iterations. Default is 1000.
+ verbose : {0, 1, 2, 3}, optional
+ Level of algorithm's verbosity:
+
+ * 0 (default) : work silently.
+ * 1 : display a termination report.
+ * 2 : display progress during iterations.
+ * 3 : display progress during iterations (more complete report).
+
+ disp : bool, optional
+ If True (default), then `verbose` will be set to 1 if it was 0.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ `OptimizeResult` with the fields documented below. Note the following:
+
+ 1. All values corresponding to the constraints are ordered as they
+ were passed to the solver. And values corresponding to `bounds`
+ constraints are put *after* other constraints.
+ 2. All numbers of function, Jacobian or Hessian evaluations correspond
+ to numbers of actual Python function calls. It means, for example,
+ that if a Jacobian is estimated by finite differences, then the
+ number of Jacobian evaluations will be zero and the number of
+ function evaluations will be incremented by all calls during the
+ finite difference estimation.
+
+ x : ndarray, shape (n,)
+ Solution found.
+ optimality : float
+ Infinity norm of the Lagrangian gradient at the solution.
+ constr_violation : float
+ Maximum constraint violation at the solution.
+ fun : float
+ Objective function at the solution.
+ grad : ndarray, shape (n,)
+ Gradient of the objective function at the solution.
+ lagrangian_grad : ndarray, shape (n,)
+ Gradient of the Lagrangian function at the solution.
+ nit : int
+ Total number of iterations.
+ nfev : int
+ Number of the objective function evaluations.
+ njev : int
+ Number of the objective function gradient evaluations.
+ nhev : int
+ Number of the objective function Hessian evaluations.
+ cg_niter : int
+ Total number of the conjugate gradient method iterations.
+ method : {'equality_constrained_sqp', 'tr_interior_point'}
+ Optimization method used.
+ constr : list of ndarray
+ List of constraint values at the solution.
+ jac : list of {ndarray, sparse array}
+ List of the Jacobian matrices of the constraints at the solution.
+ v : list of ndarray
+ List of the Lagrange multipliers for the constraints at the solution.
+ For an inequality constraint a positive multiplier means that the upper
+ bound is active, a negative multiplier means that the lower bound is
+ active and if a multiplier is zero it means the constraint is not
+ active.
+ constr_nfev : list of int
+ Number of constraint evaluations for each of the constraints.
+ constr_njev : list of int
+ Number of Jacobian matrix evaluations for each of the constraints.
+ constr_nhev : list of int
+ Number of Hessian evaluations for each of the constraints.
+ tr_radius : float
+ Radius of the trust region at the last iteration.
+ constr_penalty : float
+ Penalty parameter at the last iteration, see `initial_constr_penalty`.
+ barrier_tolerance : float
+ Tolerance for the barrier subproblem at the last iteration.
+ Only for problems with inequality constraints.
+ barrier_parameter : float
+ Barrier parameter at the last iteration. Only for problems
+ with inequality constraints.
+ execution_time : float
+ Total execution time.
+ message : str
+ Termination message.
+ status : {0, 1, 2, 3, 4}
+ Termination status:
+
+ * 0 : The maximum number of function evaluations is exceeded.
+ * 1 : `gtol` termination condition is satisfied.
+ * 2 : `xtol` termination condition is satisfied.
+ * 3 : `callback` raised `StopIteration`.
+ * 4 : Constraint violation exceeds 'gtol'.
+
+ .. versionchanged:: 1.15.0
+ If the constraint violation exceeds `gtol`, then ``result.success``
+ will now be False.
+
+ cg_stop_cond : int
+ Reason for CG subproblem termination at the last iteration:
+
+ * 0 : CG subproblem not evaluated.
+ * 1 : Iteration limit was reached.
+ * 2 : Reached the trust-region boundary.
+ * 3 : Negative curvature detected.
+ * 4 : Tolerance was satisfied.
+
+ References
+ ----------
+ .. [1] Conn, A. R., Gould, N. I., & Toint, P. L.
+ Trust region methods. 2000. Siam. pp. 19.
+ """
+ x0 = np.atleast_1d(x0).astype(float)
+ n_vars = np.size(x0)
+ if hess is None:
+ if callable(hessp):
+ hess = HessianLinearOperator(hessp, n_vars)
+ else:
+ hess = BFGS()
+ if disp and verbose == 0:
+ verbose = 1
+
+ if bounds is not None:
+ modified_lb = np.nextafter(bounds.lb, -np.inf, where=bounds.lb > -np.inf,
+ out=None)
+ modified_ub = np.nextafter(bounds.ub, np.inf, where=bounds.ub < np.inf,
+ out=None)
+ modified_lb = np.where(np.isfinite(bounds.lb), modified_lb, bounds.lb)
+ modified_ub = np.where(np.isfinite(bounds.ub), modified_ub, bounds.ub)
+ bounds = Bounds(modified_lb, modified_ub, keep_feasible=bounds.keep_feasible)
+ finite_diff_bounds = strict_bounds(bounds.lb, bounds.ub,
+ bounds.keep_feasible, n_vars)
+ else:
+ finite_diff_bounds = (-np.inf, np.inf)
+
+ # Define Objective Function
+ objective = ScalarFunction(fun, x0, args, grad, hess,
+ finite_diff_rel_step, finite_diff_bounds,
+ workers=workers)
+
+ # Put constraints in list format when needed.
+ if isinstance(constraints, (NonlinearConstraint | LinearConstraint)):
+ constraints = [constraints]
+
+ # Prepare constraints.
+ prepared_constraints = [
+ PreparedConstraint(c, x0, sparse_jacobian, finite_diff_bounds)
+ for c in constraints]
+
+ # Check that all constraints are either sparse or dense.
+ n_sparse = sum(c.fun.sparse_jacobian for c in prepared_constraints)
+ if 0 < n_sparse < len(prepared_constraints):
+ raise ValueError("All constraints must have the same kind of the "
+ "Jacobian --- either all sparse or all dense. "
+ "You can set the sparsity globally by setting "
+ "`sparse_jacobian` to either True of False.")
+ if prepared_constraints:
+ sparse_jacobian = n_sparse > 0
+
+ if bounds is not None:
+ if sparse_jacobian is None:
+ sparse_jacobian = True
+ prepared_constraints.append(PreparedConstraint(bounds, x0,
+ sparse_jacobian))
+
+ # Concatenate initial constraints to the canonical form.
+ c_eq0, c_ineq0, J_eq0, J_ineq0 = initial_constraints_as_canonical(
+ n_vars, prepared_constraints, sparse_jacobian)
+
+ # Prepare all canonical constraints and concatenate it into one.
+ canonical_all = [CanonicalConstraint.from_PreparedConstraint(c)
+ for c in prepared_constraints]
+
+ if len(canonical_all) == 0:
+ canonical = CanonicalConstraint.empty(n_vars)
+ elif len(canonical_all) == 1:
+ canonical = canonical_all[0]
+ else:
+ canonical = CanonicalConstraint.concatenate(canonical_all,
+ sparse_jacobian)
+
+ # Generate the Hessian of the Lagrangian.
+ lagrangian_hess = LagrangianHessian(n_vars, objective.hess, canonical.hess)
+
+ # Choose appropriate method
+ if canonical.n_ineq == 0:
+ method = 'equality_constrained_sqp'
+ else:
+ method = 'tr_interior_point'
+
+ # Construct OptimizeResult
+ state = OptimizeResult(
+ nit=0, nfev=0, njev=0, nhev=0,
+ cg_niter=0, cg_stop_cond=0,
+ fun=objective.f, grad=objective.g,
+ lagrangian_grad=np.copy(objective.g),
+ constr=[c.fun.f for c in prepared_constraints],
+ jac=[c.fun.J for c in prepared_constraints],
+ constr_nfev=[0 for c in prepared_constraints],
+ constr_njev=[0 for c in prepared_constraints],
+ constr_nhev=[0 for c in prepared_constraints],
+ v=[c.fun.v for c in prepared_constraints],
+ method=method)
+
+ # Start counting
+ start_time = time.time()
+
+ # Define stop criteria
+ if method == 'equality_constrained_sqp':
+ def stop_criteria(state, x, last_iteration_failed,
+ optimality, constr_violation,
+ tr_radius, constr_penalty, cg_info):
+ state = update_state_sqp(state, x, last_iteration_failed,
+ objective, prepared_constraints,
+ start_time, tr_radius, constr_penalty,
+ cg_info)
+ if verbose == 2:
+ BasicReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation)
+ elif verbose > 2:
+ SQPReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation,
+ state.constr_penalty,
+ state.cg_stop_cond)
+ state.status = None
+ state.niter = state.nit # Alias for callback (backward-compatibility)
+ if callback is not None:
+ callback_stop = False
+ try:
+ callback_stop = callback(state)
+ except StopIteration:
+ callback_stop = True
+ if callback_stop:
+ state.status = 3
+ return True
+ if state.optimality < gtol and state.constr_violation < gtol:
+ state.status = 1
+ elif state.tr_radius < xtol:
+ state.status = 2
+ elif state.nit >= maxiter:
+ state.status = 0
+ return state.status in (0, 1, 2, 3)
+ elif method == 'tr_interior_point':
+ def stop_criteria(state, x, last_iteration_failed, tr_radius,
+ constr_penalty, cg_info, barrier_parameter,
+ barrier_tolerance):
+ state = update_state_ip(state, x, last_iteration_failed,
+ objective, prepared_constraints,
+ start_time, tr_radius, constr_penalty,
+ cg_info, barrier_parameter, barrier_tolerance)
+ if verbose == 2:
+ BasicReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation)
+ elif verbose > 2:
+ IPReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation,
+ state.constr_penalty,
+ state.barrier_parameter,
+ state.cg_stop_cond)
+ state.status = None
+ state.niter = state.nit # Alias for callback (backward compatibility)
+ if callback is not None:
+ callback_stop = False
+ try:
+ callback_stop = callback(state)
+ except StopIteration:
+ callback_stop = True
+ if callback_stop:
+ state.status = 3
+ return True
+ if state.optimality < gtol and state.constr_violation < gtol:
+ state.status = 1
+ elif (state.tr_radius < xtol
+ and state.barrier_parameter < barrier_tol):
+ state.status = 2
+ elif state.nit >= maxiter:
+ state.status = 0
+ return state.status in (0, 1, 2, 3)
+
+ if verbose == 2:
+ BasicReport.print_header()
+ elif verbose > 2:
+ if method == 'equality_constrained_sqp':
+ SQPReport.print_header()
+ elif method == 'tr_interior_point':
+ IPReport.print_header()
+
+ # Call inferior function to do the optimization
+ if method == 'equality_constrained_sqp':
+ def fun_and_constr(x):
+ f = objective.fun(x)
+ c_eq, _ = canonical.fun(x)
+ return f, c_eq
+
+ def grad_and_jac(x):
+ g = objective.grad(x)
+ J_eq, _ = canonical.jac(x)
+ return g, J_eq
+
+ _, result = equality_constrained_sqp(
+ fun_and_constr, grad_and_jac, lagrangian_hess,
+ x0, objective.f, objective.g,
+ c_eq0, J_eq0,
+ stop_criteria, state,
+ initial_constr_penalty, initial_tr_radius,
+ factorization_method)
+
+ elif method == 'tr_interior_point':
+ _, result = tr_interior_point(
+ objective.fun, objective.grad, lagrangian_hess,
+ n_vars, canonical.n_ineq, canonical.n_eq,
+ canonical.fun, canonical.jac,
+ x0, objective.f, objective.g,
+ c_ineq0, J_ineq0, c_eq0, J_eq0,
+ stop_criteria,
+ canonical.keep_feasible,
+ xtol, state, initial_barrier_parameter,
+ initial_barrier_tolerance,
+ initial_constr_penalty, initial_tr_radius,
+ factorization_method, finite_diff_bounds)
+
+ # Status 4 occurs when minimize is successful but constraints are not satisfied.
+ if result.status in (1, 2) and state.constr_violation > gtol:
+ result.status = 4
+
+ # Status 3 occurs when the callback function requests termination,
+ # this is assumed to not be a success.
+ result.success = True if result.status in (1, 2) else False
+ result.message = TERMINATION_MESSAGES[result.status]
+
+ # Alias (for backward compatibility with 1.1.0)
+ result.niter = result.nit
+
+ if verbose == 2:
+ BasicReport.print_footer()
+ elif verbose > 2:
+ if method == 'equality_constrained_sqp':
+ SQPReport.print_footer()
+ elif method == 'tr_interior_point':
+ IPReport.print_footer()
+ if verbose >= 1:
+ print(result.message)
+ print(f"Number of iterations: {result.nit}, "
+ f"function evaluations: {result.nfev}, "
+ f"CG iterations: {result.cg_niter}, "
+ f"optimality: {result.optimality:.2e}, "
+ f"constraint violation: {result.constr_violation:.2e}, "
+ f"execution time: {result.execution_time:4.2} s.")
+ return result
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/projections.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..8425ba57f67dc702767c409bc6ee211b9daf3f9d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/projections.py
@@ -0,0 +1,411 @@
+"""Basic linear factorizations needed by the solver."""
+
+from scipy.sparse import block_array, csc_array, eye_array, issparse
+from scipy.sparse.linalg import LinearOperator
+import scipy.linalg
+import scipy.sparse.linalg
+try:
+ from sksparse.cholmod import cholesky_AAt, CholmodTypeConversionWarning
+ sksparse_available = True
+except ImportError:
+ import warnings
+ sksparse_available = False
+import numpy as np
+from warnings import warn, catch_warnings
+
+__all__ = [
+ 'orthogonality',
+ 'projections',
+]
+
+
+def orthogonality(A, g):
+ """Measure orthogonality between a vector and the null space of a matrix.
+
+ Compute a measure of orthogonality between the null space
+ of the (possibly sparse) matrix ``A`` and a given vector ``g``.
+
+ The formula is a simplified (and cheaper) version of formula (3.13)
+ from [1]_.
+ ``orth = norm(A g, ord=2)/(norm(A, ord='fro')*norm(g, ord=2))``.
+
+ References
+ ----------
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
+ "On the solution of equality constrained quadratic
+ programming problems arising in optimization."
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
+ """
+ # Compute vector norms
+ norm_g = np.linalg.norm(g)
+ # Compute Froebnius norm of the matrix A
+ if issparse(A):
+ norm_A = scipy.sparse.linalg.norm(A, ord='fro')
+ else:
+ norm_A = np.linalg.norm(A, ord='fro')
+
+ # Check if norms are zero
+ if norm_g == 0 or norm_A == 0:
+ return 0
+
+ norm_A_g = np.linalg.norm(A.dot(g))
+ # Orthogonality measure
+ orth = norm_A_g / (norm_A*norm_g)
+ return orth
+
+
+def normal_equation_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A using ``NormalEquation`` approach.
+ """
+ # Cholesky factorization
+ # TODO: revert this once the warning bug fix in sksparse is merged/released
+ # Add suppression of spurious warning bug from sksparse with csc_array gh-22089
+ # factor = cholesky_AAt(A)
+ with catch_warnings(action='ignore', category=CholmodTypeConversionWarning):
+ factor = cholesky_AAt(A)
+
+ # z = x - A.T inv(A A.T) A x
+ def null_space(x):
+ v = factor(A.dot(x))
+ z = x - A.T.dot(v)
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.1.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # z_next = z - A.T inv(A A.T) A z
+ v = factor(A.dot(z))
+ z = z - A.T.dot(v)
+ k += 1
+
+ return z
+
+ # z = inv(A A.T) A x
+ def least_squares(x):
+ return factor(A.dot(x))
+
+ # z = A.T inv(A A.T) x
+ def row_space(x):
+ return A.T.dot(factor(x))
+
+ return null_space, least_squares, row_space
+
+
+def augmented_system_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A - ``AugmentedSystem``."""
+ # Form augmented system
+ K = block_array([[eye_array(n), A.T], [A, None]], format="csc")
+ # LU factorization
+ # TODO: Use a symmetric indefinite factorization
+ # to solve the system twice as fast (because
+ # of the symmetry).
+ try:
+ solve = scipy.sparse.linalg.factorized(K)
+ except RuntimeError:
+ warn("Singular Jacobian matrix. Using dense SVD decomposition to "
+ "perform the factorizations.",
+ stacklevel=3)
+ return svd_factorization_projections(A.toarray(),
+ m, n, orth_tol,
+ max_refin, tol)
+
+ # z = x - A.T inv(A A.T) A x
+ # is computed solving the extended system:
+ # [I A.T] * [ z ] = [x]
+ # [A O ] [aux] [0]
+ def null_space(x):
+ # v = [x]
+ # [0]
+ v = np.hstack([x, np.zeros(m)])
+ # lu_sol = [ z ]
+ # [aux]
+ lu_sol = solve(v)
+ z = lu_sol[:n]
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.2.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # new_v = [x] - [I A.T] * [ z ]
+ # [0] [A O ] [aux]
+ new_v = v - K.dot(lu_sol)
+ # [I A.T] * [delta z ] = new_v
+ # [A O ] [delta aux]
+ lu_update = solve(new_v)
+ # [ z ] += [delta z ]
+ # [aux] [delta aux]
+ lu_sol += lu_update
+ z = lu_sol[:n]
+ k += 1
+
+ # return z = x - A.T inv(A A.T) A x
+ return z
+
+ # z = inv(A A.T) A x
+ # is computed solving the extended system:
+ # [I A.T] * [aux] = [x]
+ # [A O ] [ z ] [0]
+ def least_squares(x):
+ # v = [x]
+ # [0]
+ v = np.hstack([x, np.zeros(m)])
+ # lu_sol = [aux]
+ # [ z ]
+ lu_sol = solve(v)
+ # return z = inv(A A.T) A x
+ return lu_sol[n:m+n]
+
+ # z = A.T inv(A A.T) x
+ # is computed solving the extended system:
+ # [I A.T] * [ z ] = [0]
+ # [A O ] [aux] [x]
+ def row_space(x):
+ # v = [0]
+ # [x]
+ v = np.hstack([np.zeros(n), x])
+ # lu_sol = [ z ]
+ # [aux]
+ lu_sol = solve(v)
+ # return z = A.T inv(A A.T) x
+ return lu_sol[:n]
+
+ return null_space, least_squares, row_space
+
+
+def qr_factorization_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A using ``QRFactorization`` approach.
+ """
+ # QRFactorization
+ Q, R, P = scipy.linalg.qr(A.T, pivoting=True, mode='economic')
+
+ if np.linalg.norm(R[-1, :], np.inf) < tol:
+ warn('Singular Jacobian matrix. Using SVD decomposition to ' +
+ 'perform the factorizations.',
+ stacklevel=3)
+ return svd_factorization_projections(A, m, n,
+ orth_tol,
+ max_refin,
+ tol)
+
+ # z = x - A.T inv(A A.T) A x
+ def null_space(x):
+ # v = P inv(R) Q.T x
+ aux1 = Q.T.dot(x)
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
+ v = np.zeros(m)
+ v[P] = aux2
+ z = x - A.T.dot(v)
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.1.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # v = P inv(R) Q.T x
+ aux1 = Q.T.dot(z)
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
+ v[P] = aux2
+ # z_next = z - A.T v
+ z = z - A.T.dot(v)
+ k += 1
+
+ return z
+
+ # z = inv(A A.T) A x
+ def least_squares(x):
+ # z = P inv(R) Q.T x
+ aux1 = Q.T.dot(x)
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
+ z = np.zeros(m)
+ z[P] = aux2
+ return z
+
+ # z = A.T inv(A A.T) x
+ def row_space(x):
+ # z = Q inv(R.T) P.T x
+ aux1 = x[P]
+ aux2 = scipy.linalg.solve_triangular(R, aux1,
+ lower=False,
+ trans='T')
+ z = Q.dot(aux2)
+ return z
+
+ return null_space, least_squares, row_space
+
+
+def svd_factorization_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A using ``SVDFactorization`` approach.
+ """
+ # SVD Factorization
+ U, s, Vt = scipy.linalg.svd(A, full_matrices=False)
+
+ # Remove dimensions related with very small singular values
+ U = U[:, s > tol]
+ Vt = Vt[s > tol, :]
+ s = s[s > tol]
+
+ # z = x - A.T inv(A A.T) A x
+ def null_space(x):
+ # v = U 1/s V.T x = inv(A A.T) A x
+ aux1 = Vt.dot(x)
+ aux2 = 1/s*aux1
+ v = U.dot(aux2)
+ z = x - A.T.dot(v)
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.1.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # v = U 1/s V.T x = inv(A A.T) A x
+ aux1 = Vt.dot(z)
+ aux2 = 1/s*aux1
+ v = U.dot(aux2)
+ # z_next = z - A.T v
+ z = z - A.T.dot(v)
+ k += 1
+
+ return z
+
+ # z = inv(A A.T) A x
+ def least_squares(x):
+ # z = U 1/s V.T x = inv(A A.T) A x
+ aux1 = Vt.dot(x)
+ aux2 = 1/s*aux1
+ z = U.dot(aux2)
+ return z
+
+ # z = A.T inv(A A.T) x
+ def row_space(x):
+ # z = V 1/s U.T x
+ aux1 = U.T.dot(x)
+ aux2 = 1/s*aux1
+ z = Vt.T.dot(aux2)
+ return z
+
+ return null_space, least_squares, row_space
+
+
+def projections(A, method=None, orth_tol=1e-12, max_refin=3, tol=1e-15):
+ """Return three linear operators related with a given matrix A.
+
+ Parameters
+ ----------
+ A : sparse array (or ndarray), shape (m, n)
+ Matrix ``A`` used in the projection.
+ method : str, optional
+ Method used for compute the given linear
+ operators. Should be one of:
+
+ - 'NormalEquation': The operators
+ will be computed using the
+ so-called normal equation approach
+ explained in [1]_. In order to do
+ so the Cholesky factorization of
+ ``(A A.T)`` is computed. Exclusive
+ for sparse matrices.
+ - 'AugmentedSystem': The operators
+ will be computed using the
+ so-called augmented system approach
+ explained in [1]_. Exclusive
+ for sparse matrices.
+ - 'QRFactorization': Compute projections
+ using QR factorization. Exclusive for
+ dense matrices.
+ - 'SVDFactorization': Compute projections
+ using SVD factorization. Exclusive for
+ dense matrices.
+
+ orth_tol : float, optional
+ Tolerance for iterative refinements.
+ max_refin : int, optional
+ Maximum number of iterative refinements.
+ tol : float, optional
+ Tolerance for singular values.
+
+ Returns
+ -------
+ Z : LinearOperator, shape (n, n)
+ Null-space operator. For a given vector ``x``,
+ the null space operator is equivalent to apply
+ a projection matrix ``P = I - A.T inv(A A.T) A``
+ to the vector. It can be shown that this is
+ equivalent to project ``x`` into the null space
+ of A.
+ LS : LinearOperator, shape (m, n)
+ Least-squares operator. For a given vector ``x``,
+ the least-squares operator is equivalent to apply a
+ pseudoinverse matrix ``pinv(A.T) = inv(A A.T) A``
+ to the vector. It can be shown that this vector
+ ``pinv(A.T) x`` is the least_square solution to
+ ``A.T y = x``.
+ Y : LinearOperator, shape (n, m)
+ Row-space operator. For a given vector ``x``,
+ the row-space operator is equivalent to apply a
+ projection matrix ``Q = A.T inv(A A.T)``
+ to the vector. It can be shown that this
+ vector ``y = Q x`` the minimum norm solution
+ of ``A y = x``.
+
+ Notes
+ -----
+ Uses iterative refinements described in [1]
+ during the computation of ``Z`` in order to
+ cope with the possibility of large roundoff errors.
+
+ References
+ ----------
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
+ "On the solution of equality constrained quadratic
+ programming problems arising in optimization."
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
+ """
+ m, n = np.shape(A)
+
+ # The factorization of an empty matrix
+ # only works for the sparse representation.
+ if m*n == 0:
+ A = csc_array(A)
+
+ # Check Argument
+ if issparse(A):
+ if method is None:
+ method = "AugmentedSystem"
+ if method not in ("NormalEquation", "AugmentedSystem"):
+ raise ValueError("Method not allowed for sparse array.")
+ if method == "NormalEquation" and not sksparse_available:
+ warnings.warn("Only accepts 'NormalEquation' option when "
+ "scikit-sparse is available. Using "
+ "'AugmentedSystem' option instead.",
+ ImportWarning, stacklevel=3)
+ method = 'AugmentedSystem'
+ else:
+ if method is None:
+ method = "QRFactorization"
+ if method not in ("QRFactorization", "SVDFactorization"):
+ raise ValueError("Method not allowed for dense array.")
+
+ if method == 'NormalEquation':
+ null_space, least_squares, row_space \
+ = normal_equation_projections(A, m, n, orth_tol, max_refin, tol)
+ elif method == 'AugmentedSystem':
+ null_space, least_squares, row_space \
+ = augmented_system_projections(A, m, n, orth_tol, max_refin, tol)
+ elif method == "QRFactorization":
+ null_space, least_squares, row_space \
+ = qr_factorization_projections(A, m, n, orth_tol, max_refin, tol)
+ elif method == "SVDFactorization":
+ null_space, least_squares, row_space \
+ = svd_factorization_projections(A, m, n, orth_tol, max_refin, tol)
+
+ Z = LinearOperator((n, n), null_space)
+ LS = LinearOperator((m, n), least_squares)
+ Y = LinearOperator((n, m), row_space)
+
+ return Z, LS, Y
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae74910d3fc55808e846263faf5d90127534b8d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py
@@ -0,0 +1,637 @@
+"""Equality-constrained quadratic programming solvers."""
+
+from scipy.sparse import linalg, block_array
+from math import copysign
+import numpy as np
+from numpy.linalg import norm
+
+__all__ = [
+ 'eqp_kktfact',
+ 'sphere_intersections',
+ 'box_intersections',
+ 'box_sphere_intersections',
+ 'inside_box_boundaries',
+ 'modified_dogleg',
+ 'projected_cg'
+]
+
+
+# For comparison with the projected CG
+def eqp_kktfact(H, c, A, b):
+ """Solve equality-constrained quadratic programming (EQP) problem.
+
+ Solve ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0``
+ using direct factorization of the KKT system.
+
+ Parameters
+ ----------
+ H : sparse array, shape (n, n)
+ Hessian matrix of the EQP problem.
+ c : array_like, shape (n,)
+ Gradient of the quadratic objective function.
+ A : sparse array
+ Jacobian matrix of the EQP problem.
+ b : array_like, shape (m,)
+ Right-hand side of the constraint equation.
+
+ Returns
+ -------
+ x : array_like, shape (n,)
+ Solution of the KKT problem.
+ lagrange_multipliers : ndarray, shape (m,)
+ Lagrange multipliers of the KKT problem.
+ """
+ n, = np.shape(c) # Number of parameters
+ m, = np.shape(b) # Number of constraints
+
+ # Karush-Kuhn-Tucker matrix of coefficients.
+ # Defined as in Nocedal/Wright "Numerical
+ # Optimization" p.452 in Eq. (16.4).
+ kkt_matrix = block_array([[H, A.T], [A, None]], format="csc")
+ # Vector of coefficients.
+ kkt_vec = np.hstack([-c, -b])
+
+ # TODO: Use a symmetric indefinite factorization
+ # to solve the system twice as fast (because
+ # of the symmetry).
+ lu = linalg.splu(kkt_matrix)
+ kkt_sol = lu.solve(kkt_vec)
+ x = kkt_sol[:n]
+ lagrange_multipliers = -kkt_sol[n:n+m]
+
+ return x, lagrange_multipliers
+
+
+def sphere_intersections(z, d, trust_radius,
+ entire_line=False):
+ """Find the intersection between segment (or line) and spherical constraints.
+
+ Find the intersection between the segment (or line) defined by the
+ parametric equation ``x(t) = z + t*d`` and the ball
+ ``||x|| <= trust_radius``.
+
+ Parameters
+ ----------
+ z : array_like, shape (n,)
+ Initial point.
+ d : array_like, shape (n,)
+ Direction.
+ trust_radius : float
+ Ball radius.
+ entire_line : bool, optional
+ When ``True``, the function returns the intersection between the line
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the ball
+ ``||x|| <= trust_radius``. When ``False``, the function returns the intersection
+ between the segment ``x(t) = z + t*d``, ``0 <= t <= 1``, and the ball.
+
+ Returns
+ -------
+ ta, tb : float
+ The line/segment ``x(t) = z + t*d`` is inside the ball for
+ for ``ta <= t <= tb``.
+ intersect : bool
+ When ``True``, there is an intersection between the line/segment
+ and the sphere. On the other hand, when ``False``, there is no
+ intersection.
+ """
+ # Special case when d=0
+ if norm(d) == 0:
+ return 0, 0, False
+ # Check for inf trust_radius
+ if np.isinf(trust_radius):
+ if entire_line:
+ ta = -np.inf
+ tb = np.inf
+ else:
+ ta = 0
+ tb = 1
+ intersect = True
+ return ta, tb, intersect
+
+ a = np.dot(d, d)
+ b = 2 * np.dot(z, d)
+ c = np.dot(z, z) - trust_radius**2
+ discriminant = b*b - 4*a*c
+ if discriminant < 0:
+ intersect = False
+ return 0, 0, intersect
+ sqrt_discriminant = np.sqrt(discriminant)
+
+ # The following calculation is mathematically
+ # equivalent to:
+ # ta = (-b - sqrt_discriminant) / (2*a)
+ # tb = (-b + sqrt_discriminant) / (2*a)
+ # but produce smaller round off errors.
+ # Look at Matrix Computation p.97
+ # for a better justification.
+ aux = b + copysign(sqrt_discriminant, b)
+ ta = -aux / (2*a)
+ tb = -2*c / aux
+ ta, tb = sorted([ta, tb])
+
+ if entire_line:
+ intersect = True
+ else:
+ # Checks to see if intersection happens
+ # within vectors length.
+ if tb < 0 or ta > 1:
+ intersect = False
+ ta = 0
+ tb = 0
+ else:
+ intersect = True
+ # Restrict intersection interval
+ # between 0 and 1.
+ ta = max(0, ta)
+ tb = min(1, tb)
+
+ return ta, tb, intersect
+
+
+def box_intersections(z, d, lb, ub,
+ entire_line=False):
+ """Find the intersection between segment (or line) and box constraints.
+
+ Find the intersection between the segment (or line) defined by the
+ parametric equation ``x(t) = z + t*d`` and the rectangular box
+ ``lb <= x <= ub``.
+
+ Parameters
+ ----------
+ z : array_like, shape (n,)
+ Initial point.
+ d : array_like, shape (n,)
+ Direction.
+ lb : array_like, shape (n,)
+ Lower bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ ub : array_like, shape (n, )
+ Upper bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ entire_line : bool, optional
+ When ``True``, the function returns the intersection between the line
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the rectangular
+ box. When ``False``, the function returns the intersection between the segment
+ ``x(t) = z + t*d``, ``0 <= t <= 1``, and the rectangular box.
+
+ Returns
+ -------
+ ta, tb : float
+ The line/segment ``x(t) = z + t*d`` is inside the box for
+ for ``ta <= t <= tb``.
+ intersect : bool
+ When ``True``, there is an intersection between the line (or segment)
+ and the rectangular box. On the other hand, when ``False``, there is no
+ intersection.
+ """
+ # Make sure it is a numpy array
+ z = np.asarray(z)
+ d = np.asarray(d)
+ lb = np.asarray(lb)
+ ub = np.asarray(ub)
+ # Special case when d=0
+ if norm(d) == 0:
+ return 0, 0, False
+
+ # Get values for which d==0
+ zero_d = (d == 0)
+ # If the boundaries are not satisfied for some coordinate
+ # for which "d" is zero, there is no box-line intersection.
+ if (z[zero_d] < lb[zero_d]).any() or (z[zero_d] > ub[zero_d]).any():
+ intersect = False
+ return 0, 0, intersect
+ # Remove values for which d is zero
+ not_zero_d = np.logical_not(zero_d)
+ z = z[not_zero_d]
+ d = d[not_zero_d]
+ lb = lb[not_zero_d]
+ ub = ub[not_zero_d]
+
+ # Find a series of intervals (t_lb[i], t_ub[i]).
+ t_lb = (lb-z) / d
+ t_ub = (ub-z) / d
+ # Get the intersection of all those intervals.
+ ta = max(np.minimum(t_lb, t_ub))
+ tb = min(np.maximum(t_lb, t_ub))
+
+ # Check if intersection is feasible
+ if ta <= tb:
+ intersect = True
+ else:
+ intersect = False
+ # Checks to see if intersection happens within vectors length.
+ if not entire_line:
+ if tb < 0 or ta > 1:
+ intersect = False
+ ta = 0
+ tb = 0
+ else:
+ # Restrict intersection interval between 0 and 1.
+ ta = max(0, ta)
+ tb = min(1, tb)
+
+ return ta, tb, intersect
+
+
+def box_sphere_intersections(z, d, lb, ub, trust_radius,
+ entire_line=False,
+ extra_info=False):
+ """Find the intersection between segment (or line) and box/sphere constraints.
+
+ Find the intersection between the segment (or line) defined by the
+ parametric equation ``x(t) = z + t*d``, the rectangular box
+ ``lb <= x <= ub`` and the ball ``||x|| <= trust_radius``.
+
+ Parameters
+ ----------
+ z : array_like, shape (n,)
+ Initial point.
+ d : array_like, shape (n,)
+ Direction.
+ lb : array_like, shape (n,)
+ Lower bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ ub : array_like, shape (n, )
+ Upper bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ trust_radius : float
+ Ball radius.
+ entire_line : bool, optional
+ When ``True``, the function returns the intersection between the line
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the constraints.
+ When ``False``, the function returns the intersection between the segment
+ ``x(t) = z + t*d``, ``0 <= t <= 1`` and the constraints.
+ extra_info : bool, optional
+ When ``True``, the function returns ``intersect_sphere`` and ``intersect_box``.
+
+ Returns
+ -------
+ ta, tb : float
+ The line/segment ``x(t) = z + t*d`` is inside the rectangular box and
+ inside the ball for ``ta <= t <= tb``.
+ intersect : bool
+ When ``True``, there is an intersection between the line (or segment)
+ and both constraints. On the other hand, when ``False``, there is no
+ intersection.
+ sphere_info : dict, optional
+ Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]``
+ for which the line intercepts the ball. And a boolean value indicating
+ whether the sphere is intersected by the line.
+ box_info : dict, optional
+ Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]``
+ for which the line intercepts the box. And a boolean value indicating
+ whether the box is intersected by the line.
+ """
+ ta_b, tb_b, intersect_b = box_intersections(z, d, lb, ub,
+ entire_line)
+ ta_s, tb_s, intersect_s = sphere_intersections(z, d,
+ trust_radius,
+ entire_line)
+ ta = np.maximum(ta_b, ta_s)
+ tb = np.minimum(tb_b, tb_s)
+ if intersect_b and intersect_s and ta <= tb:
+ intersect = True
+ else:
+ intersect = False
+
+ if extra_info:
+ sphere_info = {'ta': ta_s, 'tb': tb_s, 'intersect': intersect_s}
+ box_info = {'ta': ta_b, 'tb': tb_b, 'intersect': intersect_b}
+ return ta, tb, intersect, sphere_info, box_info
+ else:
+ return ta, tb, intersect
+
+
+def inside_box_boundaries(x, lb, ub):
+ """Check if lb <= x <= ub."""
+ return (lb <= x).all() and (x <= ub).all()
+
+
+def reinforce_box_boundaries(x, lb, ub):
+ """Return clipped value of x"""
+ return np.minimum(np.maximum(x, lb), ub)
+
+
+def modified_dogleg(A, Y, b, trust_radius, lb, ub):
+ """Approximately minimize ``1/2*|| A x + b ||^2`` inside trust-region.
+
+ Approximately solve the problem of minimizing ``1/2*|| A x + b ||^2``
+ subject to ``||x|| < Delta`` and ``lb <= x <= ub`` using a modification
+ of the classical dogleg approach.
+
+ Parameters
+ ----------
+ A : LinearOperator (or sparse array or ndarray), shape (m, n)
+ Matrix ``A`` in the minimization problem. It should have
+ dimension ``(m, n)`` such that ``m < n``.
+ Y : LinearOperator (or sparse array or ndarray), shape (n, m)
+ LinearOperator that apply the projection matrix
+ ``Q = A.T inv(A A.T)`` to the vector. The obtained vector
+ ``y = Q x`` being the minimum norm solution of ``A y = x``.
+ b : array_like, shape (m,)
+ Vector ``b``in the minimization problem.
+ trust_radius: float
+ Trust radius to be considered. Delimits a sphere boundary
+ to the problem.
+ lb : array_like, shape (n,)
+ Lower bounds to each one of the components of ``x``.
+ It is expected that ``lb <= 0``, otherwise the algorithm
+ may fail. If ``lb[i] = -Inf``, the lower
+ bound for the ith component is just ignored.
+ ub : array_like, shape (n, )
+ Upper bounds to each one of the components of ``x``.
+ It is expected that ``ub >= 0``, otherwise the algorithm
+ may fail. If ``ub[i] = Inf``, the upper bound for the ith
+ component is just ignored.
+
+ Returns
+ -------
+ x : array_like, shape (n,)
+ Solution to the problem.
+
+ Notes
+ -----
+ Based on implementations described in pp. 885-886 from [1]_.
+
+ References
+ ----------
+ .. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
+ "An interior point algorithm for large-scale nonlinear
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
+ """
+ # Compute minimum norm minimizer of 1/2*|| A x + b ||^2.
+ newton_point = -Y.dot(b)
+ # Check for interior point
+ if inside_box_boundaries(newton_point, lb, ub) \
+ and norm(newton_point) <= trust_radius:
+ x = newton_point
+ return x
+
+ # Compute gradient vector ``g = A.T b``
+ g = A.T.dot(b)
+ # Compute Cauchy point
+ # `cauchy_point = g.T g / (g.T A.T A g)``.
+ A_g = A.dot(g)
+ cauchy_point = -np.dot(g, g) / np.dot(A_g, A_g) * g
+ # Origin
+ origin_point = np.zeros_like(cauchy_point)
+
+ # Check the segment between cauchy_point and newton_point
+ # for a possible solution.
+ z = cauchy_point
+ p = newton_point - cauchy_point
+ _, alpha, intersect = box_sphere_intersections(z, p, lb, ub,
+ trust_radius)
+ if intersect:
+ x1 = z + alpha*p
+ else:
+ # Check the segment between the origin and cauchy_point
+ # for a possible solution.
+ z = origin_point
+ p = cauchy_point
+ _, alpha, _ = box_sphere_intersections(z, p, lb, ub,
+ trust_radius)
+ x1 = z + alpha*p
+
+ # Check the segment between origin and newton_point
+ # for a possible solution.
+ z = origin_point
+ p = newton_point
+ _, alpha, _ = box_sphere_intersections(z, p, lb, ub,
+ trust_radius)
+ x2 = z + alpha*p
+
+ # Return the best solution among x1 and x2.
+ if norm(A.dot(x1) + b) < norm(A.dot(x2) + b):
+ return x1
+ else:
+ return x2
+
+
+def projected_cg(H, c, Z, Y, b, trust_radius=np.inf,
+ lb=None, ub=None, tol=None,
+ max_iter=None, max_infeasible_iter=None,
+ return_all=False):
+ """Solve EQP problem with projected CG method.
+
+ Solve equality-constrained quadratic programming problem
+ ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` and,
+ possibly, to trust region constraints ``||x|| < trust_radius``
+ and box constraints ``lb <= x <= ub``.
+
+ Parameters
+ ----------
+ H : LinearOperator (or sparse array or ndarray), shape (n, n)
+ Operator for computing ``H v``.
+ c : array_like, shape (n,)
+ Gradient of the quadratic objective function.
+ Z : LinearOperator (or sparse array or ndarray), shape (n, n)
+ Operator for projecting ``x`` into the null space of A.
+ Y : LinearOperator, sparse array, ndarray, shape (n, m)
+ Operator that, for a given a vector ``b``, compute smallest
+ norm solution of ``A x + b = 0``.
+ b : array_like, shape (m,)
+ Right-hand side of the constraint equation.
+ trust_radius : float, optional
+ Trust radius to be considered. By default, uses ``trust_radius=inf``,
+ which means no trust radius at all.
+ lb : array_like, shape (n,), optional
+ Lower bounds to each one of the components of ``x``.
+ If ``lb[i] = -Inf`` the lower bound for the i-th
+ component is just ignored (default).
+ ub : array_like, shape (n, ), optional
+ Upper bounds to each one of the components of ``x``.
+ If ``ub[i] = Inf`` the upper bound for the i-th
+ component is just ignored (default).
+ tol : float, optional
+ Tolerance used to interrupt the algorithm.
+ max_iter : int, optional
+ Maximum algorithm iterations. Where ``max_inter <= n-m``.
+ By default, uses ``max_iter = n-m``.
+ max_infeasible_iter : int, optional
+ Maximum infeasible (regarding box constraints) iterations the
+ algorithm is allowed to take.
+ By default, uses ``max_infeasible_iter = n-m``.
+ return_all : bool, optional
+ When ``true``, return the list of all vectors through the iterations.
+
+ Returns
+ -------
+ x : array_like, shape (n,)
+ Solution of the EQP problem.
+ info : dict
+ Dictionary containing the following:
+
+ - niter : Number of iterations.
+ - stop_cond : Reason for algorithm termination:
+ 1. Iteration limit was reached;
+ 2. Reached the trust-region boundary;
+ 3. Negative curvature detected;
+ 4. Tolerance was satisfied.
+ - allvecs : List containing all intermediary vectors (optional).
+ - hits_boundary : True if the proposed step is on the boundary
+ of the trust region.
+
+ Notes
+ -----
+ Implementation of Algorithm 6.2 on [1]_.
+
+ In the absence of spherical and box constraints, for sufficient
+ iterations, the method returns a truly optimal result.
+ In the presence of those constraints, the value returned is only
+ an inexpensive approximation of the optimal value.
+
+ References
+ ----------
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
+ "On the solution of equality constrained quadratic
+ programming problems arising in optimization."
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
+ """
+ CLOSE_TO_ZERO = 1e-25
+
+ n, = np.shape(c) # Number of parameters
+ m, = np.shape(b) # Number of constraints
+
+ # Initial Values
+ x = Y.dot(-b)
+ r = Z.dot(H.dot(x) + c)
+ g = Z.dot(r)
+ p = -g
+
+ # Store ``x`` value
+ if return_all:
+ allvecs = [x]
+ # Values for the first iteration
+ H_p = H.dot(p)
+ rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
+
+ # If x > trust-region the problem does not have a solution.
+ tr_distance = trust_radius - norm(x)
+ if tr_distance < 0:
+ raise ValueError("Trust region problem does not have a solution.")
+ # If x == trust_radius, then x is the solution
+ # to the optimization problem, since x is the
+ # minimum norm solution to Ax=b.
+ elif tr_distance < CLOSE_TO_ZERO:
+ info = {'niter': 0, 'stop_cond': 2, 'hits_boundary': True}
+ if return_all:
+ allvecs.append(x)
+ info['allvecs'] = allvecs
+ return x, info
+
+ # Set default tolerance
+ if tol is None:
+ tol = max(min(0.01 * np.sqrt(rt_g), 0.1 * rt_g), CLOSE_TO_ZERO)
+ # Set default lower and upper bounds
+ if lb is None:
+ lb = np.full(n, -np.inf)
+ if ub is None:
+ ub = np.full(n, np.inf)
+ # Set maximum iterations
+ if max_iter is None:
+ max_iter = n-m
+ max_iter = min(max_iter, n-m)
+ # Set maximum infeasible iterations
+ if max_infeasible_iter is None:
+ max_infeasible_iter = n-m
+
+ hits_boundary = False
+ stop_cond = 1
+ counter = 0
+ last_feasible_x = np.zeros_like(x)
+ k = 0
+ for i in range(max_iter):
+ # Stop criteria - Tolerance : r.T g < tol
+ if rt_g < tol:
+ stop_cond = 4
+ break
+ k += 1
+ # Compute curvature
+ pt_H_p = H_p.dot(p)
+ # Stop criteria - Negative curvature
+ if pt_H_p <= 0:
+ if np.isinf(trust_radius):
+ raise ValueError("Negative curvature not allowed "
+ "for unrestricted problems.")
+ else:
+ # Find intersection with constraints
+ _, alpha, intersect = box_sphere_intersections(
+ x, p, lb, ub, trust_radius, entire_line=True)
+ # Update solution
+ if intersect:
+ x = x + alpha*p
+ # Reinforce variables are inside box constraints.
+ # This is only necessary because of roundoff errors.
+ x = reinforce_box_boundaries(x, lb, ub)
+ # Attribute information
+ stop_cond = 3
+ hits_boundary = True
+ break
+
+ # Get next step
+ alpha = rt_g / pt_H_p
+ x_next = x + alpha*p
+
+ # Stop criteria - Hits boundary
+ if np.linalg.norm(x_next) >= trust_radius:
+ # Find intersection with box constraints
+ _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
+ trust_radius)
+ # Update solution
+ if intersect:
+ x = x + theta*alpha*p
+ # Reinforce variables are inside box constraints.
+ # This is only necessary because of roundoff errors.
+ x = reinforce_box_boundaries(x, lb, ub)
+ # Attribute information
+ stop_cond = 2
+ hits_boundary = True
+ break
+
+ # Check if ``x`` is inside the box and start counter if it is not.
+ if inside_box_boundaries(x_next, lb, ub):
+ counter = 0
+ else:
+ counter += 1
+ # Whenever outside box constraints keep looking for intersections.
+ if counter > 0:
+ _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
+ trust_radius)
+ if intersect:
+ last_feasible_x = x + theta*alpha*p
+ # Reinforce variables are inside box constraints.
+ # This is only necessary because of roundoff errors.
+ last_feasible_x = reinforce_box_boundaries(last_feasible_x,
+ lb, ub)
+ counter = 0
+ # Stop after too many infeasible (regarding box constraints) iteration.
+ if counter > max_infeasible_iter:
+ break
+ # Store ``x_next`` value
+ if return_all:
+ allvecs.append(x_next)
+
+ # Update residual
+ r_next = r + alpha*H_p
+ # Project residual g+ = Z r+
+ g_next = Z.dot(r_next)
+ # Compute conjugate direction step d
+ rt_g_next = norm(g_next)**2 # g.T g = r.T g (ref [1]_ p.1389)
+ beta = rt_g_next / rt_g
+ p = - g_next + beta*p
+ # Prepare for next iteration
+ x = x_next
+ g = g_next
+ r = g_next
+ rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
+ H_p = H.dot(p)
+
+ if not inside_box_boundaries(x, lb, ub):
+ x = last_feasible_x
+ hits_boundary = True
+ info = {'niter': k, 'stop_cond': stop_cond,
+ 'hits_boundary': hits_boundary}
+ if return_all:
+ info['allvecs'] = allvecs
+ return x, info
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/report.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/report.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7f997d663cd5ce6265e77f940622b6105362bf7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/report.py
@@ -0,0 +1,49 @@
+"""Progress report printers."""
+
+class ReportBase:
+ COLUMN_NAMES: list[str] = NotImplemented
+ COLUMN_WIDTHS: list[int] = NotImplemented
+ ITERATION_FORMATS: list[str] = NotImplemented
+
+ @classmethod
+ def print_header(cls):
+ fmt = ("|"
+ + "|".join([f"{{:^{x}}}" for x in cls.COLUMN_WIDTHS])
+ + "|")
+ separators = ['-' * x for x in cls.COLUMN_WIDTHS]
+ print(fmt.format(*cls.COLUMN_NAMES))
+ print(fmt.format(*separators))
+
+ @classmethod
+ def print_iteration(cls, *args):
+ iteration_format = [f"{{:{x}}}" for x in cls.ITERATION_FORMATS]
+ fmt = "|" + "|".join(iteration_format) + "|"
+ print(fmt.format(*args))
+
+ @classmethod
+ def print_footer(cls):
+ print()
+
+
+class BasicReport(ReportBase):
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
+ "opt", "c viol"]
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10]
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e",
+ "^10.2e", "^10.2e", "^10.2e"]
+
+
+class SQPReport(ReportBase):
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
+ "opt", "c viol", "penalty", "CG stop"]
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 7]
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e",
+ "^10.2e", "^10.2e", "^7"]
+
+
+class IPReport(ReportBase):
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
+ "opt", "c viol", "penalty", "barrier param", "CG stop"]
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 13, 7]
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e",
+ "^10.2e", "^10.2e", "^13.2e", "^7"]
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..452b327d02da3b3bd3fab9592bdef4d56d6aff57
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py
@@ -0,0 +1,296 @@
+import numpy as np
+from numpy.testing import assert_array_equal, assert_equal
+from scipy.optimize._constraints import (NonlinearConstraint, Bounds,
+ PreparedConstraint)
+from scipy.optimize._trustregion_constr.canonical_constraint \
+ import CanonicalConstraint, initial_constraints_as_canonical
+
+
+def create_quadratic_function(n, m, rng):
+ a = rng.rand(m)
+ A = rng.rand(m, n)
+ H = rng.rand(m, n, n)
+ HT = np.transpose(H, (1, 2, 0))
+
+ def fun(x):
+ return a + A.dot(x) + 0.5 * H.dot(x).dot(x)
+
+ def jac(x):
+ return A + H.dot(x)
+
+ def hess(x, v):
+ return HT.dot(v)
+
+ return fun, jac, hess
+
+
+def test_bounds_cases():
+ # Test 1: no constraints.
+ user_constraint = Bounds(-np.inf, np.inf)
+ x0 = np.array([-1, 2])
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 0)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, np.empty((0, 2)))
+ assert_array_equal(J_ineq, np.empty((0, 2)))
+
+ assert_array_equal(c.keep_feasible, [])
+
+ # Test 2: infinite lower bound.
+ user_constraint = Bounds(-np.inf, [0, np.inf, 1], [False, True, True])
+ x0 = np.array([-1, -2, -3], dtype=float)
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 2)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [-1, -4])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, np.empty((0, 3)))
+ assert_array_equal(J_ineq, np.array([[1, 0, 0], [0, 0, 1]]))
+
+ assert_array_equal(c.keep_feasible, [False, True])
+
+ # Test 3: infinite upper bound.
+ user_constraint = Bounds([0, 1, -np.inf], np.inf, [True, False, True])
+ x0 = np.array([1, 2, 3], dtype=float)
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 2)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [-1, -1])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, np.empty((0, 3)))
+ assert_array_equal(J_ineq, np.array([[-1, 0, 0], [0, -1, 0]]))
+
+ assert_array_equal(c.keep_feasible, [True, False])
+
+ # Test 4: interval constraint.
+ user_constraint = Bounds([-1, -np.inf, 2, 3], [1, np.inf, 10, 3],
+ [False, True, True, True])
+ x0 = np.array([0, 10, 8, 5])
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 1)
+ assert_equal(c.n_ineq, 4)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [2])
+ assert_array_equal(c_ineq, [-1, -2, -1, -6])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, [[0, 0, 0, 1]])
+ assert_array_equal(J_ineq, [[1, 0, 0, 0],
+ [0, 0, 1, 0],
+ [-1, 0, 0, 0],
+ [0, 0, -1, 0]])
+
+ assert_array_equal(c.keep_feasible, [False, True, False, True])
+
+
+def test_nonlinear_constraint():
+ n = 3
+ m = 5
+ rng = np.random.RandomState(0)
+ x0 = rng.rand(n)
+
+ fun, jac, hess = create_quadratic_function(n, m, rng)
+ f = fun(x0)
+ J = jac(x0)
+
+ lb = [-10, 3, -np.inf, -np.inf, -5]
+ ub = [10, 3, np.inf, 3, np.inf]
+ user_constraint = NonlinearConstraint(
+ fun, lb, ub, jac, hess, [True, False, False, True, False])
+
+ for sparse_jacobian in [False, True]:
+ prepared_constraint = PreparedConstraint(user_constraint, x0,
+ sparse_jacobian)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_array_equal(c.n_eq, 1)
+ assert_array_equal(c.n_ineq, 4)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [f[1] - lb[1]])
+ assert_array_equal(c_ineq, [f[3] - ub[3], lb[4] - f[4],
+ f[0] - ub[0], lb[0] - f[0]])
+
+ J_eq, J_ineq = c.jac(x0)
+ if sparse_jacobian:
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, J[1, None])
+ assert_array_equal(J_ineq, np.vstack((J[3], -J[4], J[0], -J[0])))
+
+ v_eq = rng.rand(c.n_eq)
+ v_ineq = rng.rand(c.n_ineq)
+ v = np.zeros(m)
+ v[1] = v_eq[0]
+ v[3] = v_ineq[0]
+ v[4] = -v_ineq[1]
+ v[0] = v_ineq[2] - v_ineq[3]
+ assert_array_equal(c.hess(x0, v_eq, v_ineq), hess(x0, v))
+
+ assert_array_equal(c.keep_feasible, [True, False, True, True])
+
+
+def test_concatenation():
+ rng = np.random.RandomState(0)
+ n = 4
+ x0 = rng.rand(n)
+
+ f1 = x0
+ J1 = np.eye(n)
+ lb1 = [-1, -np.inf, -2, 3]
+ ub1 = [1, np.inf, np.inf, 3]
+ bounds = Bounds(lb1, ub1, [False, False, True, False])
+
+ fun, jac, hess = create_quadratic_function(n, 5, rng)
+ f2 = fun(x0)
+ J2 = jac(x0)
+ lb2 = [-10, 3, -np.inf, -np.inf, -5]
+ ub2 = [10, 3, np.inf, 5, np.inf]
+ nonlinear = NonlinearConstraint(
+ fun, lb2, ub2, jac, hess, [True, False, False, True, False])
+
+ for sparse_jacobian in [False, True]:
+ bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian)
+ nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian)
+
+ c1 = CanonicalConstraint.from_PreparedConstraint(bounds_prepared)
+ c2 = CanonicalConstraint.from_PreparedConstraint(nonlinear_prepared)
+ c = CanonicalConstraint.concatenate([c1, c2], sparse_jacobian)
+
+ assert_equal(c.n_eq, 2)
+ assert_equal(c.n_ineq, 7)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]])
+ assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0],
+ lb1[0] - f1[0], f2[3] - ub2[3],
+ lb2[4] - f2[4], f2[0] - ub2[0],
+ lb2[0] - f2[0]])
+
+ J_eq, J_ineq = c.jac(x0)
+ if sparse_jacobian:
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, np.vstack((J1[3], J2[1])))
+ assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3],
+ -J2[4], J2[0], -J2[0])))
+
+ v_eq = rng.rand(c.n_eq)
+ v_ineq = rng.rand(c.n_ineq)
+ v = np.zeros(5)
+ v[1] = v_eq[1]
+ v[3] = v_ineq[3]
+ v[4] = -v_ineq[4]
+ v[0] = v_ineq[5] - v_ineq[6]
+ H = c.hess(x0, v_eq, v_ineq).dot(np.eye(n))
+ assert_array_equal(H, hess(x0, v))
+
+ assert_array_equal(c.keep_feasible,
+ [True, False, False, True, False, True, True])
+
+
+def test_empty():
+ x = np.array([1, 2, 3])
+ c = CanonicalConstraint.empty(3)
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 0)
+
+ c_eq, c_ineq = c.fun(x)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [])
+
+ J_eq, J_ineq = c.jac(x)
+ assert_array_equal(J_eq, np.empty((0, 3)))
+ assert_array_equal(J_ineq, np.empty((0, 3)))
+
+ H = c.hess(x, None, None).toarray()
+ assert_array_equal(H, np.zeros((3, 3)))
+
+
+def test_initial_constraints_as_canonical():
+ # rng is only used to generate the coefficients of the quadratic
+ # function that is used by the nonlinear constraint.
+ rng = np.random.RandomState(0)
+
+ x0 = np.array([0.5, 0.4, 0.3, 0.2])
+ n = len(x0)
+
+ lb1 = [-1, -np.inf, -2, 3]
+ ub1 = [1, np.inf, np.inf, 3]
+ bounds = Bounds(lb1, ub1, [False, False, True, False])
+
+ fun, jac, hess = create_quadratic_function(n, 5, rng)
+ lb2 = [-10, 3, -np.inf, -np.inf, -5]
+ ub2 = [10, 3, np.inf, 5, np.inf]
+ nonlinear = NonlinearConstraint(
+ fun, lb2, ub2, jac, hess, [True, False, False, True, False])
+
+ for sparse_jacobian in [False, True]:
+ bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian)
+ nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian)
+
+ f1 = bounds_prepared.fun.f
+ J1 = bounds_prepared.fun.J
+ f2 = nonlinear_prepared.fun.f
+ J2 = nonlinear_prepared.fun.J
+
+ c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical(
+ n, [bounds_prepared, nonlinear_prepared], sparse_jacobian)
+
+ assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]])
+ assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0],
+ lb1[0] - f1[0], f2[3] - ub2[3],
+ lb2[4] - f2[4], f2[0] - ub2[0],
+ lb2[0] - f2[0]])
+
+ if sparse_jacobian:
+ J1 = J1.toarray()
+ J2 = J2.toarray()
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, np.vstack((J1[3], J2[1])))
+ assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3],
+ -J2[4], J2[0], -J2[0])))
+
+
+def test_initial_constraints_as_canonical_empty():
+ n = 3
+ for sparse_jacobian in [False, True]:
+ c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical(
+ n, [], sparse_jacobian)
+
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [])
+
+ if sparse_jacobian:
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, np.empty((0, n)))
+ assert_array_equal(J_ineq, np.empty((0, n)))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9aa57058c6523d4106b26840ef447431d615cd6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py
@@ -0,0 +1,39 @@
+import pytest
+import numpy as np
+from scipy.optimize import minimize, NonlinearConstraint, rosen, rosen_der
+
+
+# Ignore this warning about inefficient use of Hessians
+# The bug only shows up with the default HUS
+@pytest.mark.filterwarnings(
+ "ignore:delta_grad == 0.0. Check if the approximated function is linear."
+)
+def test_gh21193():
+ # Test that nested minimization does not share Hessian objects
+ def identity(x):
+ return x[0]
+ def identity_jac(x):
+ a = np.zeros(len(x))
+ a[0] = 1
+ return a
+ constraint1 = NonlinearConstraint(identity, 0, 0, identity_jac)
+ constraint2 = NonlinearConstraint(identity, 0, 0, identity_jac)
+
+ # The default HUS for each should be distinct
+ assert constraint1.hess is not constraint2.hess
+
+ _ = minimize(
+ lambda x: minimize(
+ rosen,
+ x[1:],
+ jac=rosen_der,
+ constraints=constraint1,
+ method="trust-constr",
+ options={'maxiter': 2},
+ ).fun,
+ [1, 0, 0],
+ constraints=constraint2,
+ method="trust-constr",
+ options={'maxiter': 2},
+ )
+ # This test doesn't check that the output is correct, just that it doesn't crash
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8dd1f61ee0290212ff62d0ba1aca2bd87daf514
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py
@@ -0,0 +1,214 @@
+import numpy as np
+import scipy.linalg
+from scipy.sparse import csc_array
+from scipy.optimize._trustregion_constr.projections \
+ import projections, orthogonality
+from numpy.testing import (TestCase, assert_array_almost_equal,
+ assert_equal, assert_allclose)
+
+try:
+ from sksparse.cholmod import cholesky_AAt # noqa: F401
+ sksparse_available = True
+ available_sparse_methods = ("NormalEquation", "AugmentedSystem")
+except ImportError:
+ sksparse_available = False
+ available_sparse_methods = ("AugmentedSystem",)
+available_dense_methods = ('QRFactorization', 'SVDFactorization')
+
+
+class TestProjections(TestCase):
+
+ def test_nullspace_and_least_squares_sparse(self):
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ At_dense = A_dense.T
+ A = csc_array(A_dense)
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8])
+
+ for method in available_sparse_methods:
+ Z, LS, _ = projections(A, method)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ assert_array_almost_equal(A.dot(x), 0)
+ # Test orthogonality
+ assert_array_almost_equal(orthogonality(A, x), 0)
+ # Test if x is the least square solution
+ x = LS.matvec(z)
+ x2 = scipy.linalg.lstsq(At_dense, z)[0]
+ assert_array_almost_equal(x, x2)
+
+ def test_iterative_refinements_sparse(self):
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ A = csc_array(A_dense)
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8],
+ [1, 0, 0, 0, 0, 1, 2, 3+1e-10])
+
+ for method in available_sparse_methods:
+ Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=100)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ atol = 1e-13 * abs(x).max()
+ assert_allclose(A.dot(x), 0, atol=atol)
+ # Test orthogonality
+ assert_allclose(orthogonality(A, x), 0, atol=1e-13)
+
+ def test_rowspace_sparse(self):
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ A = csc_array(A_dense)
+ test_points = ([1, 2, 3],
+ [1, 10, 3],
+ [1.12, 10, 0])
+
+ for method in available_sparse_methods:
+ _, _, Y = projections(A, method)
+ for z in test_points:
+ # Test if x is solution of A x = z
+ x = Y.matvec(z)
+ assert_array_almost_equal(A.dot(x), z)
+ # Test if x is in the return row space of A
+ A_ext = np.vstack((A_dense, x))
+ assert_equal(np.linalg.matrix_rank(A_dense),
+ np.linalg.matrix_rank(A_ext))
+
+ def test_nullspace_and_least_squares_dense(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ At = A.T
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8])
+
+ for method in available_dense_methods:
+ Z, LS, _ = projections(A, method)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ assert_array_almost_equal(A.dot(x), 0)
+ # Test orthogonality
+ assert_array_almost_equal(orthogonality(A, x), 0)
+ # Test if x is the least square solution
+ x = LS.matvec(z)
+ x2 = scipy.linalg.lstsq(At, z)[0]
+ assert_array_almost_equal(x, x2)
+
+ def test_compare_dense_and_sparse(self):
+ D = np.diag(range(1, 101))
+ A = np.hstack([D, D, D, D])
+ A_sparse = csc_array(A)
+ rng = np.random.default_rng(123)
+
+ Z, LS, Y = projections(A)
+ Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
+ for k in range(20):
+ z = rng.standard_normal(size=(400,))
+ assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z))
+ assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z))
+ x = rng.standard_normal(size=(100,))
+ assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x))
+
+ def test_compare_dense_and_sparse2(self):
+ D1 = np.diag([-1.7, 1, 0.5])
+ D2 = np.diag([1, -0.6, -0.3])
+ D3 = np.diag([-0.3, -1.5, 2])
+ A = np.hstack([D1, D2, D3])
+ A_sparse = csc_array(A)
+ rng = np.random.default_rng(123)
+
+ Z, LS, Y = projections(A)
+ Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
+ for k in range(1):
+ z = rng.standard_normal(size=(9,))
+ assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z))
+ assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z))
+ x = rng.standard_normal(size=(3,))
+ assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x))
+
+ def test_iterative_refinements_dense(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1, 0, 0, 0, 0, 1, 2, 3+1e-10])
+
+ for method in available_dense_methods:
+ Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=10)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ assert_allclose(A.dot(x), 0, rtol=0, atol=2.5e-14)
+ # Test orthogonality
+ assert_allclose(orthogonality(A, x), 0, rtol=0, atol=5e-16)
+
+ def test_rowspace_dense(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ test_points = ([1, 2, 3],
+ [1, 10, 3],
+ [1.12, 10, 0])
+
+ for method in available_dense_methods:
+ _, _, Y = projections(A, method)
+ for z in test_points:
+ # Test if x is solution of A x = z
+ x = Y.matvec(z)
+ assert_array_almost_equal(A.dot(x), z)
+ # Test if x is in the return row space of A
+ A_ext = np.vstack((A, x))
+ assert_equal(np.linalg.matrix_rank(A),
+ np.linalg.matrix_rank(A_ext))
+
+
+class TestOrthogonality(TestCase):
+
+ def test_dense_matrix(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ test_vectors = ([-1.98931144, -1.56363389,
+ -0.84115584, 2.2864762,
+ 5.599141, 0.09286976,
+ 1.37040802, -0.28145812],
+ [697.92794044, -4091.65114008,
+ -3327.42316335, 836.86906951,
+ 99434.98929065, -1285.37653682,
+ -4109.21503806, 2935.29289083])
+ test_expected_orth = (0, 0)
+
+ for i in range(len(test_vectors)):
+ x = test_vectors[i]
+ orth = test_expected_orth[i]
+ assert_array_almost_equal(orthogonality(A, x), orth)
+
+ def test_sparse_matrix(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ A = csc_array(A)
+ test_vectors = ([-1.98931144, -1.56363389,
+ -0.84115584, 2.2864762,
+ 5.599141, 0.09286976,
+ 1.37040802, -0.28145812],
+ [697.92794044, -4091.65114008,
+ -3327.42316335, 836.86906951,
+ 99434.98929065, -1285.37653682,
+ -4109.21503806, 2935.29289083])
+ test_expected_orth = (0, 0)
+
+ for i in range(len(test_vectors)):
+ x = test_vectors[i]
+ orth = test_expected_orth[i]
+ assert_array_almost_equal(orthogonality(A, x), orth)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..9486671520fc6d60e1405fa839b756aa30b524fb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
@@ -0,0 +1,645 @@
+import numpy as np
+from scipy.sparse import csc_array
+from scipy.optimize._trustregion_constr.qp_subproblem \
+ import (eqp_kktfact,
+ projected_cg,
+ box_intersections,
+ sphere_intersections,
+ box_sphere_intersections,
+ modified_dogleg)
+from scipy.optimize._trustregion_constr.projections \
+ import projections
+from numpy.testing import TestCase, assert_array_almost_equal, assert_equal
+import pytest
+
+
+class TestEQPDirectFactorization(TestCase):
+
+ # From Example 16.2 Nocedal/Wright "Numerical
+ # Optimization" p.452.
+ def test_nocedal_example(self):
+ H = csc_array([[6, 2, 1],
+ [2, 5, 2],
+ [1, 2, 4]])
+ A = csc_array([[1, 0, 1],
+ [0, 1, 1]])
+ c = np.array([-8, -3, -3])
+ b = -np.array([3, 0])
+ x, lagrange_multipliers = eqp_kktfact(H, c, A, b)
+ assert_array_almost_equal(x, [2, -1, 1])
+ assert_array_almost_equal(lagrange_multipliers, [3, -2])
+
+
+class TestSphericalBoundariesIntersections(TestCase):
+
+ def test_2d_sphere_constraints(self):
+ # Interior initial point
+ ta, tb, intersect = sphere_intersections([0, 0],
+ [1, 0], 0.5)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [0, 1], 1)
+ assert_equal(intersect, False)
+
+ # Outside initial point pointing toward outside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 1)
+ assert_equal(intersect, False)
+
+ # Outside initial point pointing toward inside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [-1, 0], 1.5)
+ assert_array_almost_equal([ta, tb], [0.5, 1])
+ assert_equal(intersect, True)
+
+ # Initial point on the boundary
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 2)
+ assert_array_almost_equal([ta, tb], [0, 0])
+ assert_equal(intersect, True)
+
+ def test_2d_sphere_constraints_line_intersections(self):
+ # Interior initial point
+ ta, tb, intersect = sphere_intersections([0, 0],
+ [1, 0], 0.5,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-0.5, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [0, 1], 1,
+ entire_line=True)
+ assert_equal(intersect, False)
+
+ # Outside initial point pointing toward outside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 1,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-3, -1])
+ assert_equal(intersect, True)
+
+ # Outside initial point pointing toward inside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [-1, 0], 1.5,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0.5, 3.5])
+ assert_equal(intersect, True)
+
+ # Initial point on the boundary
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 2,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-4, 0])
+ assert_equal(intersect, True)
+
+
+class TestBoxBoundariesIntersections(TestCase):
+
+ def test_2d_box_constraints(self):
+ # Box constraint in the direction of vector d
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, 1], [3, 3])
+ assert_array_almost_equal([ta, tb], [0.5, 1])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, -3], [3, -1])
+ assert_equal(intersect, False)
+
+ # Some constraints are absent (set to +/- inf)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-np.inf, 1],
+ [np.inf, np.inf])
+ assert_array_almost_equal([ta, tb], [0.5, 1])
+ assert_equal(intersect, True)
+
+ # Intersect on the face of the box
+ ta, tb, intersect = box_intersections([1, 0], [0, 1],
+ [1, 1], [3, 3])
+ assert_array_almost_equal([ta, tb], [1, 1])
+ assert_equal(intersect, True)
+
+ # Interior initial point
+ ta, tb, intersect = box_intersections([0, 0], [4, 4],
+ [-2, -3], [3, 2])
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and box constraints
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -3], [-1, -1])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, 3], [-1, 1])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -np.inf],
+ [-1, np.inf])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0, 0], [1, 100],
+ [1, 1], [3, 3])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
+ [1, 1], [3, 3])
+ assert_equal(intersect, False)
+
+ # Initial point on the boundary
+ ta, tb, intersect = box_intersections([2, 2], [0, 1],
+ [-2, -2], [2, 2])
+ assert_array_almost_equal([ta, tb], [0, 0])
+ assert_equal(intersect, True)
+
+ def test_2d_box_constraints_entire_line(self):
+ # Box constraint in the direction of vector d
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0.5, 1.5])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, -3], [3, -1],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-1.5, -0.5])
+ assert_equal(intersect, True)
+
+ # Some constraints are absent (set to +/- inf)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-np.inf, 1],
+ [np.inf, np.inf],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0.5, np.inf])
+ assert_equal(intersect, True)
+
+ # Intersect on the face of the box
+ ta, tb, intersect = box_intersections([1, 0], [0, 1],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [1, 3])
+ assert_equal(intersect, True)
+
+ # Interior initial point
+ ta, tb, intersect = box_intersections([0, 0], [4, 4],
+ [-2, -3], [3, 2],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-0.5, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and box constraints
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -3], [-1, -1],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, 3], [-1, 1],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -np.inf],
+ [-1, np.inf],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0, 0], [1, 100],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_equal(intersect, False)
+
+ # Initial point on the boundary
+ ta, tb, intersect = box_intersections([2, 2], [0, 1],
+ [-2, -2], [2, 2],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-4, 0])
+ assert_equal(intersect, True)
+
+ def test_3d_box_constraints(self):
+ # Simple case
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
+ [1, 1, 1], [3, 3, 3])
+ assert_array_almost_equal([ta, tb], [1, 1])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
+ [1, 1, 1], [3, 3, 3])
+ assert_equal(intersect, False)
+
+ # Interior point
+ ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
+ [1, 1, 1], [3, 3, 3])
+ assert_array_almost_equal([ta, tb], [0, 1])
+ assert_equal(intersect, True)
+
+ def test_3d_box_constraints_entire_line(self):
+ # Simple case
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
+ [1, 1, 1], [3, 3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [1, 3])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
+ [1, 1, 1], [3, 3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-3, -1])
+ assert_equal(intersect, True)
+
+ # Interior point
+ ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
+ [1, 1, 1], [3, 3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-1, 1])
+ assert_equal(intersect, True)
+
+
+class TestBoxSphereBoundariesIntersections(TestCase):
+
+ def test_2d_box_constraints(self):
+ # Both constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2],
+ [-1, -2], [1, 2], 2,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # None of the constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1],
+ [-1, -3], [1, 3], 10,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 1])
+ assert_equal(intersect, True)
+
+ # Box constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 10,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # Spherical constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 0.25])
+ assert_equal(intersect, True)
+
+ # Infeasible problems
+ ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=False)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [2, 4], [2, 4], 2,
+ entire_line=False)
+ assert_equal(intersect, False)
+
+ def test_2d_box_constraints_entire_line(self):
+ # Both constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2],
+ [-1, -2], [1, 2], 2,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # None of the constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1],
+ [-1, -3], [1, 3], 10,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 2])
+ assert_equal(intersect, True)
+
+ # Box constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 10,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # Spherical constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 0.25])
+ assert_equal(intersect, True)
+
+ # Infeasible problems
+ ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [2, 4], [2, 4], 2,
+ entire_line=True)
+ assert_equal(intersect, False)
+
+
+class TestModifiedDogleg(TestCase):
+
+ def test_cauchypoint_equalsto_newtonpoint(self):
+ A = np.array([[1, 8]])
+ b = np.array([-16])
+ _, _, Y = projections(A)
+ newton_point = np.array([0.24615385, 1.96923077])
+
+ # Newton point inside boundaries
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [np.inf, np.inf])
+ assert_array_almost_equal(x, newton_point)
+
+ # Spherical constraint active
+ x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf], [np.inf, np.inf])
+ assert_array_almost_equal(x, newton_point/np.linalg.norm(newton_point))
+
+ # Box constraints active
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [0.1, np.inf])
+ assert_array_almost_equal(x, (newton_point/newton_point[0]) * 0.1)
+
+ def test_3d_example(self):
+ A = np.array([[1, 8, 1],
+ [4, 2, 2]])
+ b = np.array([-16, 2])
+ Z, LS, Y = projections(A)
+
+ newton_point = np.array([-1.37090909, 2.23272727, -0.49090909])
+ cauchy_point = np.array([0.11165723, 1.73068711, 0.16748585])
+ origin = np.zeros_like(newton_point)
+
+ # newton_point inside boundaries
+ x = modified_dogleg(A, Y, b, 3, [-np.inf, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ assert_array_almost_equal(x, newton_point)
+
+ # line between cauchy_point and newton_point contains best point
+ # (spherical constraint is active).
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ z = cauchy_point
+ d = newton_point-cauchy_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.40807330))
+ assert_array_almost_equal(np.linalg.norm(x), 2)
+
+ # line between cauchy_point and newton_point contains best point
+ # (box constraint is active).
+ x = modified_dogleg(A, Y, b, 5, [-1, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ z = cauchy_point
+ d = newton_point-cauchy_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.7498195))
+ assert_array_almost_equal(x[0], -1)
+
+ # line between origin and cauchy_point contains best point
+ # (spherical constraint is active).
+ x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ z = origin
+ d = cauchy_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.573936265))
+ assert_array_almost_equal(np.linalg.norm(x), 1)
+
+ # line between origin and newton_point contains best point
+ # (box constraint is active).
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf],
+ [np.inf, 1, np.inf])
+ z = origin
+ d = newton_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.4478827364))
+ assert_array_almost_equal(x[1], 1)
+
+
+class TestProjectCG(TestCase):
+
+ # From Example 16.2 Nocedal/Wright "Numerical
+ # Optimization" p.452.
+ def test_nocedal_example(self):
+ H = csc_array([[6, 2, 1],
+ [2, 5, 2],
+ [1, 2, 4]])
+ A = csc_array([[1, 0, 1],
+ [0, 1, 1]])
+ c = np.array([-8, -3, -3])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b)
+ assert_equal(info["stop_cond"], 4)
+ assert_equal(info["hits_boundary"], False)
+ assert_array_almost_equal(x, [2, -1, 1])
+
+ def test_compare_with_direct_fact(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b, tol=0)
+ x_kkt, _ = eqp_kktfact(H, c, A, b)
+ assert_equal(info["stop_cond"], 1)
+ assert_equal(info["hits_boundary"], False)
+ assert_array_almost_equal(x, x_kkt)
+
+ def test_trust_region_infeasible(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 1
+ Z, _, Y = projections(A)
+ with pytest.raises(ValueError):
+ projected_cg(H, c, Z, Y, b, trust_radius=trust_radius)
+
+ def test_trust_region_barely_feasible(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 2.32379000772445021283
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
+ assert_array_almost_equal(x, -Y.dot(b))
+
+ def test_hits_boundary(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 3
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
+
+ def test_negative_curvature_unconstrained(self):
+ H = csc_array([[1, 2, 1, 3],
+ [2, 0, 2, 4],
+ [1, 2, 0, 2],
+ [3, 4, 2, 0]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 0, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ with pytest.raises(ValueError):
+ projected_cg(H, c, Z, Y, b, tol=0)
+
+ def test_negative_curvature(self):
+ H = csc_array([[1, 2, 1, 3],
+ [2, 0, 2, 4],
+ [1, 2, 0, 2],
+ [3, 4, 2, 0]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 0, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ trust_radius = 1000
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 3)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
+
+ # The box constraints are inactive at the solution but
+ # are active during the iterations.
+ def test_inactive_box_constraints(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ lb=[0.5, -np.inf,
+ -np.inf, -np.inf],
+ return_all=True)
+ x_kkt, _ = eqp_kktfact(H, c, A, b)
+ assert_equal(info["stop_cond"], 1)
+ assert_equal(info["hits_boundary"], False)
+ assert_array_almost_equal(x, x_kkt)
+
+ # The box constraints active and the termination is
+ # by maximum iterations (infeasible interaction).
+ def test_active_box_constraints_maximum_iterations_reached(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ lb=[0.8, -np.inf,
+ -np.inf, -np.inf],
+ return_all=True)
+ assert_equal(info["stop_cond"], 1)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(A.dot(x), -b)
+ assert_array_almost_equal(x[0], 0.8)
+
+ # The box constraints are active and the termination is
+ # because it hits boundary (without infeasible interaction).
+ def test_active_box_constraints_hits_boundaries(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 3
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ ub=[np.inf, np.inf, 1.6, np.inf],
+ trust_radius=trust_radius,
+ return_all=True)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(x[2], 1.6)
+
+ # The box constraints are active and the termination is
+ # because it hits boundary (infeasible interaction).
+ def test_active_box_constraints_hits_boundaries_infeasible_iter(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 4
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ ub=[np.inf, 0.1, np.inf, np.inf],
+ trust_radius=trust_radius,
+ return_all=True)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(x[1], 0.1)
+
+ # The box constraints are active and the termination is
+ # because it hits boundary (no infeasible interaction).
+ def test_active_box_constraints_negative_curvature(self):
+ H = csc_array([[1, 2, 1, 3],
+ [2, 0, 2, 4],
+ [1, 2, 0, 2],
+ [3, 4, 2, 0]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 0, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ trust_radius = 1000
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ ub=[np.inf, np.inf, 100, np.inf],
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 3)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(x[2], 100)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..66fa5bd17f80a907db425c927c08e5dc0797028e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py
@@ -0,0 +1,34 @@
+import pytest
+import numpy as np
+from scipy.optimize import minimize, Bounds
+
+def test_gh10880():
+ # checks that verbose reporting works with trust-constr for
+ # bound-constrained problems
+ bnds = Bounds(1, 2)
+ opts = {'maxiter': 1000, 'verbose': 2}
+ minimize(lambda x: x**2, x0=2., method='trust-constr',
+ bounds=bnds, options=opts)
+
+ opts = {'maxiter': 1000, 'verbose': 3}
+ minimize(lambda x: x**2, x0=2., method='trust-constr',
+ bounds=bnds, options=opts)
+
+@pytest.mark.xslow
+def test_gh12922():
+ # checks that verbose reporting works with trust-constr for
+ # general constraints
+ def objective(x):
+ return np.array([(np.sum((x+1)**4))])
+
+ cons = {'type': 'ineq', 'fun': lambda x: -x[0]**2}
+ n = 25
+ x0 = np.linspace(-5, 5, n)
+
+ opts = {'maxiter': 1000, 'verbose': 2}
+ minimize(objective, x0=x0, method='trust-constr',
+ constraints=cons, options=opts)
+
+ opts = {'maxiter': 1000, 'verbose': 3}
+ minimize(objective, x0=x0, method='trust-constr',
+ constraints=cons, options=opts)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py
new file mode 100644
index 0000000000000000000000000000000000000000..981552e152469ebe6030d06d816cc7fc4c5bea60
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py
@@ -0,0 +1,369 @@
+"""Trust-region interior point method.
+
+References
+----------
+.. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
+ "An interior point algorithm for large-scale nonlinear
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
+.. [2] Byrd, Richard H., Guanghui Liu, and Jorge Nocedal.
+ "On the local behavior of an interior point method for
+ nonlinear programming." Numerical analysis 1997 (1997): 37-56.
+.. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+"""
+
+import scipy.sparse as sps
+import numpy as np
+from .equality_constrained_sqp import equality_constrained_sqp
+from scipy.sparse.linalg import LinearOperator
+
+__all__ = ['tr_interior_point']
+
+
+class BarrierSubproblem:
+ """
+ Barrier optimization problem:
+ minimize fun(x) - barrier_parameter*sum(log(s))
+ subject to: constr_eq(x) = 0
+ constr_ineq(x) + s = 0
+ """
+
+ def __init__(self, x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq,
+ constr, jac, barrier_parameter, tolerance,
+ enforce_feasibility, global_stop_criteria,
+ xtol, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0,
+ jac_eq0, finite_diff_bounds):
+ # Store parameters
+ self.n_vars = n_vars
+ self.x0 = x0
+ self.s0 = s0
+ self.fun = fun
+ self.grad = grad
+ self.lagr_hess = lagr_hess
+ self.constr = constr
+ self.jac = jac
+ self.barrier_parameter = barrier_parameter
+ self.tolerance = tolerance
+ self.n_eq = n_eq
+ self.n_ineq = n_ineq
+ self.enforce_feasibility = enforce_feasibility
+ self.global_stop_criteria = global_stop_criteria
+ self.xtol = xtol
+ self.fun0 = self._compute_function(fun0, constr_ineq0, s0)
+ self.grad0 = self._compute_gradient(grad0)
+ self.constr0 = self._compute_constr(constr_ineq0, constr_eq0, s0)
+ self.jac0 = self._compute_jacobian(jac_eq0, jac_ineq0, s0)
+ self.terminate = False
+ self.lb = finite_diff_bounds[0]
+ self.ub = finite_diff_bounds[1]
+
+ def update(self, barrier_parameter, tolerance):
+ self.barrier_parameter = barrier_parameter
+ self.tolerance = tolerance
+
+ def get_slack(self, z):
+ return z[self.n_vars:self.n_vars+self.n_ineq]
+
+ def get_variables(self, z):
+ return z[:self.n_vars]
+
+ def function_and_constraints(self, z):
+ """Returns barrier function and constraints at given point.
+
+ For z = [x, s], returns barrier function:
+ function(z) = fun(x) - barrier_parameter*sum(log(s))
+ and barrier constraints:
+ constraints(z) = [ constr_eq(x) ]
+ [ constr_ineq(x) + s ]
+
+ """
+ # Get variables and slack variables
+ x = self.get_variables(z)
+ s = self.get_slack(z)
+
+ # Compute function and constraints,
+ # making sure x is within any strict bounds
+ if np.any((x < self.lb) | (x > self.ub)):
+ # If x is out of the strict bounds, set f = inf,
+ # and just set both equality and inequality
+ # constraints to 0 since we can't evaluate
+ # them separately.
+ f = np.inf
+ c_eq = np.full(self.n_eq, 0.)
+ c_ineq = np.full(self.n_ineq, 0.)
+ else:
+ c_eq, c_ineq = self.constr(x)
+
+ if np.any(c_ineq[self.enforce_feasibility] >= 0):
+ # Set f = inf explicitly so that the actual objective function is not
+ # called with infeasible values.
+ #
+ # The iteration will fail and the trust region will be reduced.
+ f = np.inf
+ else:
+ f = self.fun(x)
+
+ # Return objective function and constraints
+ return (self._compute_function(f, c_ineq, s),
+ self._compute_constr(c_ineq, c_eq, s))
+
+ def _compute_function(self, f, c_ineq, s):
+ # Use technique from Nocedal and Wright book, ref [3]_, p.576,
+ # to guarantee constraints from `enforce_feasibility`
+ # stay feasible along iterations.
+ s[self.enforce_feasibility] = -c_ineq[self.enforce_feasibility]
+ log_s = [np.log(s_i) if s_i > 0 else -np.inf for s_i in s]
+ # Compute barrier objective function
+ return f - self.barrier_parameter*np.sum(log_s)
+
+ def _compute_constr(self, c_ineq, c_eq, s):
+ # Compute barrier constraint
+ return np.hstack((c_eq,
+ c_ineq + s))
+
+ def scaling(self, z):
+ """Returns scaling vector.
+ Given by:
+ scaling = [ones(n_vars), s]
+ """
+ s = self.get_slack(z)
+ diag_elements = np.hstack((np.ones(self.n_vars), s))
+
+ # Diagonal matrix
+ def matvec(vec):
+ return diag_elements*vec
+ return LinearOperator((self.n_vars+self.n_ineq,
+ self.n_vars+self.n_ineq),
+ matvec)
+
+ def gradient_and_jacobian(self, z):
+ """Returns scaled gradient.
+
+ Return scaled gradient:
+ gradient = [ grad(x) ]
+ [ -barrier_parameter*ones(n_ineq) ]
+ and scaled Jacobian matrix:
+ jacobian = [ jac_eq(x) 0 ]
+ [ jac_ineq(x) S ]
+ Both of them scaled by the previously defined scaling factor.
+ """
+ # Get variables and slack variables
+ x = self.get_variables(z)
+ s = self.get_slack(z)
+ # Compute first derivatives
+ g = self.grad(x)
+ J_eq, J_ineq = self.jac(x)
+ # Return gradient and Jacobian
+ return (self._compute_gradient(g),
+ self._compute_jacobian(J_eq, J_ineq, s))
+
+ def _compute_gradient(self, g):
+ return np.hstack((g, -self.barrier_parameter*np.ones(self.n_ineq)))
+
+ def _compute_jacobian(self, J_eq, J_ineq, s):
+ if self.n_ineq == 0:
+ return J_eq
+ else:
+ if sps.issparse(J_eq) or sps.issparse(J_ineq):
+ # It is expected that J_eq and J_ineq
+ # are already `csr_array` because of
+ # the way ``BoxConstraint``, ``NonlinearConstraint``
+ # and ``LinearConstraint`` are defined.
+ J_eq = sps.csr_array(J_eq)
+ J_ineq = sps.csr_array(J_ineq)
+ return self._assemble_sparse_jacobian(J_eq, J_ineq, s)
+ else:
+ S = np.diag(s)
+ zeros = np.zeros((self.n_eq, self.n_ineq))
+ # Convert to matrix
+ if sps.issparse(J_ineq):
+ J_ineq = J_ineq.toarray()
+ if sps.issparse(J_eq):
+ J_eq = J_eq.toarray()
+ # Concatenate matrices
+ return np.block([[J_eq, zeros],
+ [J_ineq, S]])
+
+ def _assemble_sparse_jacobian(self, J_eq, J_ineq, s):
+ """Assemble sparse Jacobian given its components.
+
+ Given ``J_eq``, ``J_ineq`` and ``s`` returns:
+ jacobian = [ J_eq, 0 ]
+ [ J_ineq, diag(s) ]
+
+ It is equivalent to:
+ sps.bmat([[ J_eq, None ],
+ [ J_ineq, diag(s) ]], "csr")
+ but significantly more efficient for this
+ given structure.
+ """
+ n_vars, n_ineq, n_eq = self.n_vars, self.n_ineq, self.n_eq
+ J_aux = sps.vstack([J_eq, J_ineq], "csr")
+ indptr, indices, data = J_aux.indptr, J_aux.indices, J_aux.data
+ new_indptr = indptr + np.hstack((np.zeros(n_eq, dtype=int),
+ np.arange(n_ineq+1, dtype=int)))
+ size = indices.size+n_ineq
+ new_indices = np.empty(size)
+ new_data = np.empty(size)
+ mask = np.full(size, False, bool)
+ mask[new_indptr[-n_ineq:]-1] = True
+ new_indices[mask] = n_vars+np.arange(n_ineq)
+ new_indices[~mask] = indices
+ new_data[mask] = s
+ new_data[~mask] = data
+ J = sps.csr_array((new_data, new_indices, new_indptr),
+ (n_eq + n_ineq, n_vars + n_ineq))
+ return J
+
+ def lagrangian_hessian_x(self, z, v):
+ """Returns Lagrangian Hessian (in relation to `x`) -> Hx"""
+ x = self.get_variables(z)
+ # Get lagrange multipliers related to nonlinear equality constraints
+ v_eq = v[:self.n_eq]
+ # Get lagrange multipliers related to nonlinear ineq. constraints
+ v_ineq = v[self.n_eq:self.n_eq+self.n_ineq]
+ lagr_hess = self.lagr_hess
+ return lagr_hess(x, v_eq, v_ineq)
+
+ def lagrangian_hessian_s(self, z, v):
+ """Returns scaled Lagrangian Hessian (in relation to`s`) -> S Hs S"""
+ s = self.get_slack(z)
+ # Using the primal formulation:
+ # S Hs S = diag(s)*diag(barrier_parameter/s**2)*diag(s).
+ # Reference [1]_ p. 882, formula (3.1)
+ primal = self.barrier_parameter
+ # Using the primal-dual formulation
+ # S Hs S = diag(s)*diag(v/s)*diag(s)
+ # Reference [1]_ p. 883, formula (3.11)
+ primal_dual = v[-self.n_ineq:]*s
+ # Uses the primal-dual formulation for
+ # positives values of v_ineq, and primal
+ # formulation for the remaining ones.
+ return np.where(v[-self.n_ineq:] > 0, primal_dual, primal)
+
+ def lagrangian_hessian(self, z, v):
+ """Returns scaled Lagrangian Hessian"""
+ # Compute Hessian in relation to x and s
+ Hx = self.lagrangian_hessian_x(z, v)
+ if self.n_ineq > 0:
+ S_Hs_S = self.lagrangian_hessian_s(z, v)
+
+ # The scaled Lagragian Hessian is:
+ # [ Hx 0 ]
+ # [ 0 S Hs S ]
+ def matvec(vec):
+ vec_x = self.get_variables(vec)
+ vec_s = self.get_slack(vec)
+ if self.n_ineq > 0:
+ return np.hstack((Hx.dot(vec_x), S_Hs_S*vec_s))
+ else:
+ return Hx.dot(vec_x)
+ return LinearOperator((self.n_vars+self.n_ineq,
+ self.n_vars+self.n_ineq),
+ matvec)
+
+ def stop_criteria(self, state, z, last_iteration_failed,
+ optimality, constr_violation,
+ trust_radius, penalty, cg_info):
+ """Stop criteria to the barrier problem.
+ The criteria here proposed is similar to formula (2.3)
+ from [1]_, p.879.
+ """
+ x = self.get_variables(z)
+ if self.global_stop_criteria(state, x,
+ last_iteration_failed,
+ trust_radius, penalty,
+ cg_info,
+ self.barrier_parameter,
+ self.tolerance):
+ self.terminate = True
+ return True
+ else:
+ g_cond = (optimality < self.tolerance and
+ constr_violation < self.tolerance)
+ x_cond = trust_radius < self.xtol
+ return g_cond or x_cond
+
+
+def tr_interior_point(fun, grad, lagr_hess, n_vars, n_ineq, n_eq,
+ constr, jac, x0, fun0, grad0,
+ constr_ineq0, jac_ineq0, constr_eq0,
+ jac_eq0, stop_criteria,
+ enforce_feasibility, xtol, state,
+ initial_barrier_parameter,
+ initial_tolerance,
+ initial_penalty,
+ initial_trust_radius,
+ factorization_method,
+ finite_diff_bounds):
+ """Trust-region interior points method.
+
+ Solve problem:
+ minimize fun(x)
+ subject to: constr_ineq(x) <= 0
+ constr_eq(x) = 0
+ using trust-region interior point method described in [1]_.
+ """
+ # BOUNDARY_PARAMETER controls the decrease on the slack
+ # variables. Represents ``tau`` from [1]_ p.885, formula (3.18).
+ BOUNDARY_PARAMETER = 0.995
+ # BARRIER_DECAY_RATIO controls the decay of the barrier parameter
+ # and of the subproblem tolerance. Represents ``theta`` from [1]_ p.879.
+ BARRIER_DECAY_RATIO = 0.2
+ # TRUST_ENLARGEMENT controls the enlargement on trust radius
+ # after each iteration
+ TRUST_ENLARGEMENT = 5
+
+ # Default enforce_feasibility
+ if enforce_feasibility is None:
+ enforce_feasibility = np.zeros(n_ineq, bool)
+ # Initial Values
+ barrier_parameter = initial_barrier_parameter
+ tolerance = initial_tolerance
+ trust_radius = initial_trust_radius
+ # Define initial value for the slack variables
+ s0 = np.maximum(-1.5*constr_ineq0, np.ones(n_ineq))
+ # Define barrier subproblem
+ subprob = BarrierSubproblem(
+ x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac,
+ barrier_parameter, tolerance, enforce_feasibility,
+ stop_criteria, xtol, fun0, grad0, constr_ineq0, jac_ineq0,
+ constr_eq0, jac_eq0, finite_diff_bounds)
+ # Define initial parameter for the first iteration.
+ z = np.hstack((x0, s0))
+ fun0_subprob, constr0_subprob = subprob.fun0, subprob.constr0
+ grad0_subprob, jac0_subprob = subprob.grad0, subprob.jac0
+ # Define trust region bounds
+ trust_lb = np.hstack((np.full(subprob.n_vars, -np.inf),
+ np.full(subprob.n_ineq, -BOUNDARY_PARAMETER)))
+ trust_ub = np.full(subprob.n_vars+subprob.n_ineq, np.inf)
+
+ # Solves a sequence of barrier problems
+ while True:
+ # Solve SQP subproblem
+ z, state = equality_constrained_sqp(
+ subprob.function_and_constraints,
+ subprob.gradient_and_jacobian,
+ subprob.lagrangian_hessian,
+ z, fun0_subprob, grad0_subprob,
+ constr0_subprob, jac0_subprob, subprob.stop_criteria,
+ state, initial_penalty, trust_radius,
+ factorization_method, trust_lb, trust_ub, subprob.scaling)
+ if subprob.terminate:
+ break
+ # Update parameters
+ trust_radius = max(initial_trust_radius,
+ TRUST_ENLARGEMENT*state.tr_radius)
+ # TODO: Use more advanced strategies from [2]_
+ # to update this parameters.
+ barrier_parameter *= BARRIER_DECAY_RATIO
+ tolerance *= BARRIER_DECAY_RATIO
+ # Update Barrier Problem
+ subprob.update(barrier_parameter, tolerance)
+ # Compute initial values for next iteration
+ fun0_subprob, constr0_subprob = subprob.function_and_constraints(z)
+ grad0_subprob, jac0_subprob = subprob.gradient_and_jacobian(z)
+
+ # Get x and s
+ x = subprob.get_variables(z)
+ return x, state
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_dogleg.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_dogleg.py
new file mode 100644
index 0000000000000000000000000000000000000000..a54abd60c703408d6c87cb5020d6781fdf0213c7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_dogleg.py
@@ -0,0 +1,122 @@
+"""Dog-leg trust-region optimization."""
+import numpy as np
+import scipy.linalg
+from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
+
+__all__ = []
+
+
+def _minimize_dogleg(fun, x0, args=(), jac=None, hess=None,
+ **trust_region_options):
+ """
+ Minimization of scalar function of one or more variables using
+ the dog-leg trust-region algorithm.
+
+ Options
+ -------
+ initial_trust_radius : float
+ Initial trust-region radius.
+ max_trust_radius : float
+ Maximum value of the trust-region radius. No steps that are longer
+ than this value will be proposed.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than `gtol` before successful
+ termination.
+
+ """
+ if jac is None:
+ raise ValueError('Jacobian is required for dogleg minimization')
+ if not callable(hess):
+ raise ValueError('Hessian is required for dogleg minimization')
+ return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess,
+ subproblem=DoglegSubproblem,
+ **trust_region_options)
+
+
+class DoglegSubproblem(BaseQuadraticSubproblem):
+ """Quadratic subproblem solved by the dogleg method"""
+
+ def cauchy_point(self):
+ """
+ The Cauchy point is minimal along the direction of steepest descent.
+ """
+ if self._cauchy_point is None:
+ g = self.jac
+ Bg = self.hessp(g)
+ self._cauchy_point = -(np.dot(g, g) / np.dot(g, Bg)) * g
+ return self._cauchy_point
+
+ def newton_point(self):
+ """
+ The Newton point is a global minimum of the approximate function.
+ """
+ if self._newton_point is None:
+ g = self.jac
+ B = self.hess
+ cho_info = scipy.linalg.cho_factor(B)
+ self._newton_point = -scipy.linalg.cho_solve(cho_info, g)
+ return self._newton_point
+
+ def solve(self, trust_radius):
+ """
+ Minimize a function using the dog-leg trust-region algorithm.
+
+ This algorithm requires function values and first and second derivatives.
+ It also performs a costly Hessian decomposition for most iterations,
+ and the Hessian is required to be positive definite.
+
+ Parameters
+ ----------
+ trust_radius : float
+ We are allowed to wander only this far away from the origin.
+
+ Returns
+ -------
+ p : ndarray
+ The proposed step.
+ hits_boundary : bool
+ True if the proposed step is on the boundary of the trust region.
+
+ Notes
+ -----
+ The Hessian is required to be positive definite.
+
+ References
+ ----------
+ .. [1] Jorge Nocedal and Stephen Wright,
+ Numerical Optimization, second edition,
+ Springer-Verlag, 2006, page 73.
+ """
+
+ # Compute the Newton point.
+ # This is the optimum for the quadratic model function.
+ # If it is inside the trust radius then return this point.
+ p_best = self.newton_point()
+ if scipy.linalg.norm(p_best) < trust_radius:
+ hits_boundary = False
+ return p_best, hits_boundary
+
+ # Compute the Cauchy point.
+ # This is the predicted optimum along the direction of steepest descent.
+ p_u = self.cauchy_point()
+
+ # If the Cauchy point is outside the trust region,
+ # then return the point where the path intersects the boundary.
+ p_u_norm = scipy.linalg.norm(p_u)
+ if p_u_norm >= trust_radius:
+ p_boundary = p_u * (trust_radius / p_u_norm)
+ hits_boundary = True
+ return p_boundary, hits_boundary
+
+ # Compute the intersection of the trust region boundary
+ # and the line segment connecting the Cauchy and Newton points.
+ # This requires solving a quadratic equation.
+ # ||p_u + t*(p_best - p_u)||**2 == trust_radius**2
+ # Solve this for positive time t using the quadratic formula.
+ _, tb = self.get_boundaries_intersections(p_u, p_best - p_u,
+ trust_radius)
+ p_boundary = p_u + tb * (p_best - p_u)
+ hits_boundary = True
+ return p_boundary, hits_boundary
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_exact.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..da33f2513d99a16b61bbac7a4470c865303edbb6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_exact.py
@@ -0,0 +1,459 @@
+"""Nearly exact trust-region optimization subproblem."""
+import numpy as np
+from scipy.linalg import (norm, get_lapack_funcs, solve_triangular,
+ cho_solve)
+from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
+
+__all__ = ['_minimize_trustregion_exact',
+ 'estimate_smallest_singular_value',
+ 'singular_leading_submatrix',
+ 'IterativeSubproblem']
+
+
+def _minimize_trustregion_exact(fun, x0, args=(), jac=None, hess=None,
+ **trust_region_options):
+ """
+ Minimization of scalar function of one or more variables using
+ a nearly exact trust-region algorithm.
+
+ Options
+ -------
+ initial_trust_radius : float
+ Initial trust-region radius.
+ max_trust_radius : float
+ Maximum value of the trust-region radius. No steps that are longer
+ than this value will be proposed.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than ``gtol`` before successful
+ termination.
+ subproblem_maxiter : int, optional
+ Maximum number of iterations to perform per subproblem. Only affects
+ trust-exact. Default is 25.
+
+ .. versionadded:: 1.17.0
+ """
+ if jac is None:
+ raise ValueError('Jacobian is required for trust region '
+ 'exact minimization.')
+ if not callable(hess):
+ raise ValueError('Hessian matrix is required for trust region '
+ 'exact minimization.')
+ return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess,
+ subproblem=IterativeSubproblem,
+ **trust_region_options)
+
+
+def estimate_smallest_singular_value(U):
+ """Given upper triangular matrix ``U`` estimate the smallest singular
+ value and the correspondent right singular vector in O(n**2) operations.
+
+ Parameters
+ ----------
+ U : ndarray
+ Square upper triangular matrix.
+
+ Returns
+ -------
+ s_min : float
+ Estimated smallest singular value of the provided matrix.
+ z_min : ndarray
+ Estimated right singular vector.
+
+ Notes
+ -----
+ The procedure is based on [1]_ and is done in two steps. First, it finds
+ a vector ``e`` with components selected from {+1, -1} such that the
+ solution ``w`` from the system ``U.T w = e`` is as large as possible.
+ Next it estimate ``U v = w``. The smallest singular value is close
+ to ``norm(w)/norm(v)`` and the right singular vector is close
+ to ``v/norm(v)``.
+
+ The estimation will be better more ill-conditioned is the matrix.
+
+ References
+ ----------
+ .. [1] Cline, A. K., Moler, C. B., Stewart, G. W., Wilkinson, J. H.
+ An estimate for the condition number of a matrix. 1979.
+ SIAM Journal on Numerical Analysis, 16(2), 368-375.
+ """
+
+ U = np.atleast_2d(U)
+ m, n = U.shape
+
+ if m != n:
+ raise ValueError("A square triangular matrix should be provided.")
+
+ # A vector `e` with components selected from {+1, -1}
+ # is selected so that the solution `w` to the system
+ # `U.T w = e` is as large as possible. Implementation
+ # based on algorithm 3.5.1, p. 142, from reference [2]
+ # adapted for lower triangular matrix.
+
+ p = np.zeros(n)
+ w = np.empty(n)
+
+ # Implemented according to: Golub, G. H., Van Loan, C. F. (2013).
+ # "Matrix computations". Forth Edition. JHU press. pp. 140-142.
+ for k in range(n):
+ wp = (1-p[k]) / U.T[k, k]
+ wm = (-1-p[k]) / U.T[k, k]
+ pp = p[k+1:] + U.T[k+1:, k]*wp
+ pm = p[k+1:] + U.T[k+1:, k]*wm
+
+ if abs(wp) + norm(pp, 1) >= abs(wm) + norm(pm, 1):
+ w[k] = wp
+ p[k+1:] = pp
+ else:
+ w[k] = wm
+ p[k+1:] = pm
+
+ # The system `U v = w` is solved using backward substitution.
+ v = solve_triangular(U, w)
+
+ v_norm = norm(v)
+ w_norm = norm(w)
+
+ # Smallest singular value
+ s_min = w_norm / v_norm
+
+ # Associated vector
+ z_min = v / v_norm
+
+ return s_min, z_min
+
+
+def gershgorin_bounds(H):
+ """
+ Given a square matrix ``H`` compute upper
+ and lower bounds for its eigenvalues (Gregoshgorin Bounds).
+ Defined ref. [1].
+
+ References
+ ----------
+ .. [1] Conn, A. R., Gould, N. I., & Toint, P. L.
+ Trust region methods. 2000. Siam. pp. 19.
+ """
+
+ H_diag = np.diag(H)
+ H_diag_abs = np.abs(H_diag)
+ H_row_sums = np.sum(np.abs(H), axis=1)
+ lb = np.min(H_diag + H_diag_abs - H_row_sums)
+ ub = np.max(H_diag - H_diag_abs + H_row_sums)
+
+ return lb, ub
+
+
+def singular_leading_submatrix(A, U, k):
+ """
+ Compute term that makes the leading ``k`` by ``k``
+ submatrix from ``A`` singular.
+
+ Parameters
+ ----------
+ A : ndarray
+ Symmetric matrix that is not positive definite.
+ U : ndarray
+ Upper triangular matrix resulting of an incomplete
+ Cholesky decomposition of matrix ``A``.
+ k : int
+ Positive integer such that the leading k by k submatrix from
+ `A` is the first non-positive definite leading submatrix.
+
+ Returns
+ -------
+ delta : float
+ Amount that should be added to the element (k, k) of the
+ leading k by k submatrix of ``A`` to make it singular.
+ v : ndarray
+ A vector such that ``v.T B v = 0``. Where B is the matrix A after
+ ``delta`` is added to its element (k, k).
+ """
+
+ # Compute delta
+ delta = np.sum(U[:k-1, k-1]**2) - A[k-1, k-1]
+
+ n = len(A)
+
+ # Initialize v
+ v = np.zeros(n)
+ v[k-1] = 1
+
+ # Compute the remaining values of v by solving a triangular system.
+ if k != 1:
+ v[:k-1] = solve_triangular(U[:k-1, :k-1], -U[:k-1, k-1])
+
+ return delta, v
+
+
+class IterativeSubproblem(BaseQuadraticSubproblem):
+ """Quadratic subproblem solved by nearly exact iterative method.
+
+ Notes
+ -----
+ This subproblem solver was based on [1]_, [2]_ and [3]_,
+ which implement similar algorithms. The algorithm is basically
+ that of [1]_ but ideas from [2]_ and [3]_ were also used.
+
+ References
+ ----------
+ .. [1] A.R. Conn, N.I. Gould, and P.L. Toint, "Trust region methods",
+ Siam, pp. 169-200, 2000.
+ .. [2] J. Nocedal and S. Wright, "Numerical optimization",
+ Springer Science & Business Media. pp. 83-91, 2006.
+ .. [3] J.J. More and D.C. Sorensen, "Computing a trust region step",
+ SIAM Journal on Scientific and Statistical Computing, vol. 4(3),
+ pp. 553-572, 1983.
+ """
+
+ # UPDATE_COEFF appears in reference [1]_
+ # in formula 7.3.14 (p. 190) named as "theta".
+ # As recommended there it value is fixed in 0.01.
+ UPDATE_COEFF = 0.01
+
+ # The subproblem may iterate infinitely for problematic
+ # cases (see https://github.com/scipy/scipy/issues/12513).
+ # When the `maxiter` setting is None, we need to apply a
+ # default. An ad-hoc number (though tested quite extensively)
+ # is 25, which is set below. To restore the old behavior (which
+ # potentially hangs), this parameter may be changed to zero:
+ MAXITER_DEFAULT = 25 # use np.inf for infinite number of iterations
+
+ EPS = np.finfo(float).eps
+
+ def __init__(self, x, fun, jac, hess, hessp=None,
+ k_easy=0.1, k_hard=0.2, maxiter=None):
+
+ super().__init__(x, fun, jac, hess)
+
+ # When the trust-region shrinks in two consecutive
+ # calculations (``tr_radius < previous_tr_radius``)
+ # the lower bound ``lambda_lb`` may be reused,
+ # facilitating the convergence. To indicate no
+ # previous value is known at first ``previous_tr_radius``
+ # is set to -1 and ``lambda_lb`` to None.
+ self.previous_tr_radius = -1
+ self.lambda_lb = None
+
+ self.niter = 0
+
+ # ``k_easy`` and ``k_hard`` are parameters used
+ # to determine the stop criteria to the iterative
+ # subproblem solver. Take a look at pp. 194-197
+ # from reference _[1] for a more detailed description.
+ self.k_easy = k_easy
+ self.k_hard = k_hard
+
+ # ``maxiter`` optionally limits the number of iterations
+ # the solve method may perform. Useful for poorly conditioned
+ # problems which may otherwise hang.
+ self.maxiter = self.MAXITER_DEFAULT if maxiter is None else maxiter
+ if self.maxiter < 0:
+ raise ValueError("maxiter must not be set to a negative number"
+ ", use np.inf to mean infinite.")
+
+ # Get Lapack function for cholesky decomposition.
+ # The implemented SciPy wrapper does not return
+ # the incomplete factorization needed by the method.
+ self.cholesky, = get_lapack_funcs(('potrf',), (self.hess,))
+
+ # Get info about Hessian
+ self.dimension = len(self.hess)
+ self.hess_gershgorin_lb,\
+ self.hess_gershgorin_ub = gershgorin_bounds(self.hess)
+ self.hess_inf = norm(self.hess, np.inf)
+ self.hess_fro = norm(self.hess, 'fro')
+
+ # A constant such that for vectors smaller than that
+ # backward substitution is not reliable. It was established
+ # based on Golub, G. H., Van Loan, C. F. (2013).
+ # "Matrix computations". Forth Edition. JHU press., p.165.
+ self.CLOSE_TO_ZERO = self.dimension * self.EPS * self.hess_inf
+
+ def _initial_values(self, tr_radius):
+ """Given a trust radius, return a good initial guess for
+ the damping factor, the lower bound and the upper bound.
+ The values were chosen accordingly to the guidelines on
+ section 7.3.8 (p. 192) from [1]_.
+ """
+
+ # Upper bound for the damping factor
+ lambda_ub = max(0, self.jac_mag/tr_radius + min(-self.hess_gershgorin_lb,
+ self.hess_fro,
+ self.hess_inf))
+
+ # Lower bound for the damping factor
+ lambda_lb = max(0, -min(self.hess.diagonal()),
+ self.jac_mag/tr_radius - min(self.hess_gershgorin_ub,
+ self.hess_fro,
+ self.hess_inf))
+
+ # Improve bounds with previous info
+ if tr_radius < self.previous_tr_radius:
+ lambda_lb = max(self.lambda_lb, lambda_lb)
+
+ # Initial guess for the damping factor
+ if lambda_lb == 0:
+ lambda_initial = 0
+ else:
+ lambda_initial = max(np.sqrt(lambda_lb * lambda_ub),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb))
+
+ return lambda_initial, lambda_lb, lambda_ub
+
+ def solve(self, tr_radius):
+ """Solve quadratic subproblem"""
+
+ lambda_current, lambda_lb, lambda_ub = self._initial_values(tr_radius)
+ n = self.dimension
+ hits_boundary = True
+ already_factorized = False
+ self.niter = 0
+
+ while self.niter < self.maxiter:
+
+ # Compute Cholesky factorization
+ if already_factorized:
+ already_factorized = False
+ else:
+ H = self.hess+lambda_current*np.eye(n)
+ U, info = self.cholesky(H, lower=False,
+ overwrite_a=False,
+ clean=True)
+
+ self.niter += 1
+
+ # Check if factorization succeeded
+ if info == 0 and self.jac_mag > self.CLOSE_TO_ZERO:
+ # Successful factorization
+
+ # Solve `U.T U p = s`
+ p = cho_solve((U, False), -self.jac)
+
+ p_norm = norm(p)
+
+ # Check for interior convergence
+ if p_norm <= tr_radius and lambda_current == 0:
+ hits_boundary = False
+ break
+
+ # Solve `U.T w = p`
+ w = solve_triangular(U, p, trans='T')
+
+ w_norm = norm(w)
+
+ # Compute Newton step accordingly to
+ # formula (4.44) p.87 from ref [2]_.
+ delta_lambda = (p_norm/w_norm)**2 * (p_norm-tr_radius)/tr_radius
+ lambda_new = lambda_current + delta_lambda
+
+ if p_norm < tr_radius: # Inside boundary
+ s_min, z_min = estimate_smallest_singular_value(U)
+
+ ta, tb = self.get_boundaries_intersections(p, z_min,
+ tr_radius)
+
+ # Choose `step_len` with the smallest magnitude.
+ # The reason for this choice is explained at
+ # ref [3]_, p. 6 (Immediately before the formula
+ # for `tau`).
+ step_len = min([ta, tb], key=abs)
+
+ # Compute the quadratic term (p.T*H*p)
+ quadratic_term = np.dot(p, np.dot(H, p))
+
+ # Check stop criteria
+ relative_error = ((step_len**2 * s_min**2)
+ / (quadratic_term + lambda_current*tr_radius**2))
+ if relative_error <= self.k_hard:
+ p += step_len * z_min
+ break
+
+ # Update uncertainty bounds
+ lambda_ub = lambda_current
+ lambda_lb = max(lambda_lb, lambda_current - s_min**2)
+
+ # Compute Cholesky factorization
+ H = self.hess + lambda_new*np.eye(n)
+ c, info = self.cholesky(H, lower=False,
+ overwrite_a=False,
+ clean=True)
+
+ # Check if the factorization have succeeded
+ #
+ if info == 0: # Successful factorization
+ # Update damping factor
+ lambda_current = lambda_new
+ already_factorized = True
+ U = c
+ else: # Unsuccessful factorization
+ # Update uncertainty bounds
+ lambda_lb = max(lambda_lb, lambda_new)
+
+ # Update damping factor
+ lambda_current = max(
+ np.sqrt(np.abs(lambda_lb * lambda_ub)),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)
+ )
+
+ else: # Outside boundary
+ # Check stop criteria
+ relative_error = abs(p_norm - tr_radius) / tr_radius
+ if relative_error <= self.k_easy:
+ break
+
+ # Update uncertainty bounds
+ lambda_lb = lambda_current
+
+ # Update damping factor
+ lambda_current = lambda_new
+
+ elif info == 0 and self.jac_mag <= self.CLOSE_TO_ZERO:
+ # jac_mag very close to zero
+
+ # Check for interior convergence
+ if lambda_current == 0:
+ p = np.zeros(n)
+ hits_boundary = False
+ break
+
+ s_min, z_min = estimate_smallest_singular_value(U)
+ step_len = tr_radius
+
+ p = step_len * z_min
+ # Check stop criteria
+ if (step_len**2 * s_min**2
+ <= self.k_hard * lambda_current * tr_radius**2):
+ break
+
+ # Update uncertainty bounds
+ lambda_ub = lambda_current
+ lambda_lb = max(lambda_lb, lambda_current - s_min**2)
+
+ # Update damping factor
+ lambda_current = max(
+ np.sqrt(lambda_lb * lambda_ub),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)
+ )
+
+ else: # Unsuccessful factorization
+
+ # Compute auxiliary terms
+ delta, v = singular_leading_submatrix(H, U, info)
+ v_norm = norm(v)
+
+ # Update uncertainty interval
+ lambda_lb = max(lambda_lb, lambda_current + delta/v_norm**2)
+
+ # Update damping factor
+ lambda_current = max(
+ np.sqrt(np.abs(lambda_lb * lambda_ub)),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)
+ )
+
+ self.lambda_lb = lambda_lb
+ self.lambda_current = lambda_current
+ self.previous_tr_radius = tr_radius
+
+ return p, hits_boundary
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_krylov.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_krylov.py
new file mode 100644
index 0000000000000000000000000000000000000000..54e861ae2de02164966a33c437e5fdb08ba3006c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_krylov.py
@@ -0,0 +1,65 @@
+from ._trustregion import (_minimize_trust_region)
+from ._trlib import (get_trlib_quadratic_subproblem)
+
+__all__ = ['_minimize_trust_krylov']
+
+def _minimize_trust_krylov(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ inexact=True, **trust_region_options):
+ """
+ Minimization of a scalar function of one or more variables using
+ a nearly exact trust-region algorithm that only requires matrix
+ vector products with the hessian matrix.
+
+ .. versionadded:: 1.0.0
+
+ Options
+ -------
+ inexact : bool, optional
+ Accuracy to solve subproblems. If True requires less nonlinear
+ iterations, but more vector products.
+ """
+
+ if jac is None:
+ raise ValueError('Jacobian is required for trust region ',
+ 'exact minimization.')
+ if hess is None and hessp is None:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is required for Krylov trust-region minimization')
+
+ # tol_rel specifies the termination tolerance relative to the initial
+ # gradient norm in the Krylov subspace iteration.
+
+ # - tol_rel_i specifies the tolerance for interior convergence.
+ # - tol_rel_b specifies the tolerance for boundary convergence.
+ # in nonlinear programming applications it is not necessary to solve
+ # the boundary case as exact as the interior case.
+
+ # - setting tol_rel_i=-2 leads to a forcing sequence in the Krylov
+ # subspace iteration leading to quadratic convergence if eventually
+ # the trust region stays inactive.
+ # - setting tol_rel_b=-3 leads to a forcing sequence in the Krylov
+ # subspace iteration leading to superlinear convergence as long
+ # as the iterates hit the trust region boundary.
+
+ # For details consult the documentation of trlib_krylov_min
+ # in _trlib/trlib_krylov.h
+ #
+ # Optimality of this choice of parameters among a range of possibilities
+ # has been tested on the unconstrained subset of the CUTEst library.
+
+ if inexact:
+ return _minimize_trust_region(fun, x0, args=args, jac=jac,
+ hess=hess, hessp=hessp,
+ subproblem=get_trlib_quadratic_subproblem(
+ tol_rel_i=-2.0, tol_rel_b=-3.0,
+ disp=trust_region_options.get('disp', False)
+ ),
+ **trust_region_options)
+ else:
+ return _minimize_trust_region(fun, x0, args=args, jac=jac,
+ hess=hess, hessp=hessp,
+ subproblem=get_trlib_quadratic_subproblem(
+ tol_rel_i=1e-8, tol_rel_b=1e-6,
+ disp=trust_region_options.get('disp', False)
+ ),
+ **trust_region_options)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_ncg.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_ncg.py
new file mode 100644
index 0000000000000000000000000000000000000000..fed17ff8b84eaf019c0ad69a03f260ca674477ad
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_trustregion_ncg.py
@@ -0,0 +1,126 @@
+"""Newton-CG trust-region optimization."""
+import math
+
+import numpy as np
+import scipy.linalg
+from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
+
+__all__ = []
+
+
+def _minimize_trust_ncg(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ **trust_region_options):
+ """
+ Minimization of scalar function of one or more variables using
+ the Newton conjugate gradient trust-region algorithm.
+
+ Options
+ -------
+ initial_trust_radius : float
+ Initial trust-region radius.
+ max_trust_radius : float
+ Maximum value of the trust-region radius. No steps that are longer
+ than this value will be proposed.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than `gtol` before successful
+ termination.
+
+ """
+ if jac is None:
+ raise ValueError('Jacobian is required for Newton-CG trust-region '
+ 'minimization')
+ if hess is None and hessp is None:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is required for Newton-CG trust-region minimization')
+ return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess,
+ hessp=hessp, subproblem=CGSteihaugSubproblem,
+ **trust_region_options)
+
+
+class CGSteihaugSubproblem(BaseQuadraticSubproblem):
+ """Quadratic subproblem solved by a conjugate gradient method"""
+ def solve(self, trust_radius):
+ """
+ Solve the subproblem using a conjugate gradient method.
+
+ Parameters
+ ----------
+ trust_radius : float
+ We are allowed to wander only this far away from the origin.
+
+ Returns
+ -------
+ p : ndarray
+ The proposed step.
+ hits_boundary : bool
+ True if the proposed step is on the boundary of the trust region.
+
+ Notes
+ -----
+ This is algorithm (7.2) of Nocedal and Wright 2nd edition.
+ Only the function that computes the Hessian-vector product is required.
+ The Hessian itself is not required, and the Hessian does
+ not need to be positive semidefinite.
+ """
+
+ # get the norm of jacobian and define the origin
+ p_origin = np.zeros_like(self.jac)
+
+ # define a default tolerance
+ tolerance = min(0.5, math.sqrt(self.jac_mag)) * self.jac_mag
+
+ # Stop the method if the search direction
+ # is a direction of nonpositive curvature.
+ if self.jac_mag < tolerance:
+ hits_boundary = False
+ return p_origin, hits_boundary
+
+ # init the state for the first iteration
+ z = p_origin
+ r = self.jac
+ d = -r
+
+ # Search for the min of the approximation of the objective function.
+ while True:
+
+ # do an iteration
+ Bd = self.hessp(d)
+ dBd = np.dot(d, Bd)
+ if dBd <= 0:
+ # Look at the two boundary points.
+ # Find both values of t to get the boundary points such that
+ # ||z + t d|| == trust_radius
+ # and then choose the one with the predicted min value.
+ ta, tb = self.get_boundaries_intersections(z, d, trust_radius)
+ pa = z + ta * d
+ pb = z + tb * d
+ if self(pa) < self(pb):
+ p_boundary = pa
+ else:
+ p_boundary = pb
+ hits_boundary = True
+ return p_boundary, hits_boundary
+ r_squared = np.dot(r, r)
+ alpha = r_squared / dBd
+ z_next = z + alpha * d
+ if scipy.linalg.norm(z_next) >= trust_radius:
+ # Find t >= 0 to get the boundary point such that
+ # ||z + t d|| == trust_radius
+ ta, tb = self.get_boundaries_intersections(z, d, trust_radius)
+ p_boundary = z + tb * d
+ hits_boundary = True
+ return p_boundary, hits_boundary
+ r_next = r + alpha * Bd
+ r_next_squared = np.dot(r_next, r_next)
+ if math.sqrt(r_next_squared) < tolerance:
+ hits_boundary = False
+ return z_next, hits_boundary
+ beta_next = r_next_squared / r_squared
+ d_next = -r_next + beta_next * d
+
+ # update the state for the next iteration
+ z = z_next
+ r = r_next
+ d = d_next
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_tstutils.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_tstutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a580b9c70acb910ee7578994723f2ebe217941a1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_tstutils.py
@@ -0,0 +1,972 @@
+r"""
+Parameters used in test and benchmark methods.
+
+Collections of test cases suitable for testing 1-D root-finders
+ 'original': The original benchmarking functions.
+ Real-valued functions of real-valued inputs on an interval
+ with a zero.
+ f1, .., f3 are continuous and infinitely differentiable
+ f4 has a left- and right- discontinuity at the root
+ f5 has a root at 1 replacing a 1st order pole
+ f6 is randomly positive on one side of the root,
+ randomly negative on the other.
+ f4 - f6 are not continuous at the root.
+
+ 'aps': The test problems in the 1995 paper
+ TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions"
+ by Alefeld, Potra and Shi. Real-valued functions of
+ real-valued inputs on an interval with a zero.
+ Suitable for methods which start with an enclosing interval, and
+ derivatives up to 2nd order.
+
+ 'complex': Some complex-valued functions of complex-valued inputs.
+ No enclosing bracket is provided.
+ Suitable for methods which use one or more starting values, and
+ derivatives up to 2nd order.
+
+ The test cases are provided as a list of dictionaries. The dictionary
+ keys will be a subset of:
+ ["f", "fprime", "fprime2", "args", "bracket", "smoothness",
+ "a", "b", "x0", "x1", "root", "ID"]
+"""
+
+# Sources:
+# [1] Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
+# "Algorithm 748: Enclosing Zeros of Continuous Functions",
+# ACM Trans. Math. Softw. Volume 221(1995)
+# https://dl.acm.org/doi/10.1145/210089.210111
+# [2] Chandrupatla, Tirupathi R. "A new hybrid quadratic/bisection algorithm
+# for finding the zero of a nonlinear function without using derivatives."
+# Advances in Engineering Software 28.3 (1997): 145-149.
+
+from random import random
+
+import numpy as np
+
+from scipy.optimize import _zeros_py as cc
+from scipy._lib._array_api import array_namespace
+
+# "description" refers to the original functions
+description = """
+f2 is a symmetric parabola, x**2 - 1
+f3 is a quartic polynomial with large hump in interval
+f4 is step function with a discontinuity at 1
+f5 is a hyperbola with vertical asymptote at 1
+f6 has random values positive to left of 1, negative to right
+
+Of course, these are not real problems. They just test how the
+'good' solvers behave in bad circumstances where bisection is
+really the best. A good solver should not be much worse than
+bisection in such circumstance, while being faster for smooth
+monotone sorts of functions.
+"""
+
+
+def f1(x):
+ r"""f1 is a quadratic with roots at 0 and 1"""
+ return x * (x - 1.)
+
+
+def f1_fp(x):
+ return 2 * x - 1
+
+
+def f1_fpp(x):
+ return 2
+
+
+def f2(x):
+ r"""f2 is a symmetric parabola, x**2 - 1"""
+ return x**2 - 1
+
+
+def f2_fp(x):
+ return 2 * x
+
+
+def f2_fpp(x):
+ return 2
+
+
+def f3(x):
+ r"""A quartic with roots at 0, 1, 2 and 3"""
+ return x * (x - 1.) * (x - 2.) * (x - 3.) # x**4 - 6x**3 + 11x**2 - 6x
+
+
+def f3_fp(x):
+ return 4 * x**3 - 18 * x**2 + 22 * x - 6
+
+
+def f3_fpp(x):
+ return 12 * x**2 - 36 * x + 22
+
+
+def f4(x):
+ r"""Piecewise linear, left- and right- discontinuous at x=1, the root."""
+ if x > 1:
+ return 1.0 + .1 * x
+ if x < 1:
+ return -1.0 + .1 * x
+ return 0
+
+
+def f5(x):
+ r"""
+ Hyperbola with a pole at x=1, but pole replaced with 0. Not continuous at root.
+ """
+ if x != 1:
+ return 1.0 / (1. - x)
+ return 0
+
+
+# f6(x) returns random value. Without memoization, calling twice with the
+# same x returns different values, hence a "random value", not a
+# "function with random values"
+_f6_cache = {}
+def f6(x):
+ v = _f6_cache.get(x, None)
+ if v is None:
+ if x > 1:
+ v = random()
+ elif x < 1:
+ v = -random()
+ else:
+ v = 0
+ _f6_cache[x] = v
+ return v
+
+
+# Each Original test case has
+# - a function and its two derivatives,
+# - additional arguments,
+# - a bracket enclosing a root,
+# - the order of differentiability (smoothness) on this interval
+# - a starting value for methods which don't require a bracket
+# - the root (inside the bracket)
+# - an Identifier of the test case
+
+_ORIGINAL_TESTS_KEYS = [
+ "f", "fprime", "fprime2", "args", "bracket", "smoothness", "x0", "root", "ID"
+]
+_ORIGINAL_TESTS = [
+ [f1, f1_fp, f1_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.01.00"],
+ [f2, f2_fp, f2_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.02.00"],
+ [f3, f3_fp, f3_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.03.00"],
+ [f4, None, None, (), [0.5, np.sqrt(3)], -1, 0.6, 1.0, "original.04.00"],
+ [f5, None, None, (), [0.5, np.sqrt(3)], -1, 0.6, 1.0, "original.05.00"],
+ [f6, None, None, (), [0.5, np.sqrt(3)], -np.inf, 0.6, 1.0, "original.05.00"]
+]
+
+_ORIGINAL_TESTS_DICTS = [
+ dict(zip(_ORIGINAL_TESTS_KEYS, testcase)) for testcase in _ORIGINAL_TESTS
+]
+
+# ##################
+# "APS" test cases
+# Functions and test cases that appear in [1]
+
+
+def aps01_f(x):
+ r"""Straightforward sum of trigonometric function and polynomial"""
+ return np.sin(x) - x / 2
+
+
+def aps01_fp(x):
+ return np.cos(x) - 1.0 / 2
+
+
+def aps01_fpp(x):
+ return -np.sin(x)
+
+
+def aps02_f(x):
+ r"""poles at x=n**2, 1st and 2nd derivatives at root are also close to 0"""
+ ii = np.arange(1, 21)
+ return -2 * np.sum((2 * ii - 5)**2 / (x - ii**2)**3)
+
+
+def aps02_fp(x):
+ ii = np.arange(1, 21)
+ return 6 * np.sum((2 * ii - 5)**2 / (x - ii**2)**4)
+
+
+def aps02_fpp(x):
+ ii = np.arange(1, 21)
+ return 24 * np.sum((2 * ii - 5)**2 / (x - ii**2)**5)
+
+
+def aps03_f(x, a, b):
+ r"""Rapidly changing at the root"""
+ return a * x * np.exp(b * x)
+
+
+def aps03_fp(x, a, b):
+ return a * (b * x + 1) * np.exp(b * x)
+
+
+def aps03_fpp(x, a, b):
+ return a * (b * (b * x + 1) + b) * np.exp(b * x)
+
+
+def aps04_f(x, n, a):
+ r"""Medium-degree polynomial"""
+ return x**n - a
+
+
+def aps04_fp(x, n, a):
+ return n * x**(n - 1)
+
+
+def aps04_fpp(x, n, a):
+ return n * (n - 1) * x**(n - 2)
+
+
+def aps05_f(x):
+ r"""Simple Trigonometric function"""
+ return np.sin(x) - 1.0 / 2
+
+
+def aps05_fp(x):
+ return np.cos(x)
+
+
+def aps05_fpp(x):
+ return -np.sin(x)
+
+
+def aps06_f(x, n):
+ r"""Exponential rapidly changing from -1 to 1 at x=0"""
+ return 2 * x * np.exp(-n) - 2 * np.exp(-n * x) + 1
+
+
+def aps06_fp(x, n):
+ return 2 * np.exp(-n) + 2 * n * np.exp(-n * x)
+
+
+def aps06_fpp(x, n):
+ return -2 * n * n * np.exp(-n * x)
+
+
+def aps07_f(x, n):
+ r"""Upside down parabola with parametrizable height"""
+ return (1 + (1 - n)**2) * x - (1 - n * x)**2
+
+
+def aps07_fp(x, n):
+ return (1 + (1 - n)**2) + 2 * n * (1 - n * x)
+
+
+def aps07_fpp(x, n):
+ return -2 * n * n
+
+
+def aps08_f(x, n):
+ r"""Degree n polynomial"""
+ return x * x - (1 - x)**n
+
+
+def aps08_fp(x, n):
+ return 2 * x + n * (1 - x)**(n - 1)
+
+
+def aps08_fpp(x, n):
+ return 2 - n * (n - 1) * (1 - x)**(n - 2)
+
+
+def aps09_f(x, n):
+ r"""Upside down quartic with parametrizable height"""
+ return (1 + (1 - n)**4) * x - (1 - n * x)**4
+
+
+def aps09_fp(x, n):
+ return (1 + (1 - n)**4) + 4 * n * (1 - n * x)**3
+
+
+def aps09_fpp(x, n):
+ return -12 * n * (1 - n * x)**2
+
+
+def aps10_f(x, n):
+ r"""Exponential plus a polynomial"""
+ return np.exp(-n * x) * (x - 1) + x**n
+
+
+def aps10_fp(x, n):
+ return np.exp(-n * x) * (-n * (x - 1) + 1) + n * x**(n - 1)
+
+
+def aps10_fpp(x, n):
+ return (np.exp(-n * x) * (-n * (-n * (x - 1) + 1) + -n * x)
+ + n * (n - 1) * x**(n - 2))
+
+
+def aps11_f(x, n):
+ r"""Rational function with a zero at x=1/n and a pole at x=0"""
+ return (n * x - 1) / ((n - 1) * x)
+
+
+def aps11_fp(x, n):
+ return 1 / (n - 1) / x**2
+
+
+def aps11_fpp(x, n):
+ return -2 / (n - 1) / x**3
+
+
+def aps12_f(x, n):
+ r"""nth root of x, with a zero at x=n"""
+ return np.power(x, 1.0 / n) - np.power(n, 1.0 / n)
+
+
+def aps12_fp(x, n):
+ return np.power(x, (1.0 - n) / n) / n
+
+
+def aps12_fpp(x, n):
+ return np.power(x, (1.0 - 2 * n) / n) * (1.0 / n) * (1.0 - n) / n
+
+
+_MAX_EXPABLE = np.log(np.finfo(float).max)
+
+
+def aps13_f(x):
+ r"""Function with *all* derivatives 0 at the root"""
+ if x == 0:
+ return 0
+ # x2 = 1.0/x**2
+ # if x2 > 708:
+ # return 0
+ y = 1 / x**2
+ if y > _MAX_EXPABLE:
+ return 0
+ return x / np.exp(y)
+
+
+def aps13_fp(x):
+ if x == 0:
+ return 0
+ y = 1 / x**2
+ if y > _MAX_EXPABLE:
+ return 0
+ return (1 + 2 / x**2) / np.exp(y)
+
+
+def aps13_fpp(x):
+ if x == 0:
+ return 0
+ y = 1 / x**2
+ if y > _MAX_EXPABLE:
+ return 0
+ return 2 * (2 - x**2) / x**5 / np.exp(y)
+
+
+def aps14_f(x, n):
+ r"""0 for negative x-values, trigonometric+linear for x positive"""
+ if x <= 0:
+ return -n / 20.0
+ return n / 20.0 * (x / 1.5 + np.sin(x) - 1)
+
+
+def aps14_fp(x, n):
+ if x <= 0:
+ return 0
+ return n / 20.0 * (1.0 / 1.5 + np.cos(x))
+
+
+def aps14_fpp(x, n):
+ if x <= 0:
+ return 0
+ return -n / 20.0 * (np.sin(x))
+
+
+def aps15_f(x, n):
+ r"""piecewise linear, constant outside of [0, 0.002/(1+n)]"""
+ if x < 0:
+ return -0.859
+ if x > 2 * 1e-3 / (1 + n):
+ return np.e - 1.859
+ return np.exp((n + 1) * x / 2 * 1000) - 1.859
+
+
+def aps15_fp(x, n):
+ if not 0 <= x <= 2 * 1e-3 / (1 + n):
+ return np.e - 1.859
+ return np.exp((n + 1) * x / 2 * 1000) * (n + 1) / 2 * 1000
+
+
+def aps15_fpp(x, n):
+ if not 0 <= x <= 2 * 1e-3 / (1 + n):
+ return np.e - 1.859
+ return np.exp((n + 1) * x / 2 * 1000) * (n + 1) / 2 * 1000 * (n + 1) / 2 * 1000
+
+
+# Each APS test case has
+# - a function and its two derivatives,
+# - additional arguments,
+# - a bracket enclosing a root,
+# - the order of differentiability of the function on this interval
+# - a starting value for methods which don't require a bracket
+# - the root (inside the bracket)
+# - an Identifier of the test case
+#
+# Algorithm 748 is a bracketing algorithm so a bracketing interval was provided
+# in [1] for each test case. Newton and Halley methods need a single
+# starting point x0, which was chosen to be near the middle of the interval,
+# unless that would have made the problem too easy.
+
+_APS_TESTS_KEYS = [
+ "f", "fprime", "fprime2", "args", "bracket", "smoothness", "x0", "root", "ID"
+]
+_APS_TESTS = [
+ [aps01_f, aps01_fp, aps01_fpp, (), [np.pi / 2, np.pi], np.inf,
+ 3, 1.89549426703398094e+00, "aps.01.00"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [1 + 1e-9, 4 - 1e-9], np.inf,
+ 2, 3.02291534727305677e+00, "aps.02.00"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [4 + 1e-9, 9 - 1e-9], np.inf,
+ 5, 6.68375356080807848e+00, "aps.02.01"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [9 + 1e-9, 16 - 1e-9], np.inf,
+ 10, 1.12387016550022114e+01, "aps.02.02"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [16 + 1e-9, 25 - 1e-9], np.inf,
+ 17, 1.96760000806234103e+01, "aps.02.03"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [25 + 1e-9, 36 - 1e-9], np.inf,
+ 26, 2.98282273265047557e+01, "aps.02.04"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [36 + 1e-9, 49 - 1e-9], np.inf,
+ 37, 4.19061161952894139e+01, "aps.02.05"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [49 + 1e-9, 64 - 1e-9], np.inf,
+ 50, 5.59535958001430913e+01, "aps.02.06"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [64 + 1e-9, 81 - 1e-9], np.inf,
+ 65, 7.19856655865877997e+01, "aps.02.07"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [81 + 1e-9, 100 - 1e-9], np.inf,
+ 82, 9.00088685391666701e+01, "aps.02.08"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [100 + 1e-9, 121 - 1e-9], np.inf,
+ 101, 1.10026532748330197e+02, "aps.02.09"],
+ [aps03_f, aps03_fp, aps03_fpp, (-40, -1), [-9, 31], np.inf,
+ -2, 0, "aps.03.00"],
+ [aps03_f, aps03_fp, aps03_fpp, (-100, -2), [-9, 31], np.inf,
+ -2, 0, "aps.03.01"],
+ [aps03_f, aps03_fp, aps03_fpp, (-200, -3), [-9, 31], np.inf,
+ -2, 0, "aps.03.02"],
+ [aps04_f, aps04_fp, aps04_fpp, (4, 0.2), [0, 5], np.inf,
+ 2.5, 6.68740304976422006e-01, "aps.04.00"],
+ [aps04_f, aps04_fp, aps04_fpp, (6, 0.2), [0, 5], np.inf,
+ 2.5, 7.64724491331730039e-01, "aps.04.01"],
+ [aps04_f, aps04_fp, aps04_fpp, (8, 0.2), [0, 5], np.inf,
+ 2.5, 8.17765433957942545e-01, "aps.04.02"],
+ [aps04_f, aps04_fp, aps04_fpp, (10, 0.2), [0, 5], np.inf,
+ 2.5, 8.51339922520784609e-01, "aps.04.03"],
+ [aps04_f, aps04_fp, aps04_fpp, (12, 0.2), [0, 5], np.inf,
+ 2.5, 8.74485272221167897e-01, "aps.04.04"],
+ [aps04_f, aps04_fp, aps04_fpp, (4, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.05"],
+ [aps04_f, aps04_fp, aps04_fpp, (6, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.06"],
+ [aps04_f, aps04_fp, aps04_fpp, (8, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.07"],
+ [aps04_f, aps04_fp, aps04_fpp, (10, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.08"],
+ [aps04_f, aps04_fp, aps04_fpp, (12, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.09"],
+ [aps04_f, aps04_fp, aps04_fpp, (8, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.10"],
+ [aps04_f, aps04_fp, aps04_fpp, (10, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.11"],
+ [aps04_f, aps04_fp, aps04_fpp, (12, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.12"],
+ [aps04_f, aps04_fp, aps04_fpp, (14, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.13"],
+ [aps05_f, aps05_fp, aps05_fpp, (), [0, 1.5], np.inf,
+ 1.3, np.pi / 6, "aps.05.00"],
+ [aps06_f, aps06_fp, aps06_fpp, (1,), [0, 1], np.inf,
+ 0.5, 4.22477709641236709e-01, "aps.06.00"],
+ [aps06_f, aps06_fp, aps06_fpp, (2,), [0, 1], np.inf,
+ 0.5, 3.06699410483203705e-01, "aps.06.01"],
+ [aps06_f, aps06_fp, aps06_fpp, (3,), [0, 1], np.inf,
+ 0.5, 2.23705457654662959e-01, "aps.06.02"],
+ [aps06_f, aps06_fp, aps06_fpp, (4,), [0, 1], np.inf,
+ 0.5, 1.71719147519508369e-01, "aps.06.03"],
+ [aps06_f, aps06_fp, aps06_fpp, (5,), [0, 1], np.inf,
+ 0.4, 1.38257155056824066e-01, "aps.06.04"],
+ [aps06_f, aps06_fp, aps06_fpp, (20,), [0, 1], np.inf,
+ 0.1, 3.46573590208538521e-02, "aps.06.05"],
+ [aps06_f, aps06_fp, aps06_fpp, (40,), [0, 1], np.inf,
+ 5e-02, 1.73286795139986315e-02, "aps.06.06"],
+ [aps06_f, aps06_fp, aps06_fpp, (60,), [0, 1], np.inf,
+ 1.0 / 30, 1.15524530093324210e-02, "aps.06.07"],
+ [aps06_f, aps06_fp, aps06_fpp, (80,), [0, 1], np.inf,
+ 2.5e-02, 8.66433975699931573e-03, "aps.06.08"],
+ [aps06_f, aps06_fp, aps06_fpp, (100,), [0, 1], np.inf,
+ 2e-02, 6.93147180559945415e-03, "aps.06.09"],
+ [aps07_f, aps07_fp, aps07_fpp, (5,), [0, 1], np.inf,
+ 0.4, 3.84025518406218985e-02, "aps.07.00"],
+ [aps07_f, aps07_fp, aps07_fpp, (10,), [0, 1], np.inf,
+ 0.4, 9.90000999800049949e-03, "aps.07.01"],
+ [aps07_f, aps07_fp, aps07_fpp, (20,), [0, 1], np.inf,
+ 0.4, 2.49375003906201174e-03, "aps.07.02"],
+ [aps08_f, aps08_fp, aps08_fpp, (2,), [0, 1], np.inf,
+ 0.9, 0.5, "aps.08.00"],
+ [aps08_f, aps08_fp, aps08_fpp, (5,), [0, 1], np.inf,
+ 0.9, 3.45954815848242059e-01, "aps.08.01"],
+ [aps08_f, aps08_fp, aps08_fpp, (10,), [0, 1], np.inf,
+ 0.9, 2.45122333753307220e-01, "aps.08.02"],
+ [aps08_f, aps08_fp, aps08_fpp, (15,), [0, 1], np.inf,
+ 0.9, 1.95547623536565629e-01, "aps.08.03"],
+ [aps08_f, aps08_fp, aps08_fpp, (20,), [0, 1], np.inf,
+ 0.9, 1.64920957276440960e-01, "aps.08.04"],
+ [aps09_f, aps09_fp, aps09_fpp, (1,), [0, 1], np.inf,
+ 0.5, 2.75508040999484394e-01, "aps.09.00"],
+ [aps09_f, aps09_fp, aps09_fpp, (2,), [0, 1], np.inf,
+ 0.5, 1.37754020499742197e-01, "aps.09.01"],
+ [aps09_f, aps09_fp, aps09_fpp, (4,), [0, 1], np.inf,
+ 0.5, 1.03052837781564422e-02, "aps.09.02"],
+ [aps09_f, aps09_fp, aps09_fpp, (5,), [0, 1], np.inf,
+ 0.5, 3.61710817890406339e-03, "aps.09.03"],
+ [aps09_f, aps09_fp, aps09_fpp, (8,), [0, 1], np.inf,
+ 0.5, 4.10872918496395375e-04, "aps.09.04"],
+ [aps09_f, aps09_fp, aps09_fpp, (15,), [0, 1], np.inf,
+ 0.5, 2.59895758929076292e-05, "aps.09.05"],
+ [aps09_f, aps09_fp, aps09_fpp, (20,), [0, 1], np.inf,
+ 0.5, 7.66859512218533719e-06, "aps.09.06"],
+ [aps10_f, aps10_fp, aps10_fpp, (1,), [0, 1], np.inf,
+ 0.9, 4.01058137541547011e-01, "aps.10.00"],
+ [aps10_f, aps10_fp, aps10_fpp, (5,), [0, 1], np.inf,
+ 0.9, 5.16153518757933583e-01, "aps.10.01"],
+ [aps10_f, aps10_fp, aps10_fpp, (10,), [0, 1], np.inf,
+ 0.9, 5.39522226908415781e-01, "aps.10.02"],
+ [aps10_f, aps10_fp, aps10_fpp, (15,), [0, 1], np.inf,
+ 0.9, 5.48182294340655241e-01, "aps.10.03"],
+ [aps10_f, aps10_fp, aps10_fpp, (20,), [0, 1], np.inf,
+ 0.9, 5.52704666678487833e-01, "aps.10.04"],
+ [aps11_f, aps11_fp, aps11_fpp, (2,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 2, "aps.11.00"],
+ [aps11_f, aps11_fp, aps11_fpp, (5,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 5, "aps.11.01"],
+ [aps11_f, aps11_fp, aps11_fpp, (15,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 15, "aps.11.02"],
+ [aps11_f, aps11_fp, aps11_fpp, (20,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 20, "aps.11.03"],
+ [aps12_f, aps12_fp, aps12_fpp, (2,), [1, 100], np.inf,
+ 1.1, 2, "aps.12.00"],
+ [aps12_f, aps12_fp, aps12_fpp, (3,), [1, 100], np.inf,
+ 1.1, 3, "aps.12.01"],
+ [aps12_f, aps12_fp, aps12_fpp, (4,), [1, 100], np.inf,
+ 1.1, 4, "aps.12.02"],
+ [aps12_f, aps12_fp, aps12_fpp, (5,), [1, 100], np.inf,
+ 1.1, 5, "aps.12.03"],
+ [aps12_f, aps12_fp, aps12_fpp, (6,), [1, 100], np.inf,
+ 1.1, 6, "aps.12.04"],
+ [aps12_f, aps12_fp, aps12_fpp, (7,), [1, 100], np.inf,
+ 1.1, 7, "aps.12.05"],
+ [aps12_f, aps12_fp, aps12_fpp, (9,), [1, 100], np.inf,
+ 1.1, 9, "aps.12.06"],
+ [aps12_f, aps12_fp, aps12_fpp, (11,), [1, 100], np.inf,
+ 1.1, 11, "aps.12.07"],
+ [aps12_f, aps12_fp, aps12_fpp, (13,), [1, 100], np.inf,
+ 1.1, 13, "aps.12.08"],
+ [aps12_f, aps12_fp, aps12_fpp, (15,), [1, 100], np.inf,
+ 1.1, 15, "aps.12.09"],
+ [aps12_f, aps12_fp, aps12_fpp, (17,), [1, 100], np.inf,
+ 1.1, 17, "aps.12.10"],
+ [aps12_f, aps12_fp, aps12_fpp, (19,), [1, 100], np.inf,
+ 1.1, 19, "aps.12.11"],
+ [aps12_f, aps12_fp, aps12_fpp, (21,), [1, 100], np.inf,
+ 1.1, 21, "aps.12.12"],
+ [aps12_f, aps12_fp, aps12_fpp, (23,), [1, 100], np.inf,
+ 1.1, 23, "aps.12.13"],
+ [aps12_f, aps12_fp, aps12_fpp, (25,), [1, 100], np.inf,
+ 1.1, 25, "aps.12.14"],
+ [aps12_f, aps12_fp, aps12_fpp, (27,), [1, 100], np.inf,
+ 1.1, 27, "aps.12.15"],
+ [aps12_f, aps12_fp, aps12_fpp, (29,), [1, 100], np.inf,
+ 1.1, 29, "aps.12.16"],
+ [aps12_f, aps12_fp, aps12_fpp, (31,), [1, 100], np.inf,
+ 1.1, 31, "aps.12.17"],
+ [aps12_f, aps12_fp, aps12_fpp, (33,), [1, 100], np.inf,
+ 1.1, 33, "aps.12.18"],
+ [aps13_f, aps13_fp, aps13_fpp, (), [-1, 4], np.inf,
+ 1.5, 0, "aps.13.00"],
+ [aps14_f, aps14_fp, aps14_fpp, (1,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.00"],
+ [aps14_f, aps14_fp, aps14_fpp, (2,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.01"],
+ [aps14_f, aps14_fp, aps14_fpp, (3,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.02"],
+ [aps14_f, aps14_fp, aps14_fpp, (4,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.03"],
+ [aps14_f, aps14_fp, aps14_fpp, (5,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.04"],
+ [aps14_f, aps14_fp, aps14_fpp, (6,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.05"],
+ [aps14_f, aps14_fp, aps14_fpp, (7,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.06"],
+ [aps14_f, aps14_fp, aps14_fpp, (8,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.07"],
+ [aps14_f, aps14_fp, aps14_fpp, (9,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.08"],
+ [aps14_f, aps14_fp, aps14_fpp, (10,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.09"],
+ [aps14_f, aps14_fp, aps14_fpp, (11,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.10"],
+ [aps14_f, aps14_fp, aps14_fpp, (12,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.11"],
+ [aps14_f, aps14_fp, aps14_fpp, (13,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.12"],
+ [aps14_f, aps14_fp, aps14_fpp, (14,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.13"],
+ [aps14_f, aps14_fp, aps14_fpp, (15,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.14"],
+ [aps14_f, aps14_fp, aps14_fpp, (16,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.15"],
+ [aps14_f, aps14_fp, aps14_fpp, (17,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.16"],
+ [aps14_f, aps14_fp, aps14_fpp, (18,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.17"],
+ [aps14_f, aps14_fp, aps14_fpp, (19,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.18"],
+ [aps14_f, aps14_fp, aps14_fpp, (20,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.19"],
+ [aps14_f, aps14_fp, aps14_fpp, (21,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.20"],
+ [aps14_f, aps14_fp, aps14_fpp, (22,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.21"],
+ [aps14_f, aps14_fp, aps14_fpp, (23,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.22"],
+ [aps14_f, aps14_fp, aps14_fpp, (24,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.23"],
+ [aps14_f, aps14_fp, aps14_fpp, (25,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.24"],
+ [aps14_f, aps14_fp, aps14_fpp, (26,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.25"],
+ [aps14_f, aps14_fp, aps14_fpp, (27,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.26"],
+ [aps14_f, aps14_fp, aps14_fpp, (28,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.27"],
+ [aps14_f, aps14_fp, aps14_fpp, (29,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.28"],
+ [aps14_f, aps14_fp, aps14_fpp, (30,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.29"],
+ [aps14_f, aps14_fp, aps14_fpp, (31,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.30"],
+ [aps14_f, aps14_fp, aps14_fpp, (32,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.31"],
+ [aps14_f, aps14_fp, aps14_fpp, (33,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.32"],
+ [aps14_f, aps14_fp, aps14_fpp, (34,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.33"],
+ [aps14_f, aps14_fp, aps14_fpp, (35,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.34"],
+ [aps14_f, aps14_fp, aps14_fpp, (36,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.35"],
+ [aps14_f, aps14_fp, aps14_fpp, (37,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.36"],
+ [aps14_f, aps14_fp, aps14_fpp, (38,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.37"],
+ [aps14_f, aps14_fp, aps14_fpp, (39,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.38"],
+ [aps14_f, aps14_fp, aps14_fpp, (40,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.39"],
+ [aps15_f, aps15_fp, aps15_fpp, (20,), [-1000, 1e-4], 0,
+ -2, 5.90513055942197166e-05, "aps.15.00"],
+ [aps15_f, aps15_fp, aps15_fpp, (21,), [-1000, 1e-4], 0,
+ -2, 5.63671553399369967e-05, "aps.15.01"],
+ [aps15_f, aps15_fp, aps15_fpp, (22,), [-1000, 1e-4], 0,
+ -2, 5.39164094555919196e-05, "aps.15.02"],
+ [aps15_f, aps15_fp, aps15_fpp, (23,), [-1000, 1e-4], 0,
+ -2, 5.16698923949422470e-05, "aps.15.03"],
+ [aps15_f, aps15_fp, aps15_fpp, (24,), [-1000, 1e-4], 0,
+ -2, 4.96030966991445609e-05, "aps.15.04"],
+ [aps15_f, aps15_fp, aps15_fpp, (25,), [-1000, 1e-4], 0,
+ -2, 4.76952852876389951e-05, "aps.15.05"],
+ [aps15_f, aps15_fp, aps15_fpp, (26,), [-1000, 1e-4], 0,
+ -2, 4.59287932399486662e-05, "aps.15.06"],
+ [aps15_f, aps15_fp, aps15_fpp, (27,), [-1000, 1e-4], 0,
+ -2, 4.42884791956647841e-05, "aps.15.07"],
+ [aps15_f, aps15_fp, aps15_fpp, (28,), [-1000, 1e-4], 0,
+ -2, 4.27612902578832391e-05, "aps.15.08"],
+ [aps15_f, aps15_fp, aps15_fpp, (29,), [-1000, 1e-4], 0,
+ -2, 4.13359139159538030e-05, "aps.15.09"],
+ [aps15_f, aps15_fp, aps15_fpp, (30,), [-1000, 1e-4], 0,
+ -2, 4.00024973380198076e-05, "aps.15.10"],
+ [aps15_f, aps15_fp, aps15_fpp, (31,), [-1000, 1e-4], 0,
+ -2, 3.87524192962066869e-05, "aps.15.11"],
+ [aps15_f, aps15_fp, aps15_fpp, (32,), [-1000, 1e-4], 0,
+ -2, 3.75781035599579910e-05, "aps.15.12"],
+ [aps15_f, aps15_fp, aps15_fpp, (33,), [-1000, 1e-4], 0,
+ -2, 3.64728652199592355e-05, "aps.15.13"],
+ [aps15_f, aps15_fp, aps15_fpp, (34,), [-1000, 1e-4], 0,
+ -2, 3.54307833565318273e-05, "aps.15.14"],
+ [aps15_f, aps15_fp, aps15_fpp, (35,), [-1000, 1e-4], 0,
+ -2, 3.44465949299614980e-05, "aps.15.15"],
+ [aps15_f, aps15_fp, aps15_fpp, (36,), [-1000, 1e-4], 0,
+ -2, 3.35156058778003705e-05, "aps.15.16"],
+ [aps15_f, aps15_fp, aps15_fpp, (37,), [-1000, 1e-4], 0,
+ -2, 3.26336162494372125e-05, "aps.15.17"],
+ [aps15_f, aps15_fp, aps15_fpp, (38,), [-1000, 1e-4], 0,
+ -2, 3.17968568584260013e-05, "aps.15.18"],
+ [aps15_f, aps15_fp, aps15_fpp, (39,), [-1000, 1e-4], 0,
+ -2, 3.10019354369653455e-05, "aps.15.19"],
+ [aps15_f, aps15_fp, aps15_fpp, (40,), [-1000, 1e-4], 0,
+ -2, 3.02457906702100968e-05, "aps.15.20"],
+ [aps15_f, aps15_fp, aps15_fpp, (100,), [-1000, 1e-4], 0,
+ -2, 1.22779942324615231e-05, "aps.15.21"],
+ [aps15_f, aps15_fp, aps15_fpp, (200,), [-1000, 1e-4], 0,
+ -2, 6.16953939044086617e-06, "aps.15.22"],
+ [aps15_f, aps15_fp, aps15_fpp, (300,), [-1000, 1e-4], 0,
+ -2, 4.11985852982928163e-06, "aps.15.23"],
+ [aps15_f, aps15_fp, aps15_fpp, (400,), [-1000, 1e-4], 0,
+ -2, 3.09246238772721682e-06, "aps.15.24"],
+ [aps15_f, aps15_fp, aps15_fpp, (500,), [-1000, 1e-4], 0,
+ -2, 2.47520442610501789e-06, "aps.15.25"],
+ [aps15_f, aps15_fp, aps15_fpp, (600,), [-1000, 1e-4], 0,
+ -2, 2.06335676785127107e-06, "aps.15.26"],
+ [aps15_f, aps15_fp, aps15_fpp, (700,), [-1000, 1e-4], 0,
+ -2, 1.76901200781542651e-06, "aps.15.27"],
+ [aps15_f, aps15_fp, aps15_fpp, (800,), [-1000, 1e-4], 0,
+ -2, 1.54816156988591016e-06, "aps.15.28"],
+ [aps15_f, aps15_fp, aps15_fpp, (900,), [-1000, 1e-4], 0,
+ -2, 1.37633453660223511e-06, "aps.15.29"],
+ [aps15_f, aps15_fp, aps15_fpp, (1000,), [-1000, 1e-4], 0,
+ -2, 1.23883857889971403e-06, "aps.15.30"]
+]
+
+_APS_TESTS_DICTS = [dict(zip(_APS_TESTS_KEYS, testcase)) for testcase in _APS_TESTS]
+
+
+# ##################
+# "complex" test cases
+# A few simple, complex-valued, functions, defined on the complex plane.
+
+
+def cplx01_f(z, n, a):
+ r"""z**n-a: Use to find the nth root of a"""
+ return z**n - a
+
+
+def cplx01_fp(z, n, a):
+ return n * z**(n - 1)
+
+
+def cplx01_fpp(z, n, a):
+ return n * (n - 1) * z**(n - 2)
+
+
+def cplx02_f(z, a):
+ r"""e**z - a: Use to find the log of a"""
+ return np.exp(z) - a
+
+
+def cplx02_fp(z, a):
+ return np.exp(z)
+
+
+def cplx02_fpp(z, a):
+ return np.exp(z)
+
+
+# Each "complex" test case has
+# - a function and its two derivatives,
+# - additional arguments,
+# - the order of differentiability of the function on this interval
+# - two starting values x0 and x1
+# - the root
+# - an Identifier of the test case
+#
+# Algorithm 748 is a bracketing algorithm so a bracketing interval was provided
+# in [1] for each test case. Newton and Halley need a single starting point
+# x0, which was chosen to be near the middle of the interval, unless that
+# would make the problem too easy.
+
+
+_COMPLEX_TESTS_KEYS = [
+ "f", "fprime", "fprime2", "args", "smoothness", "x0", "x1", "root", "ID"
+]
+_COMPLEX_TESTS = [
+ [cplx01_f, cplx01_fp, cplx01_fpp, (2, -1), np.inf,
+ (1 + 1j), (0.5 + 0.5j), 1j, "complex.01.00"],
+ [cplx01_f, cplx01_fp, cplx01_fpp, (3, 1), np.inf,
+ (-1 + 1j), (-0.5 + 2.0j), (-0.5 + np.sqrt(3) / 2 * 1.0j),
+ "complex.01.01"],
+ [cplx01_f, cplx01_fp, cplx01_fpp, (3, -1), np.inf,
+ 1j, (0.5 + 0.5j), (0.5 + np.sqrt(3) / 2 * 1.0j),
+ "complex.01.02"],
+ [cplx01_f, cplx01_fp, cplx01_fpp, (3, 8), np.inf,
+ 5, 4, 2, "complex.01.03"],
+ [cplx02_f, cplx02_fp, cplx02_fpp, (-1,), np.inf,
+ (1 + 2j), (0.5 + 0.5j), np.pi * 1.0j, "complex.02.00"],
+ [cplx02_f, cplx02_fp, cplx02_fpp, (1j,), np.inf,
+ (1 + 2j), (0.5 + 0.5j), np.pi * 0.5j, "complex.02.01"],
+]
+
+_COMPLEX_TESTS_DICTS = [
+ dict(zip(_COMPLEX_TESTS_KEYS, testcase)) for testcase in _COMPLEX_TESTS
+]
+
+
+def _add_a_b(tests):
+ r"""Add "a" and "b" keys to each test from the "bracket" value"""
+ for d in tests:
+ for k, v in zip(['a', 'b'], d.get('bracket', [])):
+ d[k] = v
+
+
+_add_a_b(_ORIGINAL_TESTS_DICTS)
+_add_a_b(_APS_TESTS_DICTS)
+_add_a_b(_COMPLEX_TESTS_DICTS)
+
+
+def get_tests(collection='original', smoothness=None):
+ r"""Return the requested collection of test cases, as an array of dicts with subset-specific keys
+
+ Allowed values of collection:
+ 'original': The original benchmarking functions.
+ Real-valued functions of real-valued inputs on an interval with a zero.
+ f1, .., f3 are continuous and infinitely differentiable
+ f4 has a single discontinuity at the root
+ f5 has a root at 1 replacing a 1st order pole
+ f6 is randomly positive on one side of the root, randomly negative on the other
+ 'aps': The test problems in the TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions"
+ paper by Alefeld, Potra and Shi. Real-valued functions of
+ real-valued inputs on an interval with a zero.
+ Suitable for methods which start with an enclosing interval, and
+ derivatives up to 2nd order.
+ 'complex': Some complex-valued functions of complex-valued inputs.
+ No enclosing bracket is provided.
+ Suitable for methods which use one or more starting values, and
+ derivatives up to 2nd order.
+
+ The dictionary keys will be a subset of
+ ["f", "fprime", "fprime2", "args", "bracket", "a", b", "smoothness", "x0", "x1", "root", "ID"]
+ """ # noqa: E501
+ collection = collection or "original"
+ subsets = {"aps": _APS_TESTS_DICTS,
+ "complex": _COMPLEX_TESTS_DICTS,
+ "original": _ORIGINAL_TESTS_DICTS,
+ "chandrupatla": _CHANDRUPATLA_TESTS_DICTS}
+ tests = subsets.get(collection, [])
+ if smoothness is not None:
+ tests = [tc for tc in tests if tc['smoothness'] >= smoothness]
+ return tests
+
+
+# Backwards compatibility
+methods = [cc.bisect, cc.ridder, cc.brenth, cc.brentq]
+mstrings = ['cc.bisect', 'cc.ridder', 'cc.brenth', 'cc.brentq']
+functions = [f2, f3, f4, f5, f6]
+fstrings = ['f2', 'f3', 'f4', 'f5', 'f6']
+
+# ##################
+# "Chandrupatla" test cases
+# Functions and test cases that appear in [2]
+
+def fun1(x):
+ return x**3 - 2*x - 5
+fun1.root = 2.0945514815423265 # additional precision using mpmath.findroot
+
+
+def fun2(x):
+ return 1 - 1/x**2
+fun2.root = 1
+
+
+def fun3(x):
+ return (x-3)**3
+fun3.root = 3
+
+
+def fun4(x):
+ return 6*(x-2)**5
+fun4.root = 2
+
+
+def fun5(x):
+ return x**9
+fun5.root = 0
+
+
+def fun6(x):
+ return x**19
+fun6.root = 0
+
+
+def fun7(x):
+ xp = array_namespace(x)
+ return 0 if xp.abs(x) < 3.8e-4 else x*xp.exp(-x**(-2))
+fun7.root = 0
+
+
+def fun8(x):
+ xp = array_namespace(x)
+ xi = 0.61489
+ return -(3062*(1-xi)*xp.exp(-x))/(xi + (1-xi)*xp.exp(-x)) - 1013 + 1628/x
+fun8.root = 1.0375360332870405
+
+
+def fun9(x):
+ xp = array_namespace(x)
+ return xp.exp(x) - 2 - 0.01/x**2 + .000002/x**3
+fun9.root = 0.7032048403631358
+
+# Each "chandropatla" test case has
+# - a function,
+# - two starting values x0 and x1
+# - the root
+# - the number of function evaluations required by Chandrupatla's algorithm
+# - an Identifier of the test case
+#
+# Chandrupatla's is a bracketing algorithm, so a bracketing interval was
+# provided in [2] for each test case. No special support for testing with
+# secant/Newton/Halley is provided.
+
+_CHANDRUPATLA_TESTS_KEYS = ["f", "bracket", "root", "nfeval", "ID"]
+_CHANDRUPATLA_TESTS = [
+ [fun1, [2, 3], fun1.root, 7],
+ [fun1, [1, 10], fun1.root, 11],
+ [fun1, [1, 100], fun1.root, 14],
+ [fun1, [-1e4, 1e4], fun1.root, 23],
+ [fun1, [-1e10, 1e10], fun1.root, 43],
+ [fun2, [0.5, 1.51], fun2.root, 8],
+ [fun2, [1e-4, 1e4], fun2.root, 22],
+ [fun2, [1e-6, 1e6], fun2.root, 28],
+ [fun2, [1e-10, 1e10], fun2.root, 41],
+ [fun2, [1e-12, 1e12], fun2.root, 48],
+ [fun3, [0, 5], fun3.root, 21],
+ [fun3, [-10, 10], fun3.root, 23],
+ [fun3, [-1e4, 1e4], fun3.root, 36],
+ [fun3, [-1e6, 1e6], fun3.root, 45],
+ [fun3, [-1e10, 1e10], fun3.root, 55],
+ [fun4, [0, 5], fun4.root, 21],
+ [fun4, [-10, 10], fun4.root, 23],
+ [fun4, [-1e4, 1e4], fun4.root, 33],
+ [fun4, [-1e6, 1e6], fun4.root, 43],
+ [fun4, [-1e10, 1e10], fun4.root, 54],
+ [fun5, [-1, 4], fun5.root, 21],
+ [fun5, [-2, 5], fun5.root, 22],
+ [fun5, [-1, 10], fun5.root, 23],
+ [fun5, [-5, 50], fun5.root, 25],
+ [fun5, [-10, 100], fun5.root, 26],
+ [fun6, [-1., 4.], fun6.root, 21],
+ [fun6, [-2., 5.], fun6.root, 22],
+ [fun6, [-1., 10.], fun6.root, 23],
+ [fun6, [-5., 50.], fun6.root, 25],
+ [fun6, [-10., 100.], fun6.root, 26],
+ [fun7, [-1, 4], fun7.root, 8],
+ [fun7, [-2, 5], fun7.root, 8],
+ [fun7, [-1, 10], fun7.root, 11],
+ [fun7, [-5, 50], fun7.root, 18],
+ [fun7, [-10, 100], fun7.root, 19],
+ [fun8, [2e-4, 2], fun8.root, 9],
+ [fun8, [2e-4, 3], fun8.root, 10],
+ [fun8, [2e-4, 9], fun8.root, 11],
+ [fun8, [2e-4, 27], fun8.root, 12],
+ [fun8, [2e-4, 81], fun8.root, 14],
+ [fun9, [2e-4, 1], fun9.root, 7],
+ [fun9, [2e-4, 3], fun9.root, 8],
+ [fun9, [2e-4, 9], fun9.root, 10],
+ [fun9, [2e-4, 27], fun9.root, 11],
+ [fun9, [2e-4, 81], fun9.root, 13],
+]
+_CHANDRUPATLA_TESTS = [test + [f'{test[0].__name__}.{i%5+1}']
+ for i, test in enumerate(_CHANDRUPATLA_TESTS)]
+
+_CHANDRUPATLA_TESTS_DICTS = [dict(zip(_CHANDRUPATLA_TESTS_KEYS, testcase))
+ for testcase in _CHANDRUPATLA_TESTS]
+_add_a_b(_CHANDRUPATLA_TESTS_DICTS)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_zeros.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/_zeros.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..9435c34e2b7950250d0a0307bd3db7147af6144a
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/optimize/_zeros.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py b/.venv/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..e05c6cd033fda83db120f5db1bbc24c777f3949f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py
@@ -0,0 +1,1487 @@
+import warnings
+from collections import namedtuple
+import operator
+from . import _zeros
+from ._optimize import OptimizeResult
+import numpy as np
+
+
+_iter = 100
+_xtol = 2e-12
+_rtol = 4 * np.finfo(float).eps
+
+__all__ = ['newton', 'bisect', 'ridder', 'brentq', 'brenth', 'toms748',
+ 'RootResults']
+
+# Must agree with CONVERGED, SIGNERR, CONVERR, ... in zeros.h
+_ECONVERGED = 0
+_ESIGNERR = -1 # used in _chandrupatla
+_ECONVERR = -2
+_EVALUEERR = -3
+_ECALLBACK = -4
+_EINPROGRESS = 1
+
+CONVERGED = 'converged'
+SIGNERR = 'sign error'
+CONVERR = 'convergence error'
+VALUEERR = 'value error'
+INPROGRESS = 'No error'
+
+
+flag_map = {_ECONVERGED: CONVERGED, _ESIGNERR: SIGNERR, _ECONVERR: CONVERR,
+ _EVALUEERR: VALUEERR, _EINPROGRESS: INPROGRESS}
+
+
+class RootResults(OptimizeResult):
+ """Represents the root finding result.
+
+ Parameters
+ ----------
+ root : float
+ Estimated root location.
+ iterations : int
+ Number of iterations needed to find the root.
+ function_calls : int
+ Number of times the function was called.
+ flag : str
+ Description of the cause of termination.
+ method : str
+ Root finding method used.
+
+ Attributes
+ ----------
+ root : float
+ Estimated root location.
+ iterations : int
+ Number of iterations needed to find the root.
+ function_calls : int
+ Number of times the function was called.
+ converged : bool
+ True if the routine converged.
+ flag : str
+ Description of the cause of termination.
+ method : str
+ Root finding method used.
+
+ """
+
+ def __init__(self, root, iterations, function_calls, flag, method):
+ self.root = root
+ self.iterations = iterations
+ self.function_calls = function_calls
+ self.converged = flag == _ECONVERGED
+ if flag in flag_map:
+ self.flag = flag_map[flag]
+ else:
+ self.flag = flag
+ self.method = method
+
+
+def results_c(full_output, r, method):
+ if full_output:
+ x, funcalls, iterations, flag = r
+ results = RootResults(root=x,
+ iterations=iterations,
+ function_calls=funcalls,
+ flag=flag, method=method)
+ return x, results
+ else:
+ return r
+
+
+def _results_select(full_output, r, method):
+ """Select from a tuple of (root, funccalls, iterations, flag)"""
+ x, funcalls, iterations, flag = r
+ if full_output:
+ results = RootResults(root=x,
+ iterations=iterations,
+ function_calls=funcalls,
+ flag=flag, method=method)
+ return x, results
+ return x
+
+
+def _wrap_nan_raise(f):
+
+ def f_raise(x, *args):
+ fx = f(x, *args)
+ f_raise._function_calls += 1
+ if np.isnan(fx):
+ msg = (f'The function value at x={x} is NaN; '
+ 'solver cannot continue.')
+ err = ValueError(msg)
+ err._x = x
+ err._function_calls = f_raise._function_calls
+ raise err
+ return fx
+
+ f_raise._function_calls = 0
+ return f_raise
+
+
+def newton(func, x0, fprime=None, args=(), tol=1.48e-8, maxiter=50,
+ fprime2=None, x1=None, rtol=0.0,
+ full_output=False, disp=True):
+ """
+ Find a root of a real or complex function using the Newton-Raphson
+ (or secant or Halley's) method.
+
+ Find a root of the scalar-valued function `func` given a nearby scalar
+ starting point `x0`.
+ The Newton-Raphson method is used if the derivative `fprime` of `func`
+ is provided, otherwise the secant method is used. If the second order
+ derivative `fprime2` of `func` is also provided, then Halley's method is
+ used.
+
+ If `x0` is a sequence with more than one item, `newton` returns an array:
+ the roots of the function from each (scalar) starting point in `x0`.
+ In this case, `func` must be vectorized to return a sequence or array of
+ the same shape as its first argument. If `fprime` (`fprime2`) is given,
+ then its return must also have the same shape: each element is the first
+ (second) derivative of `func` with respect to its only variable evaluated
+ at each element of its first argument.
+
+ `newton` is for finding roots of a scalar-valued functions of a single
+ variable. For problems involving several variables, see `root`.
+
+ Parameters
+ ----------
+ func : callable
+ The function whose root is wanted. It must be a function of a
+ single variable of the form ``f(x,a,b,c,...)``, where ``a,b,c,...``
+ are extra arguments that can be passed in the `args` parameter.
+ x0 : float, sequence, or ndarray
+ An initial estimate of the root that should be somewhere near the
+ actual root. If not scalar, then `func` must be vectorized and return
+ a sequence or array of the same shape as its first argument.
+ fprime : callable, optional
+ The derivative of the function when available and convenient. If it
+ is None (default), then the secant method is used.
+ args : tuple, optional
+ Extra arguments to be used in the function call.
+ tol : float, optional
+ The allowable error of the root's value. If `func` is complex-valued,
+ a larger `tol` is recommended as both the real and imaginary parts
+ of `x` contribute to ``|x - x0|``.
+ maxiter : int, optional
+ Maximum number of iterations.
+ fprime2 : callable, optional
+ The second order derivative of the function when available and
+ convenient. If it is None (default), then the normal Newton-Raphson
+ or the secant method is used. If it is not None, then Halley's method
+ is used.
+ x1 : float, optional
+ Another estimate of the root that should be somewhere near the
+ actual root. Used if `fprime` is not provided.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ full_output : bool, optional
+ If `full_output` is False (default), the root is returned.
+ If True and `x0` is scalar, the return value is ``(x, r)``, where ``x``
+ is the root and ``r`` is a `RootResults` object.
+ If True and `x0` is non-scalar, the return value is ``(x, converged,
+ zero_der)`` (see Returns section for details).
+ disp : bool, optional
+ If True, raise a RuntimeError if the algorithm didn't converge, with
+ the error message containing the number of iterations and current
+ function value. Otherwise, the convergence status is recorded in a
+ `RootResults` return object.
+ Ignored if `x0` is not scalar.
+ *Note: this has little to do with displaying, however,
+ the `disp` keyword cannot be renamed for backwards compatibility.*
+
+ Returns
+ -------
+ root : float, sequence, or ndarray
+ Estimated location where function is zero.
+ r : `RootResults`, optional
+ Present if ``full_output=True`` and `x0` is scalar.
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+ converged : ndarray of bool, optional
+ Present if ``full_output=True`` and `x0` is non-scalar.
+ For vector functions, indicates which elements converged successfully.
+ zero_der : ndarray of bool, optional
+ Present if ``full_output=True`` and `x0` is non-scalar.
+ For vector functions, indicates which elements had a zero derivative.
+
+ See Also
+ --------
+ root_scalar : interface to root solvers for scalar functions
+ root : interface to root solvers for multi-input, multi-output functions
+
+ Notes
+ -----
+ The convergence rate of the Newton-Raphson method is quadratic,
+ the Halley method is cubic, and the secant method is
+ sub-quadratic. This means that if the function is well-behaved
+ the actual error in the estimated root after the nth iteration
+ is approximately the square (cube for Halley) of the error
+ after the (n-1)th step. However, the stopping criterion used
+ here is the step size and there is no guarantee that a root
+ has been found. Consequently, the result should be verified.
+ Safer algorithms are brentq, brenth, ridder, and bisect,
+ but they all require that the root first be bracketed in an
+ interval where the function changes sign. The brentq algorithm
+ is recommended for general use in one dimensional problems
+ when such an interval has been found.
+
+ When `newton` is used with arrays, it is best suited for the following
+ types of problems:
+
+ * The initial guesses, `x0`, are all relatively the same distance from
+ the roots.
+ * Some or all of the extra arguments, `args`, are also arrays so that a
+ class of similar problems can be solved together.
+ * The size of the initial guesses, `x0`, is larger than O(100) elements.
+ Otherwise, a naive loop may perform as well or better than a vector.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy import optimize
+
+ >>> def f(x):
+ ... return (x**3 - 1) # only one real root at x = 1
+
+ ``fprime`` is not provided, use the secant method:
+
+ >>> root = optimize.newton(f, 1.5)
+ >>> root
+ 1.0000000000000016
+ >>> root = optimize.newton(f, 1.5, fprime2=lambda x: 6 * x)
+ >>> root
+ 1.0000000000000016
+
+ Only ``fprime`` is provided, use the Newton-Raphson method:
+
+ >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2)
+ >>> root
+ 1.0
+
+ Both ``fprime2`` and ``fprime`` are provided, use Halley's method:
+
+ >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2,
+ ... fprime2=lambda x: 6 * x)
+ >>> root
+ 1.0
+
+ When we want to find roots for a set of related starting values and/or
+ function parameters, we can provide both of those as an array of inputs:
+
+ >>> f = lambda x, a: x**3 - a
+ >>> fder = lambda x, a: 3 * x**2
+ >>> rng = np.random.default_rng()
+ >>> x = rng.standard_normal(100)
+ >>> a = np.arange(-50, 50)
+ >>> vec_res = optimize.newton(f, x, fprime=fder, args=(a, ), maxiter=200)
+
+ The above is the equivalent of solving for each value in ``(x, a)``
+ separately in a for-loop, just faster:
+
+ >>> loop_res = [optimize.newton(f, x0, fprime=fder, args=(a0,),
+ ... maxiter=200)
+ ... for x0, a0 in zip(x, a)]
+ >>> np.allclose(vec_res, loop_res)
+ True
+
+ Plot the results found for all values of ``a``:
+
+ >>> analytical_result = np.sign(a) * np.abs(a)**(1/3)
+ >>> fig, ax = plt.subplots()
+ >>> ax.plot(a, analytical_result, 'o')
+ >>> ax.plot(a, vec_res, '.')
+ >>> ax.set_xlabel('$a$')
+ >>> ax.set_ylabel('$x$ where $f(x, a)=0$')
+ >>> plt.show()
+
+ """
+ if tol <= 0:
+ raise ValueError(f"tol too small ({tol:g} <= 0)")
+ maxiter = operator.index(maxiter)
+ if maxiter < 1:
+ raise ValueError("maxiter must be greater than 0")
+ if np.size(x0) > 1:
+ return _array_newton(func, x0, fprime, args, tol, maxiter, fprime2,
+ full_output)
+
+ # Convert to float (don't use float(x0); this works also for complex x0)
+ # Use np.asarray because we want x0 to be a numpy object, not a Python
+ # object. e.g. np.complex(1+1j) > 0 is possible, but (1 + 1j) > 0 raises
+ # a TypeError
+ x0 = np.asarray(x0)[()] * 1.0
+ p0 = x0
+ funcalls = 0
+ if fprime is not None:
+ # Newton-Raphson method
+ method = "newton"
+ for itr in range(maxiter):
+ # first evaluate fval
+ fval = func(p0, *args)
+ funcalls += 1
+ # If fval is 0, a root has been found, then terminate
+ if fval == 0:
+ return _results_select(
+ full_output, (p0, funcalls, itr, _ECONVERGED), method)
+ fder = fprime(p0, *args)
+ funcalls += 1
+ if fder == 0:
+ msg = "Derivative was zero."
+ if disp:
+ msg += (
+ f" Failed to converge after {itr + 1} iterations,"
+ f" value is {p0}."
+ )
+ raise RuntimeError(msg)
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
+ return _results_select(
+ full_output, (p0, funcalls, itr + 1, _ECONVERR), method)
+ newton_step = fval / fder
+ if fprime2:
+ fder2 = fprime2(p0, *args)
+ funcalls += 1
+ method = "halley"
+ # Halley's method:
+ # newton_step /= (1.0 - 0.5 * newton_step * fder2 / fder)
+ # Only do it if denominator stays close enough to 1
+ # Rationale: If 1-adj < 0, then Halley sends x in the
+ # opposite direction to Newton. Doesn't happen if x is close
+ # enough to root.
+ adj = newton_step * fder2 / fder / 2
+ if np.abs(adj) < 1:
+ newton_step /= 1.0 - adj
+ p = p0 - newton_step
+ if np.isclose(p, p0, rtol=rtol, atol=tol):
+ return _results_select(
+ full_output, (p, funcalls, itr + 1, _ECONVERGED), method)
+ p0 = p
+ else:
+ # Secant method
+ method = "secant"
+ if x1 is not None:
+ if x1 == x0:
+ raise ValueError("x1 and x0 must be different")
+ p1 = x1
+ else:
+ eps = 1e-4
+ p1 = x0 * (1 + eps)
+ p1 += (eps if p1 >= 0 else -eps)
+ q0 = func(p0, *args)
+ funcalls += 1
+ q1 = func(p1, *args)
+ funcalls += 1
+ if abs(q1) < abs(q0):
+ p0, p1, q0, q1 = p1, p0, q1, q0
+ for itr in range(maxiter):
+ if q1 == q0:
+ if p1 != p0:
+ msg = f"Tolerance of {p1 - p0} reached."
+ if disp:
+ msg += (
+ f" Failed to converge after {itr + 1} iterations,"
+ f" value is {p1}."
+ )
+ raise RuntimeError(msg)
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
+ p = (p1 + p0) / 2.0
+ return _results_select(
+ full_output, (p, funcalls, itr + 1, _ECONVERR), method)
+ else:
+ if abs(q1) > abs(q0):
+ p = (-q0 / q1 * p1 + p0) / (1 - q0 / q1)
+ else:
+ p = (-q1 / q0 * p0 + p1) / (1 - q1 / q0)
+ if np.isclose(p, p1, rtol=rtol, atol=tol):
+ return _results_select(
+ full_output, (p, funcalls, itr + 1, _ECONVERGED), method)
+ p0, q0 = p1, q1
+ p1 = p
+ q1 = func(p1, *args)
+ funcalls += 1
+
+ if disp:
+ msg = f"Failed to converge after {itr + 1} iterations, value is {p}."
+ raise RuntimeError(msg)
+
+ return _results_select(full_output, (p, funcalls, itr + 1, _ECONVERR), method)
+
+
+def _array_newton(func, x0, fprime, args, tol, maxiter, fprime2, full_output):
+ """
+ A vectorized version of Newton, Halley, and secant methods for arrays.
+
+ Do not use this method directly. This method is called from `newton`
+ when ``np.size(x0) > 1`` is ``True``. For docstring, see `newton`.
+ """
+ # Explicitly copy `x0` as `p` will be modified inplace, but the
+ # user's array should not be altered.
+ p = np.array(x0, copy=True)
+
+ failures = np.ones_like(p, dtype=bool)
+ nz_der = np.ones_like(failures)
+ if fprime is not None:
+ # Newton-Raphson method
+ for iteration in range(maxiter):
+ # first evaluate fval
+ fval = np.asarray(func(p, *args))
+ # If all fval are 0, all roots have been found, then terminate
+ if not fval.any():
+ failures = fval.astype(bool)
+ break
+ fder = np.asarray(fprime(p, *args))
+ nz_der = (fder != 0)
+ # stop iterating if all derivatives are zero
+ if not nz_der.any():
+ break
+ # Newton step
+ dp = fval[nz_der] / fder[nz_der]
+ if fprime2 is not None:
+ fder2 = np.asarray(fprime2(p, *args))
+ dp = dp / (1.0 - 0.5 * dp * fder2[nz_der] / fder[nz_der])
+ # only update nonzero derivatives
+ p = np.asarray(p, dtype=np.result_type(p, dp, np.float64))
+ p[nz_der] -= dp
+ failures[nz_der] = np.abs(dp) >= tol # items not yet converged
+ # stop iterating if there aren't any failures, not incl zero der
+ if not failures[nz_der].any():
+ break
+ else:
+ # Secant method
+ dx = np.finfo(float).eps**0.33
+ p1 = p * (1 + dx) + np.where(p >= 0, dx, -dx)
+ q0 = np.asarray(func(p, *args))
+ q1 = np.asarray(func(p1, *args))
+ active = np.ones_like(p, dtype=bool)
+ for iteration in range(maxiter):
+ nz_der = (q1 != q0)
+ # stop iterating if all derivatives are zero
+ if not nz_der.any():
+ p = (p1 + p) / 2.0
+ break
+ # Secant Step
+ dp = (q1 * (p1 - p))[nz_der] / (q1 - q0)[nz_der]
+ # only update nonzero derivatives
+ p = np.asarray(p, dtype=np.result_type(p, p1, dp, np.float64))
+ p[nz_der] = p1[nz_der] - dp
+ active_zero_der = ~nz_der & active
+ p[active_zero_der] = (p1 + p)[active_zero_der] / 2.0
+ active &= nz_der # don't assign zero derivatives again
+ failures[nz_der] = np.abs(dp) >= tol # not yet converged
+ # stop iterating if there aren't any failures, not incl zero der
+ if not failures[nz_der].any():
+ break
+ p1, p = p, p1
+ q0 = q1
+ q1 = np.asarray(func(p1, *args))
+
+ zero_der = ~nz_der & failures # don't include converged with zero-ders
+ if zero_der.any():
+ # Secant warnings
+ if fprime is None:
+ nonzero_dp = (p1 != p)
+ # non-zero dp, but infinite newton step
+ zero_der_nz_dp = (zero_der & nonzero_dp)
+ if zero_der_nz_dp.any():
+ rms = np.sqrt(
+ sum((p1[zero_der_nz_dp] - p[zero_der_nz_dp]) ** 2)
+ )
+ warnings.warn(f'RMS of {rms:g} reached', RuntimeWarning, stacklevel=3)
+ # Newton or Halley warnings
+ else:
+ all_or_some = 'all' if zero_der.all() else 'some'
+ msg = f'{all_or_some:s} derivatives were zero'
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ elif failures.any():
+ all_or_some = 'all' if failures.all() else 'some'
+ msg = f'{all_or_some:s} failed to converge after {maxiter:d} iterations'
+ if failures.all():
+ raise RuntimeError(msg)
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+
+ if full_output:
+ result = namedtuple('result', ('root', 'converged', 'zero_der'))
+ p = result(p, ~failures, zero_der)
+
+ return p
+
+
+def bisect(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find root of a function within an interval using bisection.
+
+ Basic bisection routine to find a root of the function `f` between the
+ arguments `a` and `b`. ``f(a)`` and ``f(b)`` cannot have the same signs.
+ Slow but sure.
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. `f` must be continuous, and
+ ``f(a)`` and ``f(b)`` must have opposite signs.
+ a : scalar
+ One end of the bracketing interval ``[a,b]``.
+ b : scalar
+ The other end of the bracketing interval ``[a,b]``.
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive.
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where x is the root, and r is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in a `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ brentq, brenth, bisect, newton
+ fixed_point : scalar fixed-point finder
+ fsolve : n-dimensional root-finding
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `bisect` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ Examples
+ --------
+
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.bisect(f, 0, 2)
+ >>> root
+ 1.0
+
+ >>> root = optimize.bisect(f, -2, 0)
+ >>> root
+ -1.0
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._bisect(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "bisect")
+
+
+def ridder(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find a root of a function in an interval using Ridder's method.
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. f must be continuous, and f(a) and
+ f(b) must have opposite signs.
+ a : scalar
+ One end of the bracketing interval [a,b].
+ b : scalar
+ The other end of the bracketing interval [a,b].
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive.
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in any `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence.
+ In particular, ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ brentq, brenth, bisect, newton : 1-D root-finding
+ fixed_point : scalar fixed-point finder
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ Uses [Ridders1979]_ method to find a root of the function `f` between the
+ arguments `a` and `b`. Ridders' method is faster than bisection, but not
+ generally as fast as the Brent routines. [Ridders1979]_ provides the
+ classic description and source of the algorithm. A description can also be
+ found in any recent edition of Numerical Recipes.
+
+ The routine used here diverges slightly from standard presentations in
+ order to be a bit more careful of tolerance.
+
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `ridder` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [Ridders1979]
+ Ridders, C. F. J. "A New Algorithm for Computing a
+ Single Root of a Real Continuous Function."
+ IEEE Trans. Circuits Systems 26, 979-980, 1979.
+
+ Examples
+ --------
+
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.ridder(f, 0, 2)
+ >>> root
+ 1.0
+
+ >>> root = optimize.ridder(f, -2, 0)
+ >>> root
+ -1.0
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._ridder(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "ridder")
+
+
+def brentq(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find a root of a function in a bracketing interval using Brent's method.
+
+ Uses the classic Brent's method to find a root of the function `f` on
+ the sign changing interval [a , b]. Generally considered the best of the
+ rootfinding routines here. It is a safe version of the secant method that
+ uses inverse quadratic extrapolation. Brent's method combines root
+ bracketing, interval bisection, and inverse quadratic interpolation. It is
+ sometimes known as the van Wijngaarden-Dekker-Brent method. Brent (1973)
+ claims convergence is guaranteed for functions computable within [a,b].
+
+ [Brent1973]_ provides the classic description of the algorithm. Another
+ description can be found in a recent edition of Numerical Recipes, including
+ [PressEtal1992]_. A third description is at
+ http://mathworld.wolfram.com/BrentsMethod.html. It should be easy to
+ understand the algorithm just by reading our code. Our code diverges a bit
+ from standard presentations: we choose a different formula for the
+ extrapolation step.
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. The function :math:`f`
+ must be continuous, and :math:`f(a)` and :math:`f(b)` must
+ have opposite signs.
+ a : scalar
+ One end of the bracketing interval :math:`[a, b]`.
+ b : scalar
+ The other end of the bracketing interval :math:`[a, b]`.
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive. For nice functions, Brent's
+ method will often satisfy the above condition with ``xtol/2``
+ and ``rtol/2``. [Brent1973]_
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``. For nice functions, Brent's
+ method will often satisfy the above condition with ``xtol/2``
+ and ``rtol/2``. [Brent1973]_
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in any `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers
+ leastsq : nonlinear least squares minimizer
+ fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers
+ basinhopping, differential_evolution, brute : global optimizers
+ fminbound, brent, golden, bracket : local scalar minimizers
+ fsolve : N-D root-finding
+ brenth, ridder, bisect, newton : 1-D root-finding
+ fixed_point : scalar fixed-point finder
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ `f` must be continuous. f(a) and f(b) must have opposite signs.
+
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `brentq` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [Brent1973]
+ Brent, R. P.,
+ *Algorithms for Minimization Without Derivatives*.
+ Englewood Cliffs, NJ: Prentice-Hall, 1973. Ch. 3-4.
+
+ .. [PressEtal1992]
+ Press, W. H.; Flannery, B. P.; Teukolsky, S. A.; and Vetterling, W. T.
+ *Numerical Recipes in FORTRAN: The Art of Scientific Computing*, 2nd ed.
+ Cambridge, England: Cambridge University Press, pp. 352-355, 1992.
+ Section 9.3: "Van Wijngaarden-Dekker-Brent Method."
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.brentq(f, -2, 0)
+ >>> root
+ -1.0
+
+ >>> root = optimize.brentq(f, 0, 2)
+ >>> root
+ 1.0
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._brentq(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "brentq")
+
+
+def brenth(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """Find a root of a function in a bracketing interval using Brent's
+ method with hyperbolic extrapolation.
+
+ A variation on the classic Brent routine to find a root of the function f
+ between the arguments a and b that uses hyperbolic extrapolation instead of
+ inverse quadratic extrapolation. Bus & Dekker (1975) guarantee convergence
+ for this method, claiming that the upper bound of function evaluations here
+ is 4 or 5 times that of bisection.
+ f(a) and f(b) cannot have the same signs. Generally, on a par with the
+ brent routine, but not as heavily tested. It is a safe version of the
+ secant method that uses hyperbolic extrapolation.
+ The version here is by Chuck Harris, and implements Algorithm M of
+ [BusAndDekker1975]_, where further details (convergence properties,
+ additional remarks and such) can be found
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. f must be continuous, and f(a) and
+ f(b) must have opposite signs.
+ a : scalar
+ One end of the bracketing interval [a,b].
+ b : scalar
+ The other end of the bracketing interval [a,b].
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive. As with `brentq`, for nice
+ functions the method will often satisfy the above condition
+ with ``xtol/2`` and ``rtol/2``.
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``. As with `brentq`, for nice functions
+ the method will often satisfy the above condition with
+ ``xtol/2`` and ``rtol/2``.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in any `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers
+ leastsq : nonlinear least squares minimizer
+ fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers
+ basinhopping, differential_evolution, brute : global optimizers
+ fminbound, brent, golden, bracket : local scalar minimizers
+ fsolve : N-D root-finding
+ brentq, ridder, bisect, newton : 1-D root-finding
+ fixed_point : scalar fixed-point finder
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `brenth` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [BusAndDekker1975]
+ Bus, J. C. P., Dekker, T. J.,
+ "Two Efficient Algorithms with Guaranteed Convergence for Finding a Zero
+ of a Function", ACM Transactions on Mathematical Software, Vol. 1, Issue
+ 4, Dec. 1975, pp. 330-345. Section 3: "Algorithm M".
+ :doi:`10.1145/355656.355659`
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.brenth(f, -2, 0)
+ >>> root
+ -1.0
+
+ >>> root = optimize.brenth(f, 0, 2)
+ >>> root
+ 1.0
+
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._brenth(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "brenth")
+
+
+################################
+# TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions", by
+# Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
+# See [1]
+
+
+def _notclose(fs, rtol=_rtol, atol=_xtol):
+ # Ensure not None, not 0, all finite, and not very close to each other
+ notclosefvals = (
+ all(fs) and all(np.isfinite(fs)) and
+ not any(any(np.isclose(_f, fs[i + 1:], rtol=rtol, atol=atol))
+ for i, _f in enumerate(fs[:-1])))
+ return notclosefvals
+
+
+def _secant(xvals, fvals):
+ """Perform a secant step, taking a little care"""
+ # Secant has many "mathematically" equivalent formulations
+ # x2 = x0 - (x1 - x0)/(f1 - f0) * f0
+ # = x1 - (x1 - x0)/(f1 - f0) * f1
+ # = (-x1 * f0 + x0 * f1) / (f1 - f0)
+ # = (-f0 / f1 * x1 + x0) / (1 - f0 / f1)
+ # = (-f1 / f0 * x0 + x1) / (1 - f1 / f0)
+ x0, x1 = xvals[:2]
+ f0, f1 = fvals[:2]
+ if f0 == f1:
+ return np.nan
+ if np.abs(f1) > np.abs(f0):
+ x2 = (-f0 / f1 * x1 + x0) / (1 - f0 / f1)
+ else:
+ x2 = (-f1 / f0 * x0 + x1) / (1 - f1 / f0)
+ return x2
+
+
+def _update_bracket(ab, fab, c, fc):
+ """Update a bracket given (c, fc), return the discarded endpoints."""
+ fa, fb = fab
+ idx = (0 if np.sign(fa) * np.sign(fc) > 0 else 1)
+ rx, rfx = ab[idx], fab[idx]
+ fab[idx] = fc
+ ab[idx] = c
+ return rx, rfx
+
+
+def _compute_divided_differences(xvals, fvals, N=None, full=True,
+ forward=True):
+ """Return a matrix of divided differences for the xvals, fvals pairs
+
+ DD[i, j] = f[x_{i-j}, ..., x_i] for 0 <= j <= i
+
+ If full is False, just return the main diagonal(or last row):
+ f[a], f[a, b] and f[a, b, c].
+ If forward is False, return f[c], f[b, c], f[a, b, c]."""
+ if full:
+ if forward:
+ xvals = np.asarray(xvals)
+ else:
+ xvals = np.array(xvals)[::-1]
+ M = len(xvals)
+ N = M if N is None else min(N, M)
+ DD = np.zeros([M, N])
+ DD[:, 0] = fvals[:]
+ for i in range(1, N):
+ DD[i:, i] = (np.diff(DD[i - 1:, i - 1]) /
+ (xvals[i:] - xvals[:M - i]))
+ return DD
+
+ xvals = np.asarray(xvals)
+ dd = np.array(fvals)
+ row = np.array(fvals)
+ idx2Use = (0 if forward else -1)
+ dd[0] = fvals[idx2Use]
+ for i in range(1, len(xvals)):
+ denom = xvals[i:i + len(row) - 1] - xvals[:len(row) - 1]
+ row = np.diff(row)[:] / denom
+ dd[i] = row[idx2Use]
+ return dd
+
+
+def _interpolated_poly(xvals, fvals, x):
+ """Compute p(x) for the polynomial passing through the specified locations.
+
+ Use Neville's algorithm to compute p(x) where p is the minimal degree
+ polynomial passing through the points xvals, fvals"""
+ xvals = np.asarray(xvals)
+ N = len(xvals)
+ Q = np.zeros([N, N])
+ D = np.zeros([N, N])
+ Q[:, 0] = fvals[:]
+ D[:, 0] = fvals[:]
+ for k in range(1, N):
+ alpha = D[k:, k - 1] - Q[k - 1:N - 1, k - 1]
+ diffik = xvals[0:N - k] - xvals[k:N]
+ Q[k:, k] = (xvals[k:] - x) / diffik * alpha
+ D[k:, k] = (xvals[:N - k] - x) / diffik * alpha
+ # Expect Q[-1, 1:] to be small relative to Q[-1, 0] as x approaches a root
+ return np.sum(Q[-1, 1:]) + Q[-1, 0]
+
+
+def _inverse_poly_zero(a, b, c, d, fa, fb, fc, fd):
+ """Inverse cubic interpolation f-values -> x-values
+
+ Given four points (fa, a), (fb, b), (fc, c), (fd, d) with
+ fa, fb, fc, fd all distinct, find poly IP(y) through the 4 points
+ and compute x=IP(0).
+ """
+ return _interpolated_poly([fa, fb, fc, fd], [a, b, c, d], 0)
+
+
+def _newton_quadratic(ab, fab, d, fd, k):
+ """Apply Newton-Raphson like steps, using divided differences to approximate f'
+
+ ab is a real interval [a, b] containing a root,
+ fab holds the real values of f(a), f(b)
+ d is a real number outside [ab, b]
+ k is the number of steps to apply
+ """
+ a, b = ab
+ fa, fb = fab
+ _, B, A = _compute_divided_differences([a, b, d], [fa, fb, fd],
+ forward=True, full=False)
+
+ # _P is the quadratic polynomial through the 3 points
+ def _P(x):
+ # Horner evaluation of fa + B * (x - a) + A * (x - a) * (x - b)
+ return (A * (x - b) + B) * (x - a) + fa
+
+ if A == 0:
+ r = a - fa / B
+ else:
+ r = (a if np.sign(A) * np.sign(fa) > 0 else b)
+ # Apply k Newton-Raphson steps to _P(x), starting from x=r
+ for i in range(k):
+ r1 = r - _P(r) / (B + A * (2 * r - a - b))
+ if not (ab[0] < r1 < ab[1]):
+ if (ab[0] < r < ab[1]):
+ return r
+ r = sum(ab) / 2.0
+ break
+ r = r1
+
+ return r
+
+
+class TOMS748Solver:
+ """Solve f(x, *args) == 0 using Algorithm748 of Alefeld, Potro & Shi.
+ """
+ _MU = 0.5
+ _K_MIN = 1
+ _K_MAX = 100 # A very high value for real usage. Expect 1, 2, maybe 3.
+
+ def __init__(self):
+ self.f = None
+ self.args = None
+ self.function_calls = 0
+ self.iterations = 0
+ self.k = 2
+ # ab=[a,b] is a global interval containing a root
+ self.ab = [np.nan, np.nan]
+ # fab is function values at a, b
+ self.fab = [np.nan, np.nan]
+ self.d = None
+ self.fd = None
+ self.e = None
+ self.fe = None
+ self.disp = False
+ self.xtol = _xtol
+ self.rtol = _rtol
+ self.maxiter = _iter
+
+ def configure(self, xtol, rtol, maxiter, disp, k):
+ self.disp = disp
+ self.xtol = xtol
+ self.rtol = rtol
+ self.maxiter = maxiter
+ # Silently replace a low value of k with 1
+ self.k = max(k, self._K_MIN)
+ # Noisily replace a high value of k with self._K_MAX
+ if self.k > self._K_MAX:
+ msg = f"toms748: Overriding k: ->{self._K_MAX}"
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ self.k = self._K_MAX
+
+ def _callf(self, x, error=True):
+ """Call the user-supplied function, update book-keeping"""
+ fx = self.f(x, *self.args)
+ self.function_calls += 1
+ if not np.isfinite(fx) and error:
+ raise ValueError(f"Invalid function value: f({x:f}) -> {fx} ")
+ return fx
+
+ def get_result(self, x, flag=_ECONVERGED):
+ r"""Package the result and statistics into a tuple."""
+ return (x, self.function_calls, self.iterations, flag)
+
+ def _update_bracket(self, c, fc):
+ return _update_bracket(self.ab, self.fab, c, fc)
+
+ def start(self, f, a, b, args=()):
+ r"""Prepare for the iterations."""
+ self.function_calls = 0
+ self.iterations = 0
+
+ self.f = f
+ self.args = args
+ self.ab[:] = [a, b]
+ if not np.isfinite(a) or np.imag(a) != 0:
+ raise ValueError(f"Invalid x value: {a} ")
+ if not np.isfinite(b) or np.imag(b) != 0:
+ raise ValueError(f"Invalid x value: {b} ")
+
+ fa = self._callf(a)
+ if not np.isfinite(fa) or np.imag(fa) != 0:
+ raise ValueError(f"Invalid function value: f({a:f}) -> {fa} ")
+ if fa == 0:
+ return _ECONVERGED, a
+ fb = self._callf(b)
+ if not np.isfinite(fb) or np.imag(fb) != 0:
+ raise ValueError(f"Invalid function value: f({b:f}) -> {fb} ")
+ if fb == 0:
+ return _ECONVERGED, b
+
+ if np.sign(fb) * np.sign(fa) > 0:
+ raise ValueError("f(a) and f(b) must have different signs, but "
+ f"f({a:e})={fa:e}, f({b:e})={fb:e} ")
+ self.fab[:] = [fa, fb]
+
+ return _EINPROGRESS, sum(self.ab) / 2.0
+
+ def get_status(self):
+ """Determine the current status."""
+ a, b = self.ab[:2]
+ if np.isclose(a, b, rtol=self.rtol, atol=self.xtol):
+ return _ECONVERGED, sum(self.ab) / 2.0
+ if self.iterations >= self.maxiter:
+ return _ECONVERR, sum(self.ab) / 2.0
+ return _EINPROGRESS, sum(self.ab) / 2.0
+
+ def iterate(self):
+ """Perform one step in the algorithm.
+
+ Implements Algorithm 4.1(k=1) or 4.2(k=2) in [APS1995]
+ """
+ self.iterations += 1
+ eps = np.finfo(float).eps
+ d, fd, e, fe = self.d, self.fd, self.e, self.fe
+ ab_width = self.ab[1] - self.ab[0] # Need the start width below
+ c = None
+
+ for nsteps in range(2, self.k+2):
+ # If the f-values are sufficiently separated, perform an inverse
+ # polynomial interpolation step. Otherwise, nsteps repeats of
+ # an approximate Newton-Raphson step.
+ if _notclose(self.fab + [fd, fe], rtol=0, atol=32*eps):
+ c0 = _inverse_poly_zero(self.ab[0], self.ab[1], d, e,
+ self.fab[0], self.fab[1], fd, fe)
+ if self.ab[0] < c0 < self.ab[1]:
+ c = c0
+ if c is None:
+ c = _newton_quadratic(self.ab, self.fab, d, fd, nsteps)
+
+ fc = self._callf(c)
+ if fc == 0:
+ return _ECONVERGED, c
+
+ # re-bracket
+ e, fe = d, fd
+ d, fd = self._update_bracket(c, fc)
+
+ # u is the endpoint with the smallest f-value
+ uix = (0 if np.abs(self.fab[0]) < np.abs(self.fab[1]) else 1)
+ u, fu = self.ab[uix], self.fab[uix]
+
+ _, A = _compute_divided_differences(self.ab, self.fab,
+ forward=(uix == 0), full=False)
+ c = u - 2 * fu / A
+ if np.abs(c - u) > 0.5 * (self.ab[1] - self.ab[0]):
+ c = sum(self.ab) / 2.0
+ else:
+ if np.isclose(c, u, rtol=eps, atol=0):
+ # c didn't change (much).
+ # Either because the f-values at the endpoints have vastly
+ # differing magnitudes, or because the root is very close to
+ # that endpoint
+ frs = np.frexp(self.fab)[1]
+ if frs[uix] < frs[1 - uix] - 50: # Differ by more than 2**50
+ c = (31 * self.ab[uix] + self.ab[1 - uix]) / 32
+ else:
+ # Make a bigger adjustment, about the
+ # size of the requested tolerance.
+ mm = (1 if uix == 0 else -1)
+ adj = mm * np.abs(c) * self.rtol + mm * self.xtol
+ c = u + adj
+ if not self.ab[0] < c < self.ab[1]:
+ c = sum(self.ab) / 2.0
+
+ fc = self._callf(c)
+ if fc == 0:
+ return _ECONVERGED, c
+
+ e, fe = d, fd
+ d, fd = self._update_bracket(c, fc)
+
+ # If the width of the new interval did not decrease enough, bisect
+ if self.ab[1] - self.ab[0] > self._MU * ab_width:
+ e, fe = d, fd
+ z = sum(self.ab) / 2.0
+ fz = self._callf(z)
+ if fz == 0:
+ return _ECONVERGED, z
+ d, fd = self._update_bracket(z, fz)
+
+ # Record d and e for next iteration
+ self.d, self.fd = d, fd
+ self.e, self.fe = e, fe
+
+ status, xn = self.get_status()
+ return status, xn
+
+ def solve(self, f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, k=2, maxiter=_iter, disp=True):
+ r"""Solve f(x) = 0 given an interval containing a root."""
+ self.configure(xtol=xtol, rtol=rtol, maxiter=maxiter, disp=disp, k=k)
+ status, xn = self.start(f, a, b, args)
+ if status == _ECONVERGED:
+ return self.get_result(xn)
+
+ # The first step only has two x-values.
+ c = _secant(self.ab, self.fab)
+ if not self.ab[0] < c < self.ab[1]:
+ c = sum(self.ab) / 2.0
+ fc = self._callf(c)
+ if fc == 0:
+ return self.get_result(c)
+
+ self.d, self.fd = self._update_bracket(c, fc)
+ self.e, self.fe = None, None
+ self.iterations += 1
+
+ while True:
+ status, xn = self.iterate()
+ if status == _ECONVERGED:
+ return self.get_result(xn)
+ if status == _ECONVERR:
+ fmt = "Failed to converge after %d iterations, bracket is %s"
+ if disp:
+ msg = fmt % (self.iterations + 1, self.ab)
+ raise RuntimeError(msg)
+ return self.get_result(xn, _ECONVERR)
+
+
+def toms748(f, a, b, args=(), k=1,
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find a root using TOMS Algorithm 748 method.
+
+ Implements the Algorithm 748 method of Alefeld, Potro and Shi to find a
+ root of the function `f` on the interval ``[a , b]``, where `f(a)` and
+ `f(b)` must have opposite signs.
+
+ It uses a mixture of inverse cubic interpolation and
+ "Newton-quadratic" steps. [APS1995].
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a scalar. The function :math:`f`
+ must be continuous, and :math:`f(a)` and :math:`f(b)`
+ have opposite signs.
+ a : scalar,
+ lower boundary of the search interval
+ b : scalar,
+ upper boundary of the search interval
+ args : tuple, optional
+ containing extra arguments for the function `f`.
+ `f` is called by ``f(x, *args)``.
+ k : int, optional
+ The number of Newton quadratic steps to perform each
+ iteration. ``k>=1``.
+ xtol : scalar, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive.
+ rtol : scalar, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in the `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Approximate root of `f`
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ brentq, brenth, ridder, bisect, newton
+ fsolve : find roots in N dimensions.
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ `f` must be continuous.
+ Algorithm 748 with ``k=2`` is asymptotically the most efficient
+ algorithm known for finding roots of a four times continuously
+ differentiable function.
+ In contrast with Brent's algorithm, which may only decrease the length of
+ the enclosing bracket on the last step, Algorithm 748 decreases it each
+ iteration with the same asymptotic efficiency as it finds the root.
+
+ For easy statement of efficiency indices, assume that `f` has 4
+ continuous deriviatives.
+ For ``k=1``, the convergence order is at least 2.7, and with about
+ asymptotically 2 function evaluations per iteration, the efficiency
+ index is approximately 1.65.
+ For ``k=2``, the order is about 4.6 with asymptotically 3 function
+ evaluations per iteration, and the efficiency index 1.66.
+ For higher values of `k`, the efficiency index approaches
+ the kth root of ``(3k-2)``, hence ``k=1`` or ``k=2`` are
+ usually appropriate.
+
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `toms748` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [APS1995]
+ Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
+ *Algorithm 748: Enclosing Zeros of Continuous Functions*,
+ ACM Trans. Math. Softw. Volume 221(1995)
+ https://doi.org/10.1145/210089.210111
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return (x**3 - 1) # only one real root at x = 1
+
+ >>> from scipy import optimize
+ >>> root, results = optimize.toms748(f, 0, 2, full_output=True)
+ >>> root
+ 1.0
+ >>> results
+ converged: True
+ flag: converged
+ function_calls: 11
+ iterations: 5
+ root: 1.0
+ method: toms748
+ """
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol / 4:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol/4:g})")
+ maxiter = operator.index(maxiter)
+ if maxiter < 1:
+ raise ValueError("maxiter must be greater than 0")
+ if not np.isfinite(a):
+ raise ValueError(f"a is not finite {a}")
+ if not np.isfinite(b):
+ raise ValueError(f"b is not finite {b}")
+ if a >= b:
+ raise ValueError(f"a and b are not an interval [{a}, {b}]")
+ if not k >= 1:
+ raise ValueError(f"k too small ({k} < 1)")
+
+ if not isinstance(args, tuple):
+ args = (args,)
+ f = _wrap_nan_raise(f)
+ solver = TOMS748Solver()
+ result = solver.solve(f, a, b, args=args, k=k, xtol=xtol, rtol=rtol,
+ maxiter=maxiter, disp=disp)
+ x, function_calls, iterations, flag = result
+ return _results_select(full_output, (x, function_calls, iterations, flag),
+ "toms748")
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/cobyla.py b/.venv/lib/python3.12/site-packages/scipy/optimize/cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..87d111d8fc1634e54d3766a3f1c58abd37ac58cb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/cobyla.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'fmin_cobyla',
+]
+
+def __dir__():
+ return __all__
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="cobyla",
+ private_modules=["_cobyla_py"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize.pxd b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..d35f8da68b34d3a587f3a99326770d8550a2135c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize.pxd
@@ -0,0 +1,11 @@
+# Public Cython API declarations
+#
+# See doc/source/dev/contributor/public_cython_api.rst for guidelines
+
+
+# The following cimport statement provides legacy ABI
+# support. Changing it causes an ABI forward-compatibility break
+# (gh-11793), so we currently leave it as is (no further cimport
+# statements should be used in this file).
+from scipy.optimize.cython_optimize._zeros cimport (
+ brentq, brenth, ridder, bisect, zeros_full_output)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a07250bbeb06542721480c42005307992558fced
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/__init__.py
@@ -0,0 +1,133 @@
+"""
+Cython optimize root finding API
+================================
+The underlying C functions for the following root finders can be accessed
+directly using Cython:
+
+- `~scipy.optimize.bisect`
+- `~scipy.optimize.ridder`
+- `~scipy.optimize.brenth`
+- `~scipy.optimize.brentq`
+
+The Cython API for the root finding functions is similar except there is no
+``disp`` argument. Import the root finding functions using ``cimport`` from
+`scipy.optimize.cython_optimize`. ::
+
+ from scipy.optimize.cython_optimize cimport bisect, ridder, brentq, brenth
+
+
+Callback signature
+------------------
+The zeros functions in `~scipy.optimize.cython_optimize` expect a callback that
+takes a double for the scalar independent variable as the 1st argument and a
+user defined ``struct`` with any extra parameters as the 2nd argument. ::
+
+ double (*callback_type)(double, void*) noexcept
+
+
+Examples
+--------
+Usage of `~scipy.optimize.cython_optimize` requires Cython to write callbacks
+that are compiled into C. For more information on compiling Cython, see the
+`Cython Documentation `_.
+
+These are the basic steps:
+
+1. Create a Cython ``.pyx`` file, for example: ``myexample.pyx``.
+2. Import the desired root finder from `~scipy.optimize.cython_optimize`.
+3. Write the callback function, and call the selected root finding function
+ passing the callback, any extra arguments, and the other solver
+ parameters. ::
+
+ from scipy.optimize.cython_optimize cimport brentq
+
+ # import math from Cython
+ from libc cimport math
+
+ myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments
+ XLO, XHI = 0.5, 1.0 # lower and upper search boundaries
+ XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters
+
+ # user-defined struct for extra parameters
+ ctypedef struct test_params:
+ double C0
+ double C1
+
+
+ # user-defined callback
+ cdef double f(double x, void *args) noexcept:
+ cdef test_params *myargs = args
+ return myargs.C0 - math.exp(-(x - myargs.C1))
+
+
+ # Cython wrapper function
+ cdef double brentq_wrapper_example(dict args, double xa, double xb,
+ double xtol, double rtol, int mitr):
+ # Cython automatically casts dictionary to struct
+ cdef test_params myargs = args
+ return brentq(
+ f, xa, xb, &myargs, xtol, rtol, mitr, NULL)
+
+
+ # Python function
+ def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL,
+ mitr=MITR):
+ '''Calls Cython wrapper from Python.'''
+ return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr)
+
+4. If you want to call your function from Python, create a Cython wrapper, and
+ a Python function that calls the wrapper, or use ``cpdef``. Then, in Python,
+ you can import and run the example. ::
+
+ from myexample import brentq_example
+
+ x = brentq_example()
+ # 0.6999942848231314
+
+5. Create a Cython ``.pxd`` file if you need to export any Cython functions.
+
+
+Full output
+-----------
+The functions in `~scipy.optimize.cython_optimize` can also copy the full
+output from the solver to a C ``struct`` that is passed as its last argument.
+If you don't want the full output, just pass ``NULL``. The full output
+``struct`` must be type ``zeros_full_output``, which is defined in
+`scipy.optimize.cython_optimize` with the following fields:
+
+- ``int funcalls``: number of function calls
+- ``int iterations``: number of iterations
+- ``int error_num``: error number
+- ``double root``: root of function
+
+The root is copied by `~scipy.optimize.cython_optimize` to the full output
+``struct``. An error number of -1 means a sign error, -2 means a convergence
+error, and 0 means the solver converged. Continuing from the previous example::
+
+ from scipy.optimize.cython_optimize cimport zeros_full_output
+
+
+ # cython brentq solver with full output
+ cdef zeros_full_output brentq_full_output_wrapper_example(
+ dict args, double xa, double xb, double xtol, double rtol,
+ int mitr):
+ cdef test_params myargs = args
+ cdef zeros_full_output my_full_output
+ # use my_full_output instead of NULL
+ brentq(f, xa, xb, &myargs, xtol, rtol, mitr, &my_full_output)
+ return my_full_output
+
+
+ # Python function
+ def brent_full_output_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL,
+ rtol=RTOL, mitr=MITR):
+ '''Returns full output'''
+ return brentq_full_output_wrapper_example(args, xa, xb, xtol, rtol,
+ mitr)
+
+ result = brent_full_output_example()
+ # {'error_num': 0,
+ # 'funcalls': 6,
+ # 'iterations': 5,
+ # 'root': 0.6999942848231314}
+"""
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..297678453d69409f5f2b34886b7cc447fb29d7db
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4ab22cac4f6a5949aac458202d6180c6777fb5ba4f8fb09ae2ed19005b45f6f8
+size 109864
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.pxd b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..d3c9e98f0a24d80d15d1f7052f690d608f66dd80
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.pxd
@@ -0,0 +1,33 @@
+# Legacy public Cython API declarations
+#
+# NOTE: due to the way Cython ABI compatibility works, **no changes
+# should be made to this file** --- any API additions/changes should be
+# done in `cython_optimize.pxd` (see gh-11793).
+
+ctypedef double (*callback_type)(double, void*) noexcept
+
+ctypedef struct zeros_parameters:
+ callback_type function
+ void* args
+
+ctypedef struct zeros_full_output:
+ int funcalls
+ int iterations
+ int error_num
+ double root
+
+cdef double bisect(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
+
+cdef double ridder(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
+
+cdef double brenth(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
+
+cdef double brentq(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..0d83c80eb886846ddbbd6927e37e05812911f856
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd
@@ -0,0 +1,26 @@
+cdef extern from "../Zeros/zeros.h":
+ ctypedef double (*callback_type)(double, void*) noexcept
+ ctypedef struct scipy_zeros_info:
+ int funcalls
+ int iterations
+ int error_num
+
+cdef extern from "../Zeros/bisect.c" nogil:
+ double bisect(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
+
+cdef extern from "../Zeros/ridder.c" nogil:
+ double ridder(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
+
+cdef extern from "../Zeros/brenth.c" nogil:
+ double brenth(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
+
+cdef extern from "../Zeros/brentq.c" nogil:
+ double brentq(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/elementwise.py b/.venv/lib/python3.12/site-packages/scipy/optimize/elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7be4484626880182a17acf883d72388937578d1
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/elementwise.py
@@ -0,0 +1,38 @@
+"""
+===================================================================
+Elementwise Scalar Optimization (:mod:`scipy.optimize.elementwise`)
+===================================================================
+
+.. currentmodule:: scipy.optimize.elementwise
+
+This module provides a collection of functions for root finding and
+minimization of scalar, real-valued functions of one variable. Unlike their
+counterparts in the base :mod:`scipy.optimize` namespace, these functions work
+elementwise, enabling the solution of many related problems in an efficient,
+vectorized call. Furthermore, when environment variable ``SCIPY_ARRAY_API=1``,
+these functions can accept non-NumPy, array API standard compatible arrays and
+perform all calculations using the corresponding array library (e.g. PyTorch,
+JAX, CuPy).
+
+Root finding
+============
+
+.. autosummary::
+ :toctree: generated/
+
+ find_root
+ bracket_root
+
+Minimization
+============
+
+.. autosummary::
+ :toctree: generated/
+
+ find_minimum
+ bracket_minimum
+
+"""
+from ._elementwise import find_root, find_minimum, bracket_root, bracket_minimum # noqa: F401, E501
+
+__all__ = ["find_root", "find_minimum", "bracket_root", "bracket_minimum"]
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/lbfgsb.py b/.venv/lib/python3.12/site-packages/scipy/optimize/lbfgsb.py
new file mode 100644
index 0000000000000000000000000000000000000000..866407cabb3decf0ff72239e6fd372f69f7550c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/lbfgsb.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'LbfgsInvHessProduct',
+ 'OptimizeResult',
+ 'fmin_l_bfgs_b',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="lbfgsb",
+ private_modules=["_lbfgsb_py"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/linesearch.py b/.venv/lib/python3.12/site-packages/scipy/optimize/linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb34b25092da34991c868683da3d6a894d1a7f80
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/linesearch.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["line_search"] # noqa: F822
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="linesearch",
+ private_modules=["_linesearch"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/minpack.py b/.venv/lib/python3.12/site-packages/scipy/optimize/minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..29fddef537361d8508e6343d23b2c3c7d6d12ec6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/minpack.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'OptimizeWarning',
+ 'curve_fit',
+ 'fixed_point',
+ 'fsolve',
+ 'least_squares',
+ 'leastsq',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="minpack",
+ private_modules=["_minpack_py"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/minpack2.py b/.venv/lib/python3.12/site-packages/scipy/optimize/minpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdb3503e0e1e4c886c89bfb62e6a2efc3ba54549
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/minpack2.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="minpack2",
+ private_modules=["_minpack2"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/moduleTNC.py b/.venv/lib/python3.12/site-packages/scipy/optimize/moduleTNC.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fc5884ed5c39437b7681395419d641443a1fdb8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/moduleTNC.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = []
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="moduleTNC",
+ private_modules=["_moduleTNC"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/nonlin.py b/.venv/lib/python3.12/site-packages/scipy/optimize/nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..20b490b40ef790a2943d539790b45fc378df2c76
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/nonlin.py
@@ -0,0 +1,29 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'BroydenFirst',
+ 'InverseJacobian',
+ 'KrylovJacobian',
+ 'anderson',
+ 'broyden1',
+ 'broyden2',
+ 'diagbroyden',
+ 'excitingmixing',
+ 'linearmixing',
+ 'newton_krylov',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="nonlin",
+ private_modules=["_nonlin"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/optimize.py b/.venv/lib/python3.12/site-packages/scipy/optimize/optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..4db770e5f6e921906c916f2650003d92f5507791
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/optimize.py
@@ -0,0 +1,40 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'OptimizeWarning',
+ 'approx_fprime',
+ 'bracket',
+ 'brent',
+ 'brute',
+ 'check_grad',
+ 'fmin',
+ 'fmin_bfgs',
+ 'fmin_cg',
+ 'fmin_ncg',
+ 'fmin_powell',
+ 'fminbound',
+ 'golden',
+ 'line_search',
+ 'rosen',
+ 'rosen_der',
+ 'rosen_hess',
+ 'rosen_hess_prod',
+ 'show_options',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="optimize",
+ private_modules=["_optimize"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/slsqp.py b/.venv/lib/python3.12/site-packages/scipy/optimize/slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b79d93a55d363ac4a91154f30919ba5e449b8c7
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/slsqp.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'fmin_slsqp',
+ 'slsqp',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="slsqp",
+ private_modules=["_slsqp_py"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/__init__.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..d831b3c7f5dcaee71371027c7ee95aa9ee51d157
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+"""
+Taken from docstring for scipy.optimize.cython_optimize module.
+"""
+
+from scipy.optimize.cython_optimize cimport brentq
+
+# import math from Cython
+from libc cimport math
+
+myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments
+XLO, XHI = 0.5, 1.0 # lower and upper search boundaries
+XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters
+
+# user-defined struct for extra parameters
+ctypedef struct test_params:
+ double C0
+ double C1
+
+
+# user-defined callback
+cdef double f(double x, void *args) noexcept:
+ cdef test_params *myargs = args
+ return myargs.C0 - math.exp(-(x - myargs.C1))
+
+
+# Cython wrapper function
+cdef double brentq_wrapper_example(dict args, double xa, double xb,
+ double xtol, double rtol, int mitr):
+ # Cython automatically casts dictionary to struct
+ cdef test_params myargs = args
+ return brentq(
+ f, xa, xb, &myargs, xtol, rtol, mitr, NULL)
+
+
+# Python function
+def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL,
+ mitr=MITR):
+ '''Calls Cython wrapper from Python.'''
+ return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/meson.build b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..daa94864a16a311a6c7d7752cfa7e6b67280e17c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/meson.build
@@ -0,0 +1,32 @@
+project('random-build-examples', 'c', 'cpp', 'cython')
+
+fs = import('fs')
+
+py3 = import('python').find_installation(pure: false)
+
+cy = meson.get_compiler('cython')
+
+if not cy.version().version_compare('>=3.2.0')
+ error('tests requires Cython >= 3.2.0')
+endif
+
+cython_args = []
+if cy.version().version_compare('>=3.1.0')
+ cython_args += ['-Xfreethreading_compatible=True']
+endif
+
+py3.extension_module(
+ 'extending',
+ 'extending.pyx',
+ cython_args: cython_args,
+ install: false,
+)
+
+extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')
+py3.extension_module(
+ 'extending_cpp',
+ extending_cpp,
+ cython_args: cython_args,
+ install: false,
+ override_options : ['cython_language=cpp']
+)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/cython_abi_signatures.json b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/cython_abi_signatures.json
new file mode 100644
index 0000000000000000000000000000000000000000..3e0f95ec77734143bce2acdbb6075518426f70c0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/cython_abi_signatures.json
@@ -0,0 +1,8 @@
+{
+ "scipy.optimize.cython_optimize._zeros": {
+ "bisect": "double (__pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_callback_type, double, double, void *, double, double, int, __pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_zeros_full_output *)",
+ "brenth": "double (__pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_callback_type, double, double, void *, double, double, int, __pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_zeros_full_output *)",
+ "brentq": "double (__pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_callback_type, double, double, void *, double, double, int, __pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_zeros_full_output *)",
+ "ridder": "double (__pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_callback_type, double, double, void *, double, double, int, __pyx_t_5scipy_8optimize_15cython_optimize_6_zeros_zeros_full_output *)"
+ }
+}
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__basinhopping.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f21ae1728a0fa0918b5da6b2292fe88fc695fe5
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__basinhopping.py
@@ -0,0 +1,537 @@
+"""
+Unit tests for the basin hopping global minimization algorithm.
+"""
+import copy
+
+from numpy.testing import (assert_almost_equal, assert_equal, assert_,
+ assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from numpy import cos, sin
+
+from scipy.optimize import basinhopping, OptimizeResult
+from scipy.optimize._basinhopping import (
+ Storage, RandomDisplacement, Metropolis, AdaptiveStepsize)
+
+
+def func1d(x):
+ f = cos(14.5 * x - 0.3) + (x + 0.2) * x
+ df = np.array(-14.5 * sin(14.5 * x - 0.3) + 2. * x + 0.2)
+ return f, df
+
+
+def func2d_nograd(x):
+ f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0]
+ return f
+
+
+def func2d(x):
+ f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0]
+ df = np.zeros(2)
+ df[0] = -14.5 * sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
+ df[1] = 2. * x[1] + 0.2
+ return f, df
+
+
+def func2d_easyderiv(x):
+ f = 2.0*x[0]**2 + 2.0*x[0]*x[1] + 2.0*x[1]**2 - 6.0*x[0]
+ df = np.zeros(2)
+ df[0] = 4.0*x[0] + 2.0*x[1] - 6.0
+ df[1] = 2.0*x[0] + 4.0*x[1]
+
+ return f, df
+
+
+class MyTakeStep1(RandomDisplacement):
+ """use a copy of displace, but have it set a special parameter to
+ make sure it's actually being used."""
+ def __init__(self):
+ self.been_called = False
+ super().__init__()
+
+ def __call__(self, x):
+ self.been_called = True
+ return super().__call__(x)
+
+
+def myTakeStep2(x):
+ """redo RandomDisplacement in function form without the attribute stepsize
+ to make sure everything still works ok
+ """
+ s = 0.5
+ x += np.random.uniform(-s, s, np.shape(x))
+ return x
+
+
+class MyAcceptTest:
+ """pass a custom accept test
+
+ This does nothing but make sure it's being used and ensure all the
+ possible return values are accepted
+ """
+ def __init__(self):
+ self.been_called = False
+ self.ncalls = 0
+ self.testres = [False, 'force accept', True, np.bool_(True),
+ np.bool_(False), [], {}, 0, 1]
+
+ def __call__(self, **kwargs):
+ self.been_called = True
+ self.ncalls += 1
+ if self.ncalls - 1 < len(self.testres):
+ return self.testres[self.ncalls - 1]
+ else:
+ return True
+
+
+class MyCallBack:
+ """pass a custom callback function
+
+ This makes sure it's being used. It also returns True after 10
+ steps to ensure that it's stopping early.
+
+ """
+ def __init__(self):
+ self.been_called = False
+ self.ncalls = 0
+
+ def __call__(self, x, f, accepted):
+ self.been_called = True
+ self.ncalls += 1
+ if self.ncalls == 10:
+ return True
+
+
+class TestBasinHopping:
+
+ def setup_method(self):
+ """ Tests setup.
+
+ Run tests based on the 1-D and 2-D functions described above.
+ """
+ self.x0 = (1.0, [1.0, 1.0])
+ self.sol = (-0.195, np.array([-0.195, -0.1]))
+
+ self.tol = 3 # number of decimal places
+
+ self.niter = 100
+ self.disp = False
+
+ self.kwargs = {"method": "L-BFGS-B", "jac": True}
+ self.kwargs_nograd = {"method": "L-BFGS-B"}
+
+ def test_TypeError(self):
+ # test the TypeErrors are raised on bad input
+ i = 1
+ # if take_step is passed, it must be callable
+ assert_raises(TypeError, basinhopping, func2d, self.x0[i],
+ take_step=1)
+ # if accept_test is passed, it must be callable
+ assert_raises(TypeError, basinhopping, func2d, self.x0[i],
+ accept_test=1)
+
+ def test_input_validation(self):
+ msg = 'target_accept_rate has to be in range \\(0, 1\\)'
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], target_accept_rate=0.)
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], target_accept_rate=1.)
+
+ msg = 'stepwise_factor has to be in range \\(0, 1\\)'
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], stepwise_factor=0.)
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], stepwise_factor=1.)
+
+ def test_1d_grad(self):
+ # test 1-D minimizations with gradient
+ i = 0
+ res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ def test_2d(self):
+ # test 2d minimizations with gradient
+ i = 1
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+ assert_(res.nfev > 0)
+
+ def test_njev(self):
+ # test njev is returned correctly
+ i = 1
+ minimizer_kwargs = self.kwargs.copy()
+ # L-BFGS-B doesn't use njev, but BFGS does
+ minimizer_kwargs["method"] = "BFGS"
+ res = basinhopping(func2d, self.x0[i],
+ minimizer_kwargs=minimizer_kwargs, niter=self.niter,
+ disp=self.disp)
+ assert_(res.nfev > 0)
+ assert_equal(res.nfev, res.njev)
+
+ def test_jac(self):
+ # test Jacobian returned
+ minimizer_kwargs = self.kwargs.copy()
+ # BFGS returns a Jacobian
+ minimizer_kwargs["method"] = "BFGS"
+
+ res = basinhopping(func2d_easyderiv, [0.0, 0.0],
+ minimizer_kwargs=minimizer_kwargs, niter=self.niter,
+ disp=self.disp)
+
+ assert_(hasattr(res.lowest_optimization_result, "jac"))
+
+ # in this case, the Jacobian is just [df/dx, df/dy]
+ _, jacobian = func2d_easyderiv(res.x)
+ assert_almost_equal(res.lowest_optimization_result.jac, jacobian,
+ self.tol)
+
+ def test_2d_nograd(self):
+ # test 2-D minimizations without gradient
+ i = 1
+ res = basinhopping(func2d_nograd, self.x0[i],
+ minimizer_kwargs=self.kwargs_nograd,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ @pytest.mark.fail_slow(10)
+ def test_all_minimizers(self):
+ # Test 2-D minimizations with gradient. Nelder-Mead, Powell, COBYLA, and
+ # COBYQA don't accept jac=True, so aren't included here.
+ i = 1
+ methods = ['CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP']
+ minimizer_kwargs = copy.copy(self.kwargs)
+ for method in methods:
+ minimizer_kwargs["method"] = method
+ res = basinhopping(func2d, self.x0[i],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ @pytest.mark.fail_slow(40)
+ @pytest.mark.parametrize("method", [
+ 'CG', 'BFGS', 'L-BFGS-B', 'TNC', 'SLSQP',
+ 'Nelder-Mead', 'Powell', 'COBYLA', 'COBYQA'])
+ def test_all_nograd_minimizers(self, method):
+ # Test 2-D minimizations without gradient. Newton-CG requires jac=True,
+ # so not included here.
+ i = 1
+ minimizer_kwargs = self.kwargs_nograd.copy()
+ minimizer_kwargs["method"] = method
+ # These methods take extensive amount of time on this problem
+ niter = 10 if method in ('COBYLA', 'COBYQA') else self.niter
+
+ res = basinhopping(func2d_nograd, self.x0[i],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=niter, disp=self.disp, seed=1234)
+
+ tol = 2 if method == 'COBYLA' else self.tol
+ assert_almost_equal(res.x, self.sol[i], decimal=tol)
+
+ def test_pass_takestep(self):
+ # test that passing a custom takestep works
+ # also test that the stepsize is being adjusted
+ takestep = MyTakeStep1()
+ initial_step_size = takestep.stepsize
+ i = 1
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp,
+ take_step=takestep)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+ assert_(takestep.been_called)
+ # make sure that the build in adaptive step size has been used
+ assert_(initial_step_size != takestep.stepsize)
+
+ def test_pass_simple_takestep(self):
+ # test that passing a custom takestep without attribute stepsize
+ takestep = myTakeStep2
+ i = 1
+ res = basinhopping(func2d_nograd, self.x0[i],
+ minimizer_kwargs=self.kwargs_nograd,
+ niter=self.niter, disp=self.disp,
+ take_step=takestep)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ def test_pass_accept_test(self):
+ # test passing a custom accept test
+ # makes sure it's being used and ensures all the possible return values
+ # are accepted.
+ accept_test = MyAcceptTest()
+ i = 1
+ # there's no point in running it more than a few steps.
+ basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=10, disp=self.disp, accept_test=accept_test)
+ assert_(accept_test.been_called)
+
+ def test_pass_callback(self):
+ # test passing a custom callback function
+ # This makes sure it's being used. It also returns True after 10 steps
+ # to ensure that it's stopping early.
+ callback = MyCallBack()
+ i = 1
+ # there's no point in running it more than a few steps.
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=30, disp=self.disp, callback=callback)
+ assert_(callback.been_called)
+ assert_("callback" in res.message[0])
+ # One of the calls of MyCallBack is during BasinHoppingRunner
+ # construction, so there are only 9 remaining before MyCallBack stops
+ # the minimization.
+ assert_equal(res.nit, 9)
+
+ def test_minimizer_fail(self):
+ # test if a minimizer fails
+ i = 1
+ self.kwargs["options"] = dict(maxiter=0)
+ niter = 10
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=niter, disp=self.disp)
+ # the number of failed minimizations should be the number of
+ # iterations + 1
+ assert_equal(res.nit + 1, res.minimization_failures)
+
+ def test_niter_zero(self):
+ # gh5915, what happens if you call basinhopping with niter=0
+ i = 0
+ basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=0, disp=self.disp)
+
+ def test_rng_reproducibility(self):
+ # rng should ensure reproducibility between runs
+ minimizer_kwargs = {"method": "L-BFGS-B", "jac": True}
+
+ f_1 = []
+
+ def callback(x, f, accepted):
+ f_1.append(f)
+
+ basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs,
+ niter=10, callback=callback, rng=10)
+
+ f_2 = []
+
+ def callback2(x, f, accepted):
+ f_2.append(f)
+
+ basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs,
+ niter=10, callback=callback2, rng=10)
+ assert_equal(np.array(f_1), np.array(f_2))
+
+ def test_random_gen(self):
+ # check that np.random.Generator can be used (numpy >= 1.17)
+ rng = np.random.default_rng(1)
+
+ minimizer_kwargs = {"method": "L-BFGS-B", "jac": True}
+
+ res1 = basinhopping(func2d, [1.0, 1.0],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=10, rng=rng)
+
+ rng = np.random.default_rng(1)
+ res2 = basinhopping(func2d, [1.0, 1.0],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=10, rng=rng)
+ assert_equal(res1.x, res2.x)
+
+ def test_monotonic_basin_hopping(self):
+ # test 1-D minimizations with gradient and T=0
+ i = 0
+
+ res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp, T=0)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+
+class Test_Storage:
+ def create_storage(self):
+ self.x0 = np.array(1)
+ self.f0 = 0
+
+ minres = OptimizeResult(success=True)
+ minres.x = self.x0
+ minres.fun = self.f0
+
+ return Storage(minres)
+
+ def test_higher_f_rejected(self):
+ storage = self.create_storage()
+ new_minres = OptimizeResult(success=True)
+ new_minres.x = self.x0 + 1
+ new_minres.fun = self.f0 + 1
+
+ ret = storage.update(new_minres)
+ minres = storage.get_lowest()
+ assert_equal(self.x0, minres.x)
+ assert_equal(self.f0, minres.fun)
+ assert_(not ret)
+
+ @pytest.mark.parametrize('success', [True, False])
+ def test_lower_f_accepted(self, success):
+ storage = self.create_storage()
+ new_minres = OptimizeResult(success=success)
+ new_minres.x = self.x0 + 1
+ new_minres.fun = self.f0 - 1
+
+ ret = storage.update(new_minres)
+ minres = storage.get_lowest()
+ assert (self.x0 != minres.x) == success # can't use `is`
+ assert (self.f0 != minres.fun) == success # left side is NumPy bool
+ assert ret is success
+
+
+class Test_RandomDisplacement:
+ def setup_method(self):
+ self.stepsize = 1.0
+ self.N = 300000
+
+ def test_random(self):
+ # the mean should be 0
+ # the variance should be (2*stepsize)**2 / 12
+ # note these tests are random, they will fail from time to time
+ rng = np.random.RandomState(0)
+ x0 = np.zeros([self.N])
+ displace = RandomDisplacement(stepsize=self.stepsize, rng=rng)
+ x = displace(x0)
+ v = (2. * self.stepsize) ** 2 / 12
+ assert_almost_equal(np.mean(x), 0., 1)
+ assert_almost_equal(np.var(x), v, 1)
+
+
+class Test_Metropolis:
+ def setup_method(self):
+ self.T = 2.
+ self.met = Metropolis(self.T)
+ self.res_new = OptimizeResult(success=True, fun=0.)
+ self.res_old = OptimizeResult(success=True, fun=1.)
+
+ def test_boolean_return(self):
+ # the return must be a bool, else an error will be raised in
+ # basinhopping
+ ret = self.met(res_new=self.res_new, res_old=self.res_old)
+ assert isinstance(ret, bool)
+
+ def test_lower_f_accepted(self):
+ assert_(self.met(res_new=self.res_new, res_old=self.res_old))
+
+ def test_accept(self):
+ # test that steps are randomly accepted for f_new > f_old
+ one_accept = False
+ one_reject = False
+ for i in range(1000):
+ if one_accept and one_reject:
+ break
+ res_new = OptimizeResult(success=True, fun=1.)
+ res_old = OptimizeResult(success=True, fun=0.5)
+ ret = self.met(res_new=res_new, res_old=res_old)
+ if ret:
+ one_accept = True
+ else:
+ one_reject = True
+ assert_(one_accept)
+ assert_(one_reject)
+
+ def test_GH7495(self):
+ # an overflow in exp was producing a RuntimeWarning
+ # create own object here in case someone changes self.T
+ met = Metropolis(2)
+ res_new = OptimizeResult(success=True, fun=0.)
+ res_old = OptimizeResult(success=True, fun=2000)
+ with np.errstate(over='raise'):
+ met.accept_reject(res_new=res_new, res_old=res_old)
+
+ def test_gh7799(self):
+ # gh-7799 reported a problem in which local search was successful but
+ # basinhopping returned an invalid solution. Show that this is fixed.
+ def func(x):
+ return (x**2-8)**2+(x+2)**2
+
+ x0 = -4
+ limit = 50 # Constrain to func value >= 50
+ con = {'type': 'ineq', 'fun': lambda x: func(x) - limit},
+ res = basinhopping(
+ func,
+ x0,
+ 30,
+ seed=np.random.RandomState(1234),
+ minimizer_kwargs={'constraints': con}
+ )
+ assert res.success
+ assert_allclose(res.fun, limit, rtol=1e-6)
+
+ def test_accept_gh7799(self):
+ # Metropolis should not accept the result of an unsuccessful new local
+ # search if the old local search was successful
+
+ met = Metropolis(0) # monotonic basin hopping
+ res_new = OptimizeResult(success=True, fun=0.)
+ res_old = OptimizeResult(success=True, fun=1.)
+
+ # if new local search was successful and energy is lower, accept
+ assert met(res_new=res_new, res_old=res_old)
+ # if new res is unsuccessful, don't accept - even if energy is lower
+ res_new.success = False
+ assert not met(res_new=res_new, res_old=res_old)
+ # ...unless the old res was unsuccessful, too. In that case, why not?
+ res_old.success = False
+ assert met(res_new=res_new, res_old=res_old)
+
+ def test_reject_all_gh7799(self):
+ # Test the behavior when there is no feasible solution
+ def fun(x):
+ return x@x
+
+ def constraint(x):
+ return x + 1
+
+ kwargs = {'constraints': {'type': 'eq', 'fun': constraint},
+ 'bounds': [(0, 1), (0, 1)], 'method': 'slsqp'}
+ res = basinhopping(fun, x0=[2, 3], niter=10, minimizer_kwargs=kwargs)
+ assert not res.success
+
+
+@pytest.mark.thread_unsafe(reason="shared state")
+class Test_AdaptiveStepsize:
+ def setup_method(self):
+ self.stepsize = 1.
+ self.ts = RandomDisplacement(stepsize=self.stepsize)
+ self.target_accept_rate = 0.5
+ self.takestep = AdaptiveStepsize(takestep=self.ts, verbose=False,
+ accept_rate=self.target_accept_rate)
+
+ def test_adaptive_increase(self):
+ # if few steps are rejected, the stepsize should increase
+ x = 0.
+ self.takestep(x)
+ self.takestep.report(False)
+ for i in range(self.takestep.interval):
+ self.takestep(x)
+ self.takestep.report(True)
+ assert_(self.ts.stepsize > self.stepsize)
+
+ def test_adaptive_decrease(self):
+ # if few steps are rejected, the stepsize should increase
+ x = 0.
+ self.takestep(x)
+ self.takestep.report(True)
+ for i in range(self.takestep.interval):
+ self.takestep(x)
+ self.takestep.report(False)
+ assert_(self.ts.stepsize < self.stepsize)
+
+ def test_all_accepted(self):
+ # test that everything works OK if all steps were accepted
+ x = 0.
+ for i in range(self.takestep.interval + 1):
+ self.takestep(x)
+ self.takestep.report(True)
+ assert_(self.ts.stepsize > self.stepsize)
+
+ def test_all_rejected(self):
+ # test that everything works OK if all steps were rejected
+ x = 0.
+ for i in range(self.takestep.interval + 1):
+ self.takestep(x)
+ self.takestep.report(False)
+ assert_(self.ts.stepsize < self.stepsize)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__differential_evolution.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__differential_evolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7e1daa8a0152b8dda8da415ca07eecb258d7fbf
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__differential_evolution.py
@@ -0,0 +1,1751 @@
+"""
+Unit tests for the differential global minimization algorithm.
+"""
+from multiprocessing.dummy import Pool as ThreadPool
+import platform
+import warnings
+
+from scipy._lib._gcutils import assert_deallocated
+from scipy.optimize._differentialevolution import (DifferentialEvolutionSolver,
+ _ConstraintWrapper)
+from scipy.optimize import differential_evolution, OptimizeResult
+from scipy.optimize._constraints import (Bounds, NonlinearConstraint,
+ LinearConstraint)
+from scipy.optimize import rosen, minimize, rosen_der
+from scipy.sparse import csr_array
+from scipy import stats
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_allclose, assert_almost_equal,
+ assert_string_equal, assert_)
+from pytest import raises as assert_raises, warns
+import pytest
+
+
+class TestDifferentialEvolutionSolver:
+
+ def setup_method(self):
+ self.old_seterr = np.seterr(invalid='raise')
+ self.limits = np.array([[0., 0.],
+ [2., 2.]])
+ self.bounds = [(0., 2.), (0., 2.)]
+
+ self.dummy_solver = DifferentialEvolutionSolver(self.quadratic,
+ [(0, 100)])
+
+ # dummy_solver2 will be used to test mutation strategies
+ self.dummy_solver2 = DifferentialEvolutionSolver(self.quadratic,
+ [(0, 1)],
+ popsize=7,
+ mutation=0.5)
+ # create a population that's only 7 members long
+ # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
+ population = np.atleast_2d(np.arange(0.1, 0.8, 0.1)).T
+ self.dummy_solver2.population = population
+
+ def teardown_method(self):
+ np.seterr(**self.old_seterr)
+
+ def quadratic(self, x):
+ return x[0]**2
+
+ def test__strategy_resolves(self):
+ # test that the correct mutation function is resolved by
+ # different requested strategy arguments
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best1exp')
+ assert_equal(solver.strategy, 'best1exp')
+ assert_equal(solver.mutation_func.__name__, '_best1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best1bin')
+ assert_equal(solver.strategy, 'best1bin')
+ assert_equal(solver.mutation_func.__name__, '_best1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand1bin')
+ assert_equal(solver.strategy, 'rand1bin')
+ assert_equal(solver.mutation_func.__name__, '_rand1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand1exp')
+ assert_equal(solver.strategy, 'rand1exp')
+ assert_equal(solver.mutation_func.__name__, '_rand1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand2exp')
+ assert_equal(solver.strategy, 'rand2exp')
+ assert_equal(solver.mutation_func.__name__, '_rand2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best2bin')
+ assert_equal(solver.strategy, 'best2bin')
+ assert_equal(solver.mutation_func.__name__, '_best2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand2bin')
+ assert_equal(solver.strategy, 'rand2bin')
+ assert_equal(solver.mutation_func.__name__, '_rand2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand2exp')
+ assert_equal(solver.strategy, 'rand2exp')
+ assert_equal(solver.mutation_func.__name__, '_rand2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='randtobest1bin')
+ assert_equal(solver.strategy, 'randtobest1bin')
+ assert_equal(solver.mutation_func.__name__, '_randtobest1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='randtobest1exp')
+ assert_equal(solver.strategy, 'randtobest1exp')
+ assert_equal(solver.mutation_func.__name__, '_randtobest1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='currenttobest1bin')
+ assert_equal(solver.strategy, 'currenttobest1bin')
+ assert_equal(solver.mutation_func.__name__, '_currenttobest1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='currenttobest1exp')
+ assert_equal(solver.strategy, 'currenttobest1exp')
+ assert_equal(solver.mutation_func.__name__, '_currenttobest1')
+
+ def test__mutate1(self):
+ # strategies */1/*, i.e. rand/1/bin, best/1/exp, etc.
+ result = np.array([0.05])
+ trial = self.dummy_solver2._best1(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ result = np.array([0.25])
+ trial = self.dummy_solver2._rand1(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ def test__mutate2(self):
+ # strategies */2/*, i.e. rand/2/bin, best/2/exp, etc.
+ # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
+
+ result = np.array([-0.1])
+ trial = self.dummy_solver2._best2(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ result = np.array([0.1])
+ trial = self.dummy_solver2._rand2(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ def test__randtobest1(self):
+ # strategies randtobest/1/*
+ result = np.array([0.15])
+ trial = self.dummy_solver2._randtobest1(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ def test__currenttobest1(self):
+ # strategies currenttobest/1/*
+ result = np.array([0.1])
+ trial = self.dummy_solver2._currenttobest1(
+ 1,
+ np.array([2, 3, 4, 5, 6])
+ )
+ assert_allclose(trial, result)
+
+ def test_can_init_with_dithering(self):
+ mutation = (0.5, 1)
+ solver = DifferentialEvolutionSolver(self.quadratic,
+ self.bounds,
+ mutation=mutation)
+
+ assert_equal(solver.dither, list(mutation))
+
+ def test_invalid_mutation_values_arent_accepted(self):
+ func = rosen
+ mutation = (0.5, 3)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ func,
+ self.bounds,
+ mutation=mutation)
+
+ mutation = (-1, 1)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ func,
+ self.bounds,
+ mutation=mutation)
+
+ mutation = (0.1, np.nan)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ func,
+ self.bounds,
+ mutation=mutation)
+
+ mutation = 0.5
+ solver = DifferentialEvolutionSolver(func,
+ self.bounds,
+ mutation=mutation)
+ assert_equal(0.5, solver.scale)
+ assert_equal(None, solver.dither)
+
+ def test_invalid_functional(self):
+ def func(x):
+ return np.array([np.sum(x ** 2), np.sum(x)])
+
+ with assert_raises(
+ RuntimeError,
+ match=r"func\(x, \*args\) must return a scalar value"):
+ differential_evolution(func, [(-2, 2), (-2, 2)])
+
+ def test__scale_parameters(self):
+ trial = np.array([0.3])
+ assert_equal(30, self.dummy_solver._scale_parameters(trial))
+
+ # it should also work with the limits reversed
+ self.dummy_solver.limits = np.array([[100], [0.]])
+ assert_equal(30, self.dummy_solver._scale_parameters(trial))
+
+ def test__unscale_parameters(self):
+ trial = np.array([30])
+ assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
+
+ # it should also work with the limits reversed
+ self.dummy_solver.limits = np.array([[100], [0.]])
+ assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
+
+ def test_equal_bounds(self):
+ with np.errstate(invalid='raise'):
+ solver = DifferentialEvolutionSolver(
+ self.quadratic,
+ bounds=[(2.0, 2.0), (1.0, 3.0)]
+ )
+ v = solver._unscale_parameters([2.0, 2.0])
+ assert_allclose(v, 0.5)
+
+ res = differential_evolution(self.quadratic, [(2.0, 2.0), (3.0, 3.0)])
+ assert_equal(res.x, [2.0, 3.0])
+
+ def test__ensure_constraint(self):
+ trial = np.array([1.1, -100, 0.9, 2., 300., -0.00001])
+ self.dummy_solver._ensure_constraint(trial)
+
+ assert_equal(trial[2], 0.9)
+ assert_(np.logical_and(trial >= 0, trial <= 1).all())
+
+ def test_differential_evolution(self):
+ # test that the Jmin of DifferentialEvolutionSolver
+ # is the same as the function evaluation
+ solver = DifferentialEvolutionSolver(
+ self.quadratic, [(-2, 2)], maxiter=1, polish=False
+ )
+ result = solver.solve()
+ assert_equal(result.fun, self.quadratic(result.x))
+
+ solver = DifferentialEvolutionSolver(
+ self.quadratic, [(-2, 2)], maxiter=1, polish=True
+ )
+ result = solver.solve()
+ assert_equal(result.fun, self.quadratic(result.x))
+
+ def test_best_solution_retrieval(self):
+ # test that the getter property method for the best solution works.
+ solver = DifferentialEvolutionSolver(self.quadratic, [(-2, 2)])
+ result = solver.solve()
+ assert_allclose(result.x, solver.x, atol=1e-15, rtol=0)
+
+ def test_intermediate_result(self):
+ # Check that intermediate result object passed into the callback
+ # function contains the expected information and that raising
+ # `StopIteration` causes the expected behavior.
+ maxiter = 10
+
+ def func(x):
+ val = rosen(x)
+ if val < func.val:
+ func.x = x
+ func.val = val
+ return val
+ func.x = None
+ func.val = np.inf
+
+ def callback(intermediate_result):
+ callback.nit += 1
+ callback.intermediate_result = intermediate_result
+ assert intermediate_result.population.ndim == 2
+ assert intermediate_result.population.shape[1] == 2
+ assert intermediate_result.nit == callback.nit
+
+ # Check that `x` and `fun` attributes are the best found so far
+ assert_equal(intermediate_result.x, callback.func.x)
+ assert_equal(intermediate_result.fun, callback.func.val)
+
+ # Check for consistency between `fun`, `population_energies`,
+ # `x`, and `population`
+ assert_equal(intermediate_result.fun, rosen(intermediate_result.x))
+ for i in range(len(intermediate_result.population_energies)):
+ res = intermediate_result.population_energies[i]
+ ref = rosen(intermediate_result.population[i])
+ assert_equal(res, ref)
+ assert_equal(intermediate_result.x,
+ intermediate_result.population[0])
+ assert_equal(intermediate_result.fun,
+ intermediate_result.population_energies[0])
+
+ assert intermediate_result.message == 'in progress'
+ assert intermediate_result.success is True
+ assert isinstance(intermediate_result, OptimizeResult)
+ if callback.nit == maxiter:
+ raise StopIteration
+ callback.nit = 0
+ callback.intermediate_result = None
+ callback.func = func
+
+ bounds = [(0, 2), (0, 2)]
+ kwargs = dict(func=func, bounds=bounds, rng=838245, polish=False)
+ res = differential_evolution(**kwargs, callback=callback)
+ ref = differential_evolution(**kwargs, maxiter=maxiter)
+
+ # Check that final `intermediate_result` is equivalent to returned
+ # result object and that terminating with callback `StopIteration`
+ # after `maxiter` iterations is equivalent to terminating with
+ # `maxiter` parameter.
+ assert res.success is ref.success is False
+ assert callback.nit == res.nit == maxiter
+ assert res.message == 'callback function requested stop early'
+ assert ref.message == 'Maximum number of iterations has been exceeded.'
+ for field, val in ref.items():
+ if field in {'message', 'success'}: # checked separately
+ continue
+ assert_equal(callback.intermediate_result[field], val)
+ assert_equal(res[field], val)
+
+ # Check that polish occurs after `StopIteration` as advertised
+ callback.nit = 0
+ func.val = np.inf
+ kwargs['polish'] = True
+ res = differential_evolution(**kwargs, callback=callback)
+ assert res.fun < ref.fun
+
+ def test_callback_terminates(self):
+ # test that if the callback returns true, then the minimization halts
+ bounds = [(0, 2), (0, 2)]
+ expected_msg = 'callback function requested stop early'
+ def callback_python_true(param, convergence=0.):
+ return True
+
+ result = differential_evolution(
+ rosen, bounds, callback=callback_python_true
+ )
+ assert_string_equal(result.message, expected_msg)
+
+ # if callback raises StopIteration then solve should be interrupted
+ def callback_stop(intermediate_result):
+ raise StopIteration
+
+ result = differential_evolution(rosen, bounds, callback=callback_stop)
+ assert not result.success
+
+ def callback_evaluates_true(param, convergence=0.):
+ # DE should stop if bool(self.callback) is True
+ return [10]
+
+ result = differential_evolution(rosen, bounds, callback=callback_evaluates_true)
+ assert_string_equal(result.message, expected_msg)
+ assert not result.success
+
+ def callback_evaluates_false(param, convergence=0.):
+ return []
+
+ result = differential_evolution(rosen, bounds,
+ callback=callback_evaluates_false)
+ assert result.success
+
+ def test_args_tuple_is_passed(self):
+ # test that the args tuple is passed to the cost function properly.
+ bounds = [(-10, 10)]
+ args = (1., 2., 3.)
+
+ def quadratic(x, *args):
+ if not isinstance(args, tuple):
+ raise ValueError('args should be a tuple')
+ return args[0] + args[1] * x + args[2] * x**2.
+
+ result = differential_evolution(quadratic,
+ bounds,
+ args=args,
+ polish=True,
+ rng=1980983098)
+ assert_almost_equal(result.fun, 2 / 3.)
+
+ def test_init_with_invalid_strategy(self):
+ # test that passing an invalid strategy raises ValueError
+ func = rosen
+ bounds = [(-3, 3)]
+ assert_raises(ValueError,
+ differential_evolution,
+ func,
+ bounds,
+ strategy='abc')
+
+ def test_bounds_checking(self):
+ # test that the bounds checking works
+ func = rosen
+ bounds = [(-3)]
+ assert_raises(ValueError,
+ differential_evolution,
+ func,
+ bounds)
+ bounds = [(-3, 3), (3, 4, 5)]
+ assert_raises(ValueError,
+ differential_evolution,
+ func,
+ bounds)
+
+ # test that we can use a new-type Bounds object
+ result = differential_evolution(
+ rosen, Bounds([0, 0], [2, 2]), rng=1980983098
+ )
+ assert_almost_equal(result.x, (1., 1.))
+
+ def test_select_samples(self):
+ # select_samples should return 5 separate random numbers.
+ limits = np.arange(12., dtype='float64').reshape(2, 6)
+ bounds = list(zip(limits[0, :], limits[1, :]))
+ solver = DifferentialEvolutionSolver(None, bounds, popsize=1)
+ candidate = 0
+ r1, r2, r3, r4, r5 = solver._select_samples(candidate, 5)
+ assert_equal(
+ len(np.unique(np.array([candidate, r1, r2, r3, r4, r5]))), 6)
+
+ def test_maxiter_stops_solve(self):
+ # test that if the maximum number of iterations is exceeded
+ # the solver stops.
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=1)
+ result = solver.solve()
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of iterations has been exceeded.')
+
+ def test_maxfun_stops_solve(self):
+ # test that if the maximum number of function evaluations is exceeded
+ # during initialisation the solver stops
+ rng = np.random.default_rng(1980983098)
+
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, maxfun=1,
+ polish=False)
+ result = solver.solve()
+
+ assert_equal(result.nfev, 2)
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of function evaluations has '
+ 'been exceeded.')
+
+ # test that if the maximum number of function evaluations is exceeded
+ # during the actual minimisation, then the solver stops.
+ # Have to turn polishing off, as this will still occur even if maxfun
+ # is reached. For popsize=5 and len(bounds)=2, then there are only 10
+ # function evaluations during initialisation.
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ popsize=5,
+ polish=False,
+ maxfun=40,
+ rng=rng)
+ result = solver.solve()
+
+ assert_equal(result.nfev, 41)
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of function evaluations has '
+ 'been exceeded.')
+
+ # now repeat for updating='deferred version
+ # 47 function evaluations is not a multiple of the population size,
+ # so maxfun is reached partway through a population evaluation.
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ popsize=5,
+ polish=False,
+ maxfun=47,
+ updating='deferred',
+ rng=rng)
+ result = solver.solve()
+
+ assert_equal(result.nfev, 47)
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of function evaluations has '
+ 'been reached.')
+
+ def test_quadratic(self):
+ # test the quadratic function from object
+ solver = DifferentialEvolutionSolver(self.quadratic,
+ [(-100, 100)],
+ tol=0.02)
+ solver.solve()
+ assert_equal(np.argmin(solver.population_energies), 0)
+
+ def test_quadratic_from_diff_ev(self):
+ # test the quadratic function from differential_evolution function
+ differential_evolution(self.quadratic,
+ [(-100, 100)],
+ tol=0.02,
+ rng=1980983098)
+
+ def test_rng_gives_repeatability(self):
+ result = differential_evolution(self.quadratic,
+ [(-100, 100)],
+ polish=False,
+ rng=1,
+ tol=0.5)
+ result2 = differential_evolution(self.quadratic,
+ [(-100, 100)],
+ polish=False,
+ rng=1,
+ tol=0.5)
+ assert_equal(result.x, result2.x)
+ assert_equal(result.nfev, result2.nfev)
+
+ def test_random_generator(self):
+ # check that np.random.Generator can be used (numpy >= 1.17)
+ # obtain a np.random.Generator object
+ rng = np.random.default_rng()
+
+ inits = ['random', 'latinhypercube', 'sobol', 'halton']
+ for init in inits:
+ differential_evolution(self.quadratic,
+ [(-100, 100)],
+ polish=False,
+ rng=rng,
+ tol=0.5,
+ init=init)
+
+ def test_exp_runs(self):
+ # test whether exponential mutation loop runs
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best1exp',
+ maxiter=1)
+
+ solver.solve()
+
+ def test_gh_4511_regression(self):
+ # This modification of the differential evolution docstring example
+ # uses a custom popsize that had triggered an off-by-one error.
+ # Because we do not care about solving the optimization problem in
+ # this test, we use maxiter=1 to reduce the testing time.
+ bounds = [(-5, 5), (-5, 5)]
+ # result = differential_evolution(rosen, bounds, popsize=1815,
+ # maxiter=1)
+
+ # the original issue arose because of rounding error in arange, with
+ # linspace being a much better solution. 1815 is quite a large popsize
+ # to use and results in a long test time (~13s). I used the original
+ # issue to figure out the lowest number of samples that would cause
+ # this rounding error to occur, 49.
+ differential_evolution(rosen, bounds, popsize=49, maxiter=1)
+
+ def test_calculate_population_energies(self):
+ # if popsize is 3, then the overall generation has size (6,)
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3)
+ solver._calculate_population_energies(solver.population)
+ solver._promote_lowest_energy()
+ assert_equal(np.argmin(solver.population_energies), 0)
+
+ # initial calculation of the energies should require 6 nfev.
+ assert_equal(solver._nfev, 6)
+
+ def test_iteration(self):
+ # test that DifferentialEvolutionSolver is iterable
+ # if popsize is 3, then the overall generation has size (6,)
+ rng = np.random.default_rng(4210919)
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3,
+ maxfun=12, rng=rng)
+ x, fun = next(solver)
+ assert_equal(np.size(x, 0), 2)
+
+ # 6 nfev are required for initial calculation of energies, 6 nfev are
+ # required for the evolution of the 6 population members.
+ assert_equal(solver._nfev, 12)
+
+ # the next generation should halt because it exceeds maxfun
+ assert_raises(StopIteration, next, solver)
+
+ # check a proper minimisation can be done by an iterable solver
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, rng=rng)
+ _, fun_prev = next(solver)
+ for i, soln in enumerate(solver):
+ x_current, fun_current = soln
+ assert fun_prev >= fun_current
+ _, fun_prev = x_current, fun_current
+ # need to have this otherwise the solver would never stop.
+ if i == 50:
+ break
+
+ def test_convergence(self):
+ rng = np.random.default_rng(4210919)
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, tol=0.2,
+ polish=False, rng=rng)
+ solver.solve()
+ assert solver.convergence < 0.2
+
+ def test_maxiter_none_GH5731(self):
+ # Pre 0.17 the previous default for maxiter and maxfun was None.
+ # the numerical defaults are now 1000 and np.inf. However, some scripts
+ # will still supply None for both of those, this will raise a TypeError
+ # in the solve method.
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=None,
+ maxfun=None)
+ solver.solve()
+
+ def test_population_initiation(self):
+ # test the different modes of population initiation
+
+ # init must be either 'latinhypercube' or 'random'
+ # raising ValueError is something else is passed in
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ *(rosen, self.bounds),
+ **{'init': 'rubbish'})
+
+ solver = DifferentialEvolutionSolver(rosen, self.bounds)
+
+ # check that population initiation:
+ # 1) resets _nfev to 0
+ # 2) all population energies are np.inf
+ solver.init_population_random()
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ solver.init_population_lhs()
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ solver.init_population_qmc(qmc_engine='halton')
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, init='sobol')
+ solver.init_population_qmc(qmc_engine='sobol')
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ # we should be able to initialize with our own array
+ population = np.linspace(-1, 3, 10).reshape(5, 2)
+ solver = DifferentialEvolutionSolver(rosen, self.bounds,
+ init=population,
+ strategy='best2bin',
+ atol=0.01, rng=1, popsize=5)
+
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+ assert_(solver.num_population_members == 5)
+ assert_(solver.population_shape == (5, 2))
+
+ # check that the population was initialized correctly
+ unscaled_population = np.clip(solver._unscale_parameters(population),
+ 0, 1)
+ assert_almost_equal(solver.population[:5], unscaled_population)
+
+ # population values need to be clipped to bounds
+ assert_almost_equal(np.min(solver.population[:5]), 0)
+ assert_almost_equal(np.max(solver.population[:5]), 1)
+
+ # shouldn't be able to initialize with an array if it's the wrong shape
+ # this would have too many parameters
+ population = np.linspace(-1, 3, 15).reshape(5, 3)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ *(rosen, self.bounds),
+ **{'init': population})
+
+ # provide an initial solution
+ # bounds are [(0, 2), (0, 2)]
+ x0 = np.random.uniform(low=0.0, high=2.0, size=2)
+ solver = DifferentialEvolutionSolver(
+ rosen, self.bounds, x0=x0
+ )
+ # parameters are scaled to unit interval
+ assert_allclose(solver.population[0], x0 / 2.0)
+
+ def test_x0(self):
+ # smoke test that checks that x0 is usable.
+ rng = np.random.default_rng(4210919)
+ res = differential_evolution(rosen, self.bounds, x0=[0.2, 0.8], rng=rng)
+ assert res.success
+
+ # check what happens if some of the x0 lay outside the bounds
+ with assert_raises(ValueError):
+ differential_evolution(rosen, self.bounds, x0=[0.2, 2.1])
+
+ def test_infinite_objective_function(self):
+ # Test that there are no problems if the objective function
+ # returns inf on some runs
+ def sometimes_inf(x):
+ if x[0] < .5:
+ return np.inf
+ return x[1]
+ bounds = [(0, 1), (0, 1)]
+ differential_evolution(sometimes_inf, bounds=bounds, disp=False)
+
+ def test_deferred_updating(self):
+ # check setting of deferred updating, with default workers
+ rng = np.random.default_rng(4210919)
+ bounds = [(0., 2.), (0., 2.)]
+ solver = DifferentialEvolutionSolver(
+ rosen, bounds, updating='deferred', rng=rng
+ )
+ assert solver._updating == 'deferred'
+ assert solver._mapwrapper._mapfunc is map
+ res = solver.solve()
+ assert res.success
+
+ # check that deferred updating works with an exponential crossover
+ res = differential_evolution(
+ rosen, bounds, updating='deferred', strategy='best1exp', rng=rng
+ )
+ assert res.success
+
+ def test_immediate_updating(self):
+ # check setting of immediate updating, with default workers
+ bounds = [(0., 2.), (0., 2.)]
+ solver = DifferentialEvolutionSolver(rosen, bounds)
+ assert_(solver._updating == 'immediate')
+
+ # should raise a UserWarning because the updating='immediate'
+ # is being overridden by the workers keyword
+ with warns(UserWarning):
+ with DifferentialEvolutionSolver(rosen, bounds, workers=2) as s:
+ solver.solve()
+ assert s._updating == 'deferred'
+
+ def test_parallel_threads(self):
+ # smoke test for parallelization with deferred updating
+ bounds = [(0., 2.), (0., 2.)]
+ # use threads instead of Process to speed things up for this simple example
+ with ThreadPool(2) as p, DifferentialEvolutionSolver(
+ rosen, bounds, updating='deferred', workers=p.map, tol=0.1, popsize=3
+ ) as solver:
+ assert solver._mapwrapper.pool is not None
+ assert solver._updating == 'deferred'
+ solver.solve()
+
+ @pytest.mark.fail_slow(10)
+ def test_parallel_processes(self):
+ bounds = [(0., 2.), (0., 2.)]
+ with DifferentialEvolutionSolver(
+ rosen, bounds, updating='deferred', workers=2, popsize=3, tol=0.1
+ ) as solver:
+ assert solver._mapwrapper.pool is not None
+ assert solver._updating == 'deferred'
+ solver.solve()
+
+ def test_converged(self):
+ rng = np.random.default_rng(4210919)
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)], rng=rng)
+ solver.solve()
+ assert solver.converged()
+
+ def test_constraint_violation_fn(self):
+ def constr_f(x):
+ return [x[0] + x[1]]
+
+ def constr_f2(x):
+ return np.array([x[0]**2 + x[1], x[0] - x[1]])
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,))
+
+ cv = solver._constraint_violation_fn(np.array([1.0, 1.0]))
+ assert_almost_equal(cv, 0.1)
+
+ nlc2 = NonlinearConstraint(constr_f2, -np.inf, 1.8)
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc, nlc2))
+
+ # for multiple constraints the constraint violations should
+ # be concatenated.
+ xs = [(1.2, 1), (2.0, 2.0), (0.5, 0.5)]
+ vs = [(0.3, 0.64, 0.0), (2.1, 4.2, 0.0), (0, 0, 0)]
+
+ for x, v in zip(xs, vs):
+ cv = solver._constraint_violation_fn(np.array(x))
+ assert_allclose(cv, np.atleast_2d(v))
+
+ # vectorized calculation of a series of solutions
+ assert_allclose(
+ solver._constraint_violation_fn(np.array(xs)), np.array(vs)
+ )
+
+ # the following line is used in _calculate_population_feasibilities.
+ # _constraint_violation_fn returns an (1, M) array when
+ # x.shape == (N,), i.e. a single solution. Therefore this list
+ # comprehension should generate (S, 1, M) array.
+ constraint_violation = np.array([solver._constraint_violation_fn(x)
+ for x in np.array(xs)])
+ assert constraint_violation.shape == (3, 1, 3)
+
+ # we need reasonable error messages if the constraint function doesn't
+ # return the right thing
+ def constr_f3(x):
+ # returns (S, M), rather than (M, S)
+ return constr_f2(x).T
+
+ nlc2 = NonlinearConstraint(constr_f3, -np.inf, 1.8)
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc, nlc2),
+ vectorized=False)
+ solver.vectorized = True
+ with pytest.raises(
+ RuntimeError, match="An array returned from a Constraint"
+ ):
+ solver._constraint_violation_fn(np.array(xs))
+
+ def test_constraint_population_feasibilities(self):
+ def constr_f(x):
+ return [x[0] + x[1]]
+
+ def constr_f2(x):
+ return [x[0]**2 + x[1], x[0] - x[1]]
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,))
+
+ # are population feasibilities correct
+ # [0.5, 0.5] corresponds to scaled values of [1., 1.]
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.5, 0.5], [1., 1.]]))
+ assert_equal(feas, [False, False])
+ assert_almost_equal(cv, np.array([[0.1], [2.1]]))
+ assert cv.shape == (2, 1)
+
+ nlc2 = NonlinearConstraint(constr_f2, -np.inf, 1.8)
+
+ for vectorize in [False, True]:
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc, nlc2),
+ vectorized=vectorize,
+ updating='deferred')
+
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.5, 0.5], [0.6, 0.5]]))
+ assert_equal(feas, [False, False])
+ assert_almost_equal(cv, np.array([[0.1, 0.2, 0], [0.3, 0.64, 0]]))
+
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.5, 0.5], [1., 1.]]))
+ assert_equal(feas, [False, False])
+ assert_almost_equal(cv, np.array([[0.1, 0.2, 0], [2.1, 4.2, 0]]))
+ assert cv.shape == (2, 3)
+
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.25, 0.25], [1., 1.]]))
+ assert_equal(feas, [True, False])
+ assert_almost_equal(cv, np.array([[0.0, 0.0, 0.], [2.1, 4.2, 0]]))
+ assert cv.shape == (2, 3)
+
+ def test_constraint_solve(self):
+ rng = np.random.default_rng(4210919)
+
+ def constr_f(x):
+ return np.array([x[0] + x[1]])
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,), rng=rng)
+
+ # trust-constr warns if the constraint function is linear
+ with warns(UserWarning):
+ res = solver.solve()
+
+ assert constr_f(res.x) <= 1.9
+ assert res.success
+
+ @pytest.mark.fail_slow(10)
+ def test_impossible_constraint(self):
+ rng = np.random.default_rng(4210919)
+
+ def constr_f(x):
+ return np.array([x[0] + x[1]])
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, -1)
+
+ solver = DifferentialEvolutionSolver(
+ rosen, [(0, 2), (0, 2)], constraints=(nlc,), popsize=1, rng=rng, maxiter=100
+ )
+
+ # a UserWarning is issued because the 'trust-constr' polishing is
+ # attempted on the least infeasible solution found.
+ with warns(UserWarning):
+ res = solver.solve()
+
+ assert res.maxcv > 0
+ assert not res.success
+
+ # test _promote_lowest_energy works when none of the population is
+ # feasible. In this case, the solution with the lowest constraint
+ # violation should be promoted.
+ solver = DifferentialEvolutionSolver(
+ rosen, [(0, 2), (0, 2)], constraints=(nlc,), polish=False)
+ next(solver)
+ assert not solver.feasible.all()
+ assert not np.isfinite(solver.population_energies).all()
+
+ # now swap two of the entries in the population
+ l = 20
+ cv = solver.constraint_violation[0]
+
+ solver.population_energies[[0, l]] = solver.population_energies[[l, 0]]
+ solver.population[[0, l], :] = solver.population[[l, 0], :]
+ solver.constraint_violation[[0, l], :] = (
+ solver.constraint_violation[[l, 0], :])
+
+ solver._promote_lowest_energy()
+ assert_equal(solver.constraint_violation[0], cv)
+
+ def test_accept_trial(self):
+ # _accept_trial(self, energy_trial, feasible_trial, cv_trial,
+ # energy_orig, feasible_orig, cv_orig)
+ def constr_f(x):
+ return [x[0] + x[1]]
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,))
+ fn = solver._accept_trial
+ # both solutions are feasible, select lower energy
+ assert fn(0.1, True, np.array([0.]), 1.0, True, np.array([0.]))
+ assert (fn(1.0, True, np.array([0.0]), 0.1, True, np.array([0.0])) is False)
+ assert fn(0.1, True, np.array([0.]), 0.1, True, np.array([0.]))
+
+ # trial is feasible, original is not
+ assert fn(9.9, True, np.array([0.]), 1.0, False, np.array([1.]))
+
+ # trial and original are infeasible
+ # cv_trial have to be <= cv_original to be better
+ assert (fn(0.1, False, np.array([0.5, 0.5]),
+ 1.0, False, np.array([1., 1.0])))
+ assert (fn(0.1, False, np.array([0.5, 0.5]),
+ 1.0, False, np.array([1., 0.50])))
+ assert not (fn(1.0, False, np.array([0.5, 0.5]),
+ 1.0, False, np.array([1.0, 0.4])))
+
+ def test_constraint_wrapper(self):
+ lb = np.array([0, 20, 30])
+ ub = np.array([0.5, np.inf, 70])
+ x0 = np.array([1, 2, 3])
+ pc = _ConstraintWrapper(Bounds(lb, ub), x0)
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([0.25, 21, 31]) == 0).all()
+
+ # check vectorized Bounds constraint
+ xs = np.arange(1, 16).reshape(5, 3)
+ violations = []
+ for x in xs:
+ violations.append(pc.violation(x))
+ np.testing.assert_allclose(pc.violation(xs.T), np.array(violations).T)
+
+ x0 = np.array([1, 2, 3, 4])
+ A = np.array([[1, 2, 3, 4], [5, 0, 0, 6], [7, 0, 8, 0]])
+ pc = _ConstraintWrapper(LinearConstraint(A, -np.inf, 0), x0)
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ # check vectorized LinearConstraint, for 7 lots of parameter vectors
+ # with each parameter vector being 4 long, with 3 constraints
+ # xs is the same shape as stored in the differential evolution
+ # population, but it's sent to the violation function as (len(x), M)
+ xs = np.arange(1, 29).reshape(7, 4)
+ violations = []
+ for x in xs:
+ violations.append(pc.violation(x))
+ np.testing.assert_allclose(pc.violation(xs.T), np.array(violations).T)
+
+ pc = _ConstraintWrapper(LinearConstraint(csr_array(A), -np.inf, 0),
+ x0)
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ def fun(x):
+ return A.dot(x)
+
+ nonlinear = NonlinearConstraint(fun, -np.inf, 0)
+ pc = _ConstraintWrapper(nonlinear, [-10, 2, -10, 4])
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ def test_constraint_wrapper_violation(self):
+ def cons_f(x):
+ # written in vectorised form to accept an array of (N, S)
+ # returning (M, S)
+ # where N is the number of parameters,
+ # S is the number of solution vectors to be examined,
+ # and M is the number of constraint components
+ return np.array([x[0] ** 2 + x[1],
+ x[0] ** 2 - x[1]])
+
+ nlc = NonlinearConstraint(cons_f, [-1, -0.8500], [2, 2])
+ pc = _ConstraintWrapper(nlc, [0.5, 1])
+ assert np.size(pc.bounds[0]) == 2
+
+ xs = [(0.5, 1), (0.5, 1.2), (1.2, 1.2), (0.1, -1.2), (0.1, 2.0)]
+ vs = [(0, 0), (0, 0.1), (0.64, 0), (0.19, 0), (0.01, 1.14)]
+
+ for x, v in zip(xs, vs):
+ assert_allclose(pc.violation(x), v)
+
+ # now check that we can vectorize the constraint wrapper
+ assert_allclose(pc.violation(np.array(xs).T),
+ np.array(vs).T)
+ assert pc.fun(np.array(xs).T).shape == (2, len(xs))
+ assert pc.violation(np.array(xs).T).shape == (2, len(xs))
+ assert pc.num_constr == 2
+ assert pc.parameter_count == 2
+
+ def test_matrix_linear_constraint(self):
+ # gh20041 supplying an np.matrix to construct a LinearConstraint caused
+ # _ConstraintWrapper to start returning constraint violations of the
+ # wrong shape.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", PendingDeprecationWarning)
+ matrix = np.matrix([[1, 1, 1, 1.],
+ [2, 2, 2, 2.]])
+ lc = LinearConstraint(matrix, 0, 1)
+ x0 = np.ones(4)
+ cw = _ConstraintWrapper(lc, x0)
+ # the shape of the constraint violation should be the same as the number
+ # of constraints applied.
+ assert cw.violation(x0).shape == (2,)
+
+ # let's try a vectorised violation call.
+ xtrial = np.arange(4 * 5).reshape(4, 5)
+ assert cw.violation(xtrial).shape == (2, 5)
+
+ @pytest.mark.fail_slow(20)
+ def test_L1(self):
+ # Lampinen ([5]) test problem 1
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = np.sum(5*x[1:5]) - 5*x[1:5]@x[1:5] - np.sum(x[5:])
+ return fun
+
+ A = np.zeros((10, 14)) # 1-indexed to match reference
+ A[1, [1, 2, 10, 11]] = 2, 2, 1, 1
+ A[2, [1, 10]] = -8, 1
+ A[3, [4, 5, 10]] = -2, -1, 1
+ A[4, [1, 3, 10, 11]] = 2, 2, 1, 1
+ A[5, [2, 11]] = -8, 1
+ A[6, [6, 7, 11]] = -2, -1, 1
+ A[7, [2, 3, 11, 12]] = 2, 2, 1, 1
+ A[8, [3, 12]] = -8, 1
+ A[9, [8, 9, 12]] = -2, -1, 1
+ A = A[1:, 1:]
+
+ b = np.array([10, 0, 0, 10, 0, 0, 10, 0, 0])
+
+ L = LinearConstraint(A, -np.inf, b)
+
+ bounds = [(0, 1)]*9 + [(0, 100)]*3 + [(0, 1)]
+
+ # using a lower popsize to speed the test up
+ rng = np.random.default_rng(np.random.MT19937(12345))
+ res = differential_evolution(
+ f, bounds, strategy='best1bin', rng=rng, constraints=(L,),
+ popsize=5, tol=0.01
+ )
+
+ x_opt = (1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1)
+ f_opt = -15
+
+ assert_allclose(f(x_opt), f_opt, atol=6e-4)
+ assert res.success
+ assert_allclose(res.x, x_opt, atol=6e-4)
+ assert_allclose(res.fun, f_opt, atol=5e-3)
+ assert_(np.all(A@res.x <= b))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ # now repeat the same solve, using the same overall constraints,
+ # but using a sparse array for the LinearConstraint instead of an
+ # array
+
+ L = LinearConstraint(csr_array(A), -np.inf, b)
+
+ # using a lower popsize to speed the test up
+ rng = np.random.default_rng(np.random.MT19937(12345))
+ res = differential_evolution(
+ f, bounds, strategy='best1bin', rng=rng, constraints=(L,),
+ popsize=5, tol=0.01
+ )
+
+ assert_allclose(f(x_opt), f_opt)
+ assert res.success
+ assert_allclose(res.x, x_opt, atol=5e-4)
+ assert_allclose(res.fun, f_opt, atol=5e-3)
+ assert_(np.all(A@res.x <= b))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ # now repeat the same solve, using the same overall constraints,
+ # but specify half the constraints in terms of LinearConstraint,
+ # and the other half by NonlinearConstraint
+ def c1(x):
+ x = np.hstack(([0], x))
+ return [2*x[2] + 2*x[3] + x[11] + x[12],
+ -8*x[3] + x[12]]
+
+ def c2(x):
+ x = np.hstack(([0], x))
+ return -2*x[8] - x[9] + x[12]
+
+ L = LinearConstraint(A[:5, :], -np.inf, b[:5])
+ L2 = LinearConstraint(A[5:6, :], -np.inf, b[5:6])
+ N = NonlinearConstraint(c1, -np.inf, b[6:8])
+ N2 = NonlinearConstraint(c2, -np.inf, b[8:9])
+ constraints = (L, N, L2, N2)
+
+ with warnings.catch_warnings():
+ rng = np.random.default_rng(np.random.MT19937(12345))
+ warnings.simplefilter("ignore", UserWarning)
+ res = differential_evolution(
+ f, bounds, strategy='best1bin', rng=rng,
+ constraints=constraints, popsize=5, tol=0.05
+ )
+
+ assert_allclose(res.x, x_opt, atol=6e-4)
+ assert_allclose(res.fun, f_opt, atol=5e-3)
+ assert_(np.all(A@res.x <= b))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L2(self):
+ # Lampinen ([5]) test problem 2
+ rng = np.random.default_rng(111121332)
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = ((x[1]-10)**2 + 5*(x[2]-12)**2 + x[3]**4 + 3*(x[4]-11)**2 +
+ 10*x[5]**6 + 7*x[6]**2 + x[7]**4 - 4*x[6]*x[7] - 10*x[6] -
+ 8*x[7])
+ return fun
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [127 - 2*x[1]**2 - 3*x[2]**4 - x[3] - 4*x[4]**2 - 5*x[5],
+ 196 - 23*x[1] - x[2]**2 - 6*x[6]**2 + 8*x[7],
+ 282 - 7*x[1] - 3*x[2] - 10*x[3]**2 - x[4] + x[5],
+ -4*x[1]**2 - x[2]**2 + 3*x[1]*x[2] - 2*x[3]**2 -
+ 5*x[6] + 11*x[7]]
+
+ N = NonlinearConstraint(c1, 0, np.inf)
+ bounds = [(-10, 10)]*7
+ constraints = (N)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ res = differential_evolution(f, bounds, strategy='best1bin',
+ rng=rng, constraints=constraints)
+
+ f_opt = 680.6300599487869
+ x_opt = (2.330499, 1.951372, -0.4775414, 4.365726,
+ -0.6244870, 1.038131, 1.594227)
+
+ assert_allclose(f(x_opt), f_opt)
+ assert_allclose(res.fun, f_opt)
+ assert_allclose(res.x, x_opt, atol=1e-5)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L3(self):
+ # Lampinen ([5]) test problem 3
+ rng = np.random.default_rng(1234520312198)
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (x[1]**2 + x[2]**2 + x[1]*x[2] - 14*x[1] - 16*x[2] +
+ (x[3]-10)**2 + 4*(x[4]-5)**2 + (x[5]-3)**2 + 2*(x[6]-1)**2 +
+ 5*x[7]**2 + 7*(x[8]-11)**2 + 2*(x[9]-10)**2 +
+ (x[10] - 7)**2 + 45
+ )
+ return fun # maximize
+
+ A = np.zeros((4, 11))
+ A[1, [1, 2, 7, 8]] = -4, -5, 3, -9
+ A[2, [1, 2, 7, 8]] = -10, 8, 17, -2
+ A[3, [1, 2, 9, 10]] = 8, -2, -5, 2
+ A = A[1:, 1:]
+ b = np.array([-105, 0, -12])
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [3*x[1] - 6*x[2] - 12*(x[9]-8)**2 + 7*x[10],
+ -3*(x[1]-2)**2 - 4*(x[2]-3)**2 - 2*x[3]**2 + 7*x[4] + 120,
+ -x[1]**2 - 2*(x[2]-2)**2 + 2*x[1]*x[2] - 14*x[5] + 6*x[6],
+ -5*x[1]**2 - 8*x[2] - (x[3]-6)**2 + 2*x[4] + 40,
+ -0.5*(x[1]-8)**2 - 2*(x[2]-4)**2 - 3*x[5]**2 + x[6] + 30]
+
+ L = LinearConstraint(A, b, np.inf)
+ N = NonlinearConstraint(c1, 0, np.inf)
+ bounds = [(-10, 10)]*10
+ constraints = (L, N)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ res = differential_evolution(f, bounds, rng=rng,
+ constraints=constraints, popsize=3)
+
+ x_opt = (2.171996, 2.363683, 8.773926, 5.095984, 0.9906548,
+ 1.430574, 1.321644, 9.828726, 8.280092, 8.375927)
+ f_opt = 24.3062091
+
+ assert_allclose(f(x_opt), f_opt, atol=1e-5)
+ assert_allclose(res.x, x_opt, atol=1e-6)
+ assert_allclose(res.fun, f_opt, atol=1e-5)
+ assert res.success
+ assert_(np.all(A @ res.x >= b))
+ assert_(np.all(np.array(c1(res.x)) >= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ # test_L4 was remove for flakiness due to numerical instability (gh24549)
+
+ @pytest.mark.fail_slow(10)
+ def test_L5(self):
+ # Lampinen ([5]) test problem 5
+ rng = np.random.default_rng(209331234)
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (np.sin(2*np.pi*x[1])**3*np.sin(2*np.pi*x[2]) /
+ (x[1]**3*(x[1]+x[2])))
+ return -fun # maximize
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [x[1]**2 - x[2] + 1,
+ 1 - x[1] + (x[2]-4)**2]
+
+ N = NonlinearConstraint(c1, -np.inf, 0)
+ bounds = [(0, 10)]*2
+ constraints = (N)
+
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=rng,
+ constraints=constraints)
+
+ x_opt = (1.22797135, 4.24537337)
+ f_opt = -0.095825
+ assert_allclose(f(x_opt), f_opt, atol=2e-5)
+ assert_allclose(res.fun, f_opt, atol=1e-4)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) <= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L6(self):
+ # Lampinen ([5]) test problem 6
+ rng = np.random.default_rng(209331234)
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (x[1]-10)**3 + (x[2] - 20)**3
+ return fun
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [(x[1]-5)**2 + (x[2] - 5)**2 - 100,
+ -(x[1]-6)**2 - (x[2] - 5)**2 + 82.81]
+
+ N = NonlinearConstraint(c1, 0, np.inf)
+ bounds = [(13, 100), (0, 100)]
+ constraints = (N)
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=rng,
+ constraints=constraints, tol=1e-7)
+ x_opt = (14.095, 0.84296)
+ f_opt = -6961.814744
+
+ assert_allclose(f(x_opt), f_opt, atol=1e-6)
+ assert_allclose(res.fun, f_opt, atol=0.001)
+ assert_allclose(res.x, x_opt, atol=1e-4)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ def test_L7(self):
+ # Lampinen ([5]) test problem 7
+ rng = np.random.default_rng(209331234)
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (5.3578547*x[3]**2 + 0.8356891*x[1]*x[5] +
+ 37.293239*x[1] - 40792.141)
+ return fun
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [
+ 85.334407 + 0.0056858*x[2]*x[5] + 0.0006262*x[1]*x[4] -
+ 0.0022053*x[3]*x[5],
+
+ 80.51249 + 0.0071317*x[2]*x[5] + 0.0029955*x[1]*x[2] +
+ 0.0021813*x[3]**2,
+
+ 9.300961 + 0.0047026*x[3]*x[5] + 0.0012547*x[1]*x[3] +
+ 0.0019085*x[3]*x[4]
+ ]
+
+ N = NonlinearConstraint(c1, [0, 90, 20], [92, 110, 25])
+
+ bounds = [(78, 102), (33, 45)] + [(27, 45)]*3
+ constraints = (N)
+
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=rng,
+ constraints=constraints)
+
+ # using our best solution, rather than Lampinen/Koziel. Koziel solution
+ # doesn't satisfy constraints, Lampinen f_opt just plain wrong.
+ x_opt = [78.00000686, 33.00000362, 29.99526064, 44.99999971,
+ 36.77579979]
+
+ f_opt = -30665.537578
+
+ assert_allclose(f(x_opt), f_opt)
+ assert_allclose(res.x, x_opt, atol=1e-3)
+ assert_allclose(res.fun, f_opt, atol=1e-3)
+
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= np.array([0, 90, 20])))
+ assert_(np.all(np.array(c1(res.x)) <= np.array([92, 110, 25])))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.xslow
+ @pytest.mark.xfail(platform.machine() == 'ppc64le',
+ reason="fails on ppc64le")
+ def test_L8(self):
+ rng = np.random.default_rng(209331234)
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = 3*x[1] + 0.000001*x[1]**3 + 2*x[2] + 0.000002/3*x[2]**3
+ return fun
+
+ A = np.zeros((3, 5))
+ A[1, [4, 3]] = 1, -1
+ A[2, [3, 4]] = 1, -1
+ A = A[1:, 1:]
+ b = np.array([-.55, -.55])
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [
+ 1000*np.sin(-x[3]-0.25) + 1000*np.sin(-x[4]-0.25) +
+ 894.8 - x[1],
+ 1000*np.sin(x[3]-0.25) + 1000*np.sin(x[3]-x[4]-0.25) +
+ 894.8 - x[2],
+ 1000*np.sin(x[4]-0.25) + 1000*np.sin(x[4]-x[3]-0.25) +
+ 1294.8
+ ]
+ L = LinearConstraint(A, b, np.inf)
+ N = NonlinearConstraint(c1, np.full(3, -0.001), np.full(3, 0.001))
+
+ bounds = [(0, 1200)]*2+[(-.55, .55)]*2
+ constraints = (L, N)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ # original Lampinen test was with rand1bin, but that takes a
+ # huge amount of CPU time. Changing strategy to best1bin speeds
+ # things up a lot
+ res = differential_evolution(f, bounds, strategy='best1bin',
+ rng=rng, constraints=constraints,
+ maxiter=5000)
+
+ x_opt = (679.9453, 1026.067, 0.1188764, -0.3962336)
+ f_opt = 5126.4981
+
+ assert_allclose(f(x_opt), f_opt, atol=1e-3)
+ assert_allclose(res.x[:2], x_opt[:2], atol=2e-3)
+ assert_allclose(res.x[2:], x_opt[2:], atol=2e-3)
+ assert_allclose(res.fun, f_opt, atol=2e-2)
+ assert res.success
+ assert_(np.all(A@res.x >= b))
+ assert_(np.all(np.array(c1(res.x)) >= -0.001))
+ assert_(np.all(np.array(c1(res.x)) <= 0.001))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(5)
+ def test_L9(self):
+ # Lampinen ([5]) test problem 9
+ rng = np.random.default_rng(209331234)
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return x[1]**2 + (x[2]-1)**2
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [x[2] - x[1]**2]
+
+ N = NonlinearConstraint(c1, [-.001], [0.001])
+
+ bounds = [(-1, 1)]*2
+ constraints = (N)
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=rng,
+ constraints=constraints)
+
+ x_opt = [np.sqrt(2)/2, 0.5]
+ f_opt = 0.75
+
+ assert_allclose(f(x_opt), f_opt)
+ assert_allclose(np.abs(res.x), x_opt, atol=1e-3)
+ assert_allclose(res.fun, f_opt, atol=1e-3)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= -0.001))
+ assert_(np.all(np.array(c1(res.x)) <= 0.001))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_integrality(self):
+ # test fitting discrete distribution to data
+ rng = np.random.default_rng(6519843218105)
+ dist = stats.nbinom
+ shapes = (5, 0.5)
+ x = dist.rvs(*shapes, size=10000, random_state=rng)
+
+ def func(p, *args):
+ dist, x = args
+ # negative log-likelihood function
+ ll = -np.log(dist.pmf(x, *p)).sum(axis=-1)
+ if np.isnan(ll): # occurs when x is outside of support
+ ll = np.inf # we don't want that
+ return ll
+
+ integrality = [True, False]
+ bounds = [(1, 18), (0, 0.95)]
+
+ res = differential_evolution(func, bounds, args=(dist, x),
+ integrality=integrality, polish=False,
+ rng=rng)
+ # tolerance has to be fairly relaxed for the second parameter
+ # because we're fitting a distribution to random variates.
+ assert res.x[0] == 5
+ assert_allclose(res.x, shapes, rtol=0.025)
+
+ # check that we can still use integrality constraints with polishing
+ res2 = differential_evolution(func, bounds, args=(dist, x),
+ integrality=integrality, polish=True,
+ rng=rng)
+
+ def func2(p, *args):
+ n, dist, x = args
+ return func(np.array([n, p[0]]), dist, x)
+
+ # compare the DE derived solution to an LBFGSB solution (that doesn't
+ # have to find the integral values). Note we're setting x0 to be the
+ # output from the first DE result, thereby making the polishing step
+ # and this minimisation pretty much equivalent.
+ LBFGSB = minimize(func2, res2.x[1], args=(5, dist, x),
+ bounds=[(0, 0.95)])
+ assert_allclose(res2.x[1], LBFGSB.x)
+ assert res2.fun <= res.fun
+
+ def test_integrality_limits(self):
+ def f(x):
+ return x
+
+ integrality = [True, False, True]
+ bounds = [(0.2, 1.1), (0.9, 2.2), (3.3, 4.9)]
+
+ # no integrality constraints
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=False)
+ assert_allclose(solver.limits[0], [0.2, 0.9, 3.3])
+ assert_allclose(solver.limits[1], [1.1, 2.2, 4.9])
+
+ # with integrality constraints
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+ assert_allclose(solver.limits[0], [0.5, 0.9, 3.5])
+ assert_allclose(solver.limits[1], [1.5, 2.2, 4.5])
+ assert_equal(solver.integrality, [True, False, True])
+ assert solver.polish is False
+
+ bounds = [(-1.2, -0.9), (0.9, 2.2), (-10.3, 4.1)]
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+ assert_allclose(solver.limits[0], [-1.5, 0.9, -10.5])
+ assert_allclose(solver.limits[1], [-0.5, 2.2, 4.5])
+
+ # A lower bound of -1.2 is converted to
+ # np.nextafter(np.ceil(-1.2) - 0.5, np.inf)
+ # with a similar process to the upper bound. Check that the
+ # conversions work
+ assert_allclose(np.round(solver.limits[0]), [-1.0, 1.0, -10.0])
+ assert_allclose(np.round(solver.limits[1]), [-1.0, 2.0, 4.0])
+
+ bounds = [(-10.2, -8.1), (0.9, 2.2), (-10.9, -9.9999)]
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+ assert_allclose(solver.limits[0], [-10.5, 0.9, -10.5])
+ assert_allclose(solver.limits[1], [-8.5, 2.2, -9.5])
+
+ bounds = [(-10.2, -10.1), (0.9, 2.2), (-10.9, -9.9999)]
+ with pytest.raises(ValueError, match='One of the integrality'):
+ DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+
+ @pytest.mark.fail_slow(10)
+ def test_vectorized(self):
+ def quadratic(x):
+ return np.sum(x**2)
+
+ def quadratic_vec(x):
+ return np.sum(x**2, axis=0)
+
+ # A vectorized function needs to accept (len(x), S) and return (S,)
+ with pytest.raises(RuntimeError, match='The vectorized function'):
+ differential_evolution(quadratic, self.bounds,
+ vectorized=True, updating='deferred')
+
+ # vectorized overrides the updating keyword, check for warning
+ with warns(UserWarning, match="differential_evolution: the 'vector"):
+ differential_evolution(quadratic_vec, self.bounds,
+ vectorized=True)
+
+ # vectorized defers to the workers keyword, check for warning
+ with warns(UserWarning, match="differential_evolution: the 'workers"):
+ differential_evolution(quadratic_vec, self.bounds,
+ vectorized=True, workers=map,
+ updating='deferred')
+
+ ncalls = [0]
+
+ def rosen_vec(x):
+ ncalls[0] += 1
+ return rosen(x)
+
+ bounds = [(0, 10), (0, 10)]
+ rng = np.random.default_rng(209331234)
+ res1 = differential_evolution(rosen, bounds, updating='deferred',
+ rng=rng)
+ rng = np.random.default_rng(209331234)
+ res2 = differential_evolution(rosen_vec, bounds, vectorized=True,
+ updating='deferred', rng=rng)
+
+ # the two minimisation runs should be functionally equivalent
+ assert_allclose(res1.x, res2.x)
+ assert ncalls[0] == res2.nfev
+ assert res1.nit == res2.nit
+
+ def test_vectorized_constraints(self):
+ def constr_f(x):
+ return np.array([x[0] + x[1]])
+
+ def constr_f2(x):
+ return np.array([x[0]**2 + x[1], x[0] - x[1]])
+
+ nlc1 = NonlinearConstraint(constr_f, -np.inf, 1.9)
+ nlc2 = NonlinearConstraint(constr_f2, (0.9, 0.5), (2.0, 2.0))
+
+ def rosen_vec(x):
+ # accept an (len(x0), S) array, returning a (S,) array
+ v = 100 * (x[1:] - x[:-1]**2.0)**2.0
+ v += (1 - x[:-1])**2.0
+ return np.squeeze(v)
+
+ bounds = [(0, 10), (0, 10)]
+
+ rng = np.random.default_rng(209331234)
+ res1 = differential_evolution(rosen, bounds, updating='deferred',
+ rng=rng, constraints=[nlc1, nlc2],
+ polish=False)
+ rng = np.random.default_rng(209331234)
+ res2 = differential_evolution(rosen_vec, bounds, vectorized=True,
+ updating='deferred', rng=rng,
+ constraints=[nlc1, nlc2],
+ polish=False)
+ # the two minimisation runs should be functionally equivalent
+ assert_allclose(res1.x, res2.x)
+
+ def test_polish_function(self):
+ # the polishing may be done by a callable
+ N = len(self.bounds)
+
+ def pf(fun, x, **kwds):
+ pf.res = minimize(fun, x, jac=rosen_der, method='trust-constr', **kwds)
+ return pf.res
+ pf.res = None
+
+ rng = np.random.default_rng(209331234)
+ res = differential_evolution(
+ rosen, self.bounds, polish=pf, maxiter=1, rng=rng
+ )
+ rng = np.random.default_rng(209331234)
+ ref = differential_evolution(
+ rosen, self.bounds, polish=True, maxiter=1, rng=rng
+ )
+
+ # res.success will be False because of the small number of iterations
+ # The solution produced by DE would be bad after only one iteration.
+ # However, we still expect a good answer if the polishing worked
+ assert res.jac is not None
+ assert_allclose(res.x, np.ones(N), atol=1e-6)
+ # test that the `pf` callable is really used; it's not just truthy
+ assert res.fun == pf.res.fun
+ assert ref.fun != res.fun
+
+ def dummy_pf(func, x, **kwds):
+ assert "bounds" in kwds
+ assert isinstance(kwds["bounds"], Bounds)
+ assert "constraints" in kwds
+ return np.ones(N)
+
+ with assert_raises(
+ ValueError,
+ match="The result from a user defined polishing"
+ ):
+ differential_evolution(
+ rosen,
+ self.bounds,
+ polish=dummy_pf,
+ maxiter=1
+ )
+
+ # check that output of polish==False followed by a manual polish
+ # is the same as a callable(polish). Limit maxiter on DE so polisher
+ # has to do all the work.
+ def pf(func, x, **kwds):
+ return minimize(func, x, method='L-BFGS-B', **kwds)
+
+ rng = np.random.default_rng(110980928209)
+ res = differential_evolution(
+ rosen, self.bounds, polish=False, rng=rng, maxiter=1
+ )
+ res = minimize(rosen, res.x, bounds=self.bounds, method='L-BFGS-B')
+ rng = np.random.default_rng(110980928209)
+ res2 = differential_evolution(
+ rosen, self.bounds, polish=pf, rng=rng, maxiter=1
+ )
+ # could possibly do assert_allequal, but not sure about bitwise exactness
+ # for repeated runs from same starting point
+ assert_allclose(res.x, res2.x)
+ assert_allclose(res.fun, res2.fun)
+
+ def test_constraint_violation_error_message(self):
+ rng = np.random.default_rng(209331234)
+
+ def func(x):
+ return np.cos(x[0]) + np.sin(x[1])
+
+ # Intentionally infeasible constraints.
+ c0 = NonlinearConstraint(lambda x: x[1] - (x[0]-1)**2, 0, np.inf)
+ c1 = NonlinearConstraint(lambda x: x[1] + x[0]**2, -np.inf, 0)
+
+ result = differential_evolution(func,
+ bounds=[(-1, 2), (-1, 1)],
+ constraints=[c0, c1],
+ maxiter=10,
+ polish=False,
+ rng=rng)
+ assert result.success is False
+ # The numerical value in the error message might be sensitive to
+ # changes in the implementation. It can be updated if the code is
+ # changed. The essential part of the test is that there is a number
+ # after the '=', so if necessary, the text could be reduced to, say,
+ # "MAXCV = 0.".
+ assert "MAXCV = 0." in result.message
+
+ @pytest.mark.fail_slow(20) # fail-slow exception by request - see gh-20806
+ def test_strategy_fn(self):
+ rng = np.random.default_rng(209331234)
+
+ # examines ability to customize strategy by mimicking one of the
+ # in-built strategies
+ parameter_count = 4
+ popsize = 10
+ bounds = [(0, 10.)] * parameter_count
+ total_popsize = parameter_count * popsize
+ mutation = 0.8
+ recombination = 0.7
+
+ calls = [0]
+ def custom_strategy_fn(candidate, population, rng=None):
+ calls[0] += 1
+ trial = np.copy(population[candidate])
+ fill_point = rng.choice(parameter_count)
+
+ pool = np.arange(total_popsize)
+ rng.shuffle(pool)
+ idxs = pool[:2 + 1]
+ idxs = idxs[idxs != candidate][:2]
+
+ r0, r1 = idxs[:2]
+
+ bprime = (population[0] + mutation *
+ (population[r0] - population[r1]))
+
+ crossovers = rng.uniform(size=parameter_count)
+ crossovers = crossovers < recombination
+ crossovers[fill_point] = True
+ trial = np.where(crossovers, bprime, trial)
+ return trial
+
+ solver = DifferentialEvolutionSolver(
+ rosen,
+ bounds,
+ popsize=popsize,
+ recombination=recombination,
+ mutation=mutation,
+ maxiter=2,
+ strategy=custom_strategy_fn,
+ rng=rng,
+ polish=False
+ )
+ assert solver.strategy is custom_strategy_fn
+ solver.solve()
+ assert calls[0] > 0
+
+ # check custom strategy works with updating='deferred'
+ rng = np.random.default_rng(209331234)
+ res = differential_evolution(
+ rosen, bounds, strategy=custom_strategy_fn, updating='deferred', rng=rng
+ )
+ assert res.success
+
+ def custom_strategy_fn(candidate, population, rng=None):
+ return np.array([1.0, 2.0])
+
+ with pytest.raises(RuntimeError, match="strategy*"):
+ differential_evolution(
+ rosen,
+ bounds,
+ strategy=custom_strategy_fn
+ )
+
+ def test_reference_cycles(self):
+ with assert_deallocated(DifferentialEvolutionSolver, rosen, [(0, 10)]*2):
+ pass
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__dual_annealing.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..931f497361edd6bd5edc2914a05ccc5da468f40b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__dual_annealing.py
@@ -0,0 +1,415 @@
+# Dual annealing unit tests implementation.
+# Copyright (c) 2018 Sylvain Gubian ,
+# Yang Xiang
+# Author: Sylvain Gubian, PMP S.A.
+"""
+Unit tests for the dual annealing global optimizer
+"""
+from scipy.optimize import dual_annealing, Bounds
+
+from scipy.optimize._dual_annealing import EnergyState
+from scipy.optimize._dual_annealing import LocalSearchWrapper
+from scipy.optimize._dual_annealing import ObjectiveFunWrapper
+from scipy.optimize._dual_annealing import StrategyChain
+from scipy.optimize._dual_annealing import VisitingDistribution
+from scipy.optimize import rosen, rosen_der
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose, assert_array_less
+from pytest import raises as assert_raises
+from scipy._lib._util import check_random_state
+
+import threading
+
+
+class TestDualAnnealing:
+
+ def setup_method(self):
+ # A function that returns always infinity for initialization tests
+ self.weirdfunc = lambda x: np.inf
+ # 2-D bounds for testing function
+ self.ld_bounds = [(-5.12, 5.12)] * 2
+ # 4-D bounds for testing function
+ self.hd_bounds = self.ld_bounds * 4
+ # Number of values to be generated for testing visit function
+ self.nbtestvalues = 5000
+ self.high_temperature = 5230
+ self.low_temperature = 0.1
+ self.qv = 2.62
+ self.seed = 1234
+ self.nb_fun_call = threading.local()
+ self.ngev = threading.local()
+
+ def callback(self, x, f, context):
+ # For testing callback mechanism. Should stop for e <= 1 as
+ # the callback function returns True
+ if f <= 1.0:
+ return True
+
+ def func(self, x, args=()):
+ # Using Rastrigin function for performing tests
+ if args:
+ shift = args
+ else:
+ shift = 0
+ y = np.sum((x - shift) ** 2 - 10 * np.cos(2 * np.pi * (
+ x - shift))) + 10 * np.size(x) + shift
+ if not hasattr(self.nb_fun_call, 'c'):
+ self.nb_fun_call.c = 0
+ self.nb_fun_call.c += 1
+ return y
+
+ def rosen_der_wrapper(self, x, args=()):
+ if not hasattr(self.ngev, 'c'):
+ self.ngev.c = 0
+ self.ngev.c += 1
+ return rosen_der(x, *args)
+
+ # FIXME: there are some discontinuities in behaviour as a function of `qv`,
+ # this needs investigating - see gh-12384
+ @pytest.mark.parametrize('qv', [1.1, 1.41, 2, 2.62, 2.9])
+ def test_visiting_stepping(self, qv):
+ rng = np.random.default_rng(1234)
+ lu = list(zip(*self.ld_bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ dim = lower.size
+ vd = VisitingDistribution(lower, upper, qv, rng)
+ values = np.zeros(dim)
+ x_step_low = vd.visiting(values, 0, self.high_temperature)
+ # Make sure that only the first component is changed
+ assert_equal(np.not_equal(x_step_low, 0), True)
+ values = np.zeros(dim)
+ x_step_high = vd.visiting(values, dim, self.high_temperature)
+ # Make sure that component other than at dim has changed
+ assert_equal(np.not_equal(x_step_high[0], 0), True)
+
+ @pytest.mark.parametrize('qv', [2.25, 2.62, 2.9])
+ def test_visiting_dist_high_temperature(self, qv):
+ rng = np.random.default_rng(1234)
+ lu = list(zip(*self.ld_bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ vd = VisitingDistribution(lower, upper, qv, rng)
+ # values = np.zeros(self.nbtestvalues)
+ # for i in np.arange(self.nbtestvalues):
+ # values[i] = vd.visit_fn(self.high_temperature)
+ values = vd.visit_fn(self.high_temperature, self.nbtestvalues)
+
+ # Visiting distribution is a distorted version of Cauchy-Lorentz
+ # distribution, and as no 1st and higher moments (no mean defined,
+ # no variance defined).
+ # Check that big tails values are generated
+ assert_array_less(np.min(values), 1e-10)
+ assert_array_less(1e+10, np.max(values))
+
+ def test_reset(self):
+ owf = ObjectiveFunWrapper(self.weirdfunc)
+ lu = list(zip(*self.ld_bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ es = EnergyState(lower, upper)
+ assert_raises(ValueError, es.reset, owf, check_random_state(None))
+
+ def test_low_dim(self):
+ ret = dual_annealing(
+ self.func, self.ld_bounds, rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=1e-12)
+ assert ret.success
+
+ @pytest.mark.fail_slow(10)
+ def test_high_dim(self):
+ ret = dual_annealing(self.func, self.hd_bounds, rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=1e-12)
+ assert ret.success
+
+ def test_low_dim_no_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ no_local_search=True, seed=self.seed)
+ assert_allclose(ret.fun, 0., atol=1e-4)
+
+ @pytest.mark.fail_slow(10)
+ def test_high_dim_no_ls(self):
+ ret = dual_annealing(self.func, self.hd_bounds,
+ no_local_search=True, rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=1.2e-4)
+
+ def test_nb_fun_call(self):
+ self.nb_fun_call.c = 0
+ ret = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ assert_equal(self.nb_fun_call.c, ret.nfev)
+
+ def test_nb_fun_call_no_ls(self):
+ self.nb_fun_call.c = 0
+ ret = dual_annealing(self.func, self.ld_bounds,
+ no_local_search=True, rng=self.seed)
+ assert_equal(self.nb_fun_call.c, ret.nfev)
+
+ def test_max_reinit(self):
+ assert_raises(ValueError, dual_annealing, self.weirdfunc,
+ self.ld_bounds)
+
+ @pytest.mark.fail_slow(10)
+ def test_reproduce(self):
+ res1 = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ res2 = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ res3 = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ # If we have reproducible results, x components found has to
+ # be exactly the same, which is not the case with no seeding
+ assert_equal(res1.x, res2.x)
+ assert_equal(res1.x, res3.x)
+
+ def test_rand_gen(self):
+ # check that np.random.Generator can be used (numpy >= 1.17)
+ # obtain a np.random.Generator object
+ rng = np.random.default_rng(1)
+
+ res1 = dual_annealing(self.func, self.ld_bounds, rng=rng)
+ # seed again
+ rng = np.random.default_rng(1)
+ res2 = dual_annealing(self.func, self.ld_bounds, rng=rng)
+ # If we have reproducible results, x components found has to
+ # be exactly the same, which is not the case with no seeding
+ assert_equal(res1.x, res2.x)
+
+ def test_bounds_integrity(self):
+ wrong_bounds = [(-5.12, 5.12), (1, 0), (5.12, 5.12)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ wrong_bounds)
+
+ def test_bound_validity(self):
+ invalid_bounds = [(-5, 5), (-np.inf, 0), (-5, 5)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ invalid_bounds)
+ invalid_bounds = [(-5, 5), (0, np.inf), (-5, 5)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ invalid_bounds)
+ invalid_bounds = [(-5, 5), (0, np.nan), (-5, 5)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ invalid_bounds)
+
+ def test_deprecated_local_search_options_bounds(self):
+ def func(x):
+ return np.sum((x - 5) * (x - 1))
+ bounds = list(zip([-6, -5], [6, 5]))
+ # Test bounds can be passed (see gh-10831)
+
+ with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "):
+ dual_annealing(
+ func,
+ bounds=bounds,
+ minimizer_kwargs={"method": "CG", "bounds": bounds})
+
+ def test_minimizer_kwargs_bounds(self):
+ def func(x):
+ return np.sum((x - 5) * (x - 1))
+ bounds = list(zip([-6, -5], [6, 5]))
+ # Test bounds can be passed (see gh-10831)
+ dual_annealing(
+ func,
+ bounds=bounds,
+ minimizer_kwargs={"method": "SLSQP", "bounds": bounds})
+
+ with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "):
+ dual_annealing(
+ func,
+ bounds=bounds,
+ minimizer_kwargs={"method": "CG", "bounds": bounds})
+
+ def test_max_fun_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds, maxfun=100,
+ rng=self.seed)
+
+ ls_max_iter = min(max(
+ len(self.ld_bounds) * LocalSearchWrapper.LS_MAXITER_RATIO,
+ LocalSearchWrapper.LS_MAXITER_MIN),
+ LocalSearchWrapper.LS_MAXITER_MAX)
+ assert ret.nfev <= 100 + ls_max_iter
+ assert not ret.success
+
+ def test_max_fun_no_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ no_local_search=True, maxfun=500, rng=self.seed)
+ assert ret.nfev <= 500
+ assert not ret.success
+
+ def test_maxiter(self):
+ ret = dual_annealing(self.func, self.ld_bounds, maxiter=700,
+ rng=self.seed)
+ assert ret.nit <= 700
+
+ # Testing that args are passed correctly for dual_annealing
+ def test_fun_args_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ args=((3.14159,)), rng=self.seed)
+ assert_allclose(ret.fun, 3.14159, atol=1e-6)
+
+ # Testing that args are passed correctly for pure simulated annealing
+ def test_fun_args_no_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ args=((3.14159, )), no_local_search=True,
+ rng=self.seed)
+ assert_allclose(ret.fun, 3.14159, atol=1e-4)
+
+ def test_callback_stop(self):
+ # Testing that callback make the algorithm stop for
+ # fun value <= 1.0 (see callback method)
+ ret = dual_annealing(self.func, self.ld_bounds,
+ callback=self.callback, rng=self.seed)
+ assert ret.fun <= 1.0
+ assert 'stop early' in ret.message[0]
+ assert not ret.success
+
+ @pytest.mark.parametrize('method, atol', [
+ ('Nelder-Mead', 2e-5),
+ ('COBYLA', 1e-5),
+ ('COBYQA', 1e-8),
+ ('Powell', 1e-8),
+ ('CG', 1e-8),
+ ('BFGS', 1e-8),
+ ('TNC', 1e-8),
+ ('SLSQP', 2e-7),
+ ])
+ def test_multi_ls_minimizer(self, method, atol):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ minimizer_kwargs=dict(method=method),
+ rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=atol)
+
+ def test_wrong_restart_temp(self):
+ assert_raises(ValueError, dual_annealing, self.func,
+ self.ld_bounds, restart_temp_ratio=1)
+ assert_raises(ValueError, dual_annealing, self.func,
+ self.ld_bounds, restart_temp_ratio=0)
+
+ def test_gradient_gnev(self):
+ minimizer_opts = {
+ 'jac': self.rosen_der_wrapper,
+ }
+ ret = dual_annealing(rosen, self.ld_bounds,
+ minimizer_kwargs=minimizer_opts,
+ rng=self.seed)
+ assert ret.njev == self.ngev.c
+
+ @pytest.mark.fail_slow(10)
+ def test_from_docstring(self):
+ def func(x):
+ return np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x)
+ lw = [-5.12] * 10
+ up = [5.12] * 10
+ ret = dual_annealing(func, bounds=list(zip(lw, up)), rng=1234)
+ assert_allclose(ret.x,
+ [-4.26437714e-09, -3.91699361e-09, -1.86149218e-09,
+ -3.97165720e-09, -6.29151648e-09, -6.53145322e-09,
+ -3.93616815e-09, -6.55623025e-09, -6.05775280e-09,
+ -5.00668935e-09], atol=4e-8)
+ assert_allclose(ret.fun, 0.000000, atol=5e-13)
+
+ @pytest.mark.parametrize('new_e, temp_step, accepted, accept_rate', [
+ (0, 100, 1000, 1.0097587941791923),
+ (0, 2, 1000, 1.2599210498948732),
+ (10, 100, 878, 0.8786035869128718),
+ (10, 60, 695, 0.6812920690579612),
+ (2, 100, 990, 0.9897404249173424),
+ ])
+ def test_accept_reject_probabilistic(
+ self, new_e, temp_step, accepted, accept_rate):
+ # Test accepts unconditionally with e < current_energy and
+ # probabilistically with e > current_energy
+
+ rs = check_random_state(123)
+
+ count_accepted = 0
+ iterations = 1000
+
+ accept_param = -5
+ current_energy = 1
+ for _ in range(iterations):
+ energy_state = EnergyState(lower=None, upper=None)
+ # Set energy state with current_energy, any location.
+ energy_state.update_current(current_energy, [0])
+
+ chain = StrategyChain(
+ accept_param, None, None, None, rs, energy_state)
+ # Normally this is set in run()
+ chain.temperature_step = temp_step
+
+ # Check if update is accepted.
+ chain.accept_reject(j=1, e=new_e, x_visit=[2])
+ if energy_state.current_energy == new_e:
+ count_accepted += 1
+
+ assert count_accepted == accepted
+
+ # Check accept rate
+ pqv = 1 - (1 - accept_param) * (new_e - current_energy) / temp_step
+ rate = 0 if pqv <= 0 else np.exp(np.log(pqv) / (1 - accept_param))
+
+ assert_allclose(rate, accept_rate)
+
+ @pytest.mark.fail_slow(10)
+ def test_bounds_class(self):
+ # test that result does not depend on the bounds type
+ def func(x):
+ f = np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x)
+ return f
+ lw = [-5.12] * 5
+ up = [5.12] * 5
+
+ # Unbounded global minimum is all zeros. Most bounds below will force
+ # a DV away from unbounded minimum and be active at solution.
+ up[0] = -2.0
+ up[1] = -1.0
+ lw[3] = 1.0
+ lw[4] = 2.0
+
+ # run optimizations
+ bounds = Bounds(lw, up)
+ ret_bounds_class = dual_annealing(func, bounds=bounds, rng=1234)
+
+ bounds_old = list(zip(lw, up))
+ ret_bounds_list = dual_annealing(func, bounds=bounds_old, rng=1234)
+
+ # test that found minima, function evaluations and iterations match
+ assert_allclose(ret_bounds_class.x, ret_bounds_list.x, atol=1e-8)
+ assert_allclose(ret_bounds_class.x, np.arange(-2, 3), atol=1e-7)
+ assert_allclose(ret_bounds_list.fun, ret_bounds_class.fun, atol=1e-9)
+ assert ret_bounds_list.nfev == ret_bounds_class.nfev
+
+ @pytest.mark.fail_slow(10)
+ def test_callable_jac_hess_with_args_gh11052(self):
+ # dual_annealing used to fail when `jac` was callable and `args` were
+ # used; check that this is resolved. Example is from gh-11052.
+
+ # extended to hess as part of closing gh20614
+ rng = np.random.default_rng(94253637693657847462)
+ def f(x, power):
+ return np.sum(np.exp(x ** power))
+
+ def jac(x, power):
+ return np.exp(x ** power) * power * x ** (power - 1)
+
+ def hess(x, power):
+ # calculated using WolframAlpha as d^2/dx^2 e^(x^p)
+ return np.diag(
+ power * np.exp(x ** power) * x ** (power - 2) *
+ (power * x ** power + power - 1)
+ )
+
+ def hessp(x, p, power):
+ return hess(x, power) @ p
+
+ res1 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='L-BFGS-B'))
+ res2 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='L-BFGS-B',
+ jac=jac))
+ res3 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='newton-cg',
+ jac=jac, hess=hess))
+ res4 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='newton-cg',
+ jac=jac, hessp=hessp))
+ assert_allclose(res1.fun, res2.fun, rtol=1e-6)
+ assert_allclose(res3.fun, res2.fun, rtol=1e-6)
+ assert_allclose(res4.fun, res2.fun, rtol=1e-6)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1affff822e8abdb50ba1483b0f3f85eb1becdd6
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py
@@ -0,0 +1,320 @@
+"""
+Unit test for Linear Programming via Simplex Algorithm.
+"""
+import warnings
+
+from copy import deepcopy
+from datetime import date
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal
+from numpy.exceptions import VisibleDeprecationWarning
+from pytest import raises as assert_raises
+
+from scipy.optimize._linprog_util import _clean_inputs, _LPProblem
+
+
+def test_aliasing():
+ """
+ Test for ensuring that no objects referred to by `lp` attributes,
+ `c`, `A_ub`, `b_ub`, `A_eq`, `b_eq`, `bounds`, have been modified
+ by `_clean_inputs` as a side effect.
+ """
+ lp = _LPProblem(
+ c=1,
+ A_ub=[[1]],
+ b_ub=[1],
+ A_eq=[[1]],
+ b_eq=[1],
+ bounds=(-np.inf, np.inf)
+ )
+ lp_copy = deepcopy(lp)
+
+ _clean_inputs(lp)
+
+ assert_(lp.c == lp_copy.c, "c modified by _clean_inputs")
+ assert_(lp.A_ub == lp_copy.A_ub, "A_ub modified by _clean_inputs")
+ assert_(lp.b_ub == lp_copy.b_ub, "b_ub modified by _clean_inputs")
+ assert_(lp.A_eq == lp_copy.A_eq, "A_eq modified by _clean_inputs")
+ assert_(lp.b_eq == lp_copy.b_eq, "b_eq modified by _clean_inputs")
+ assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs")
+
+
+def test_aliasing2():
+ """
+ Similar purpose as `test_aliasing` above.
+ """
+ lp = _LPProblem(
+ c=np.array([1, 1]),
+ A_ub=np.array([[1, 1], [2, 2]]),
+ b_ub=np.array([[1], [1]]),
+ A_eq=np.array([[1, 1]]),
+ b_eq=np.array([1]),
+ bounds=[(-np.inf, np.inf), (None, 1)]
+ )
+ lp_copy = deepcopy(lp)
+
+ _clean_inputs(lp)
+
+ assert_allclose(lp.c, lp_copy.c, err_msg="c modified by _clean_inputs")
+ assert_allclose(lp.A_ub, lp_copy.A_ub, err_msg="A_ub modified by _clean_inputs")
+ assert_allclose(lp.b_ub, lp_copy.b_ub, err_msg="b_ub modified by _clean_inputs")
+ assert_allclose(lp.A_eq, lp_copy.A_eq, err_msg="A_eq modified by _clean_inputs")
+ assert_allclose(lp.b_eq, lp_copy.b_eq, err_msg="b_eq modified by _clean_inputs")
+ assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs")
+
+
+def test_missing_inputs():
+ c = [1, 2]
+ A_ub = np.array([[1, 1], [2, 2]])
+ b_ub = np.array([1, 1])
+ A_eq = np.array([[1, 1], [2, 2]])
+ b_eq = np.array([1, 1])
+
+ assert_raises(TypeError, _clean_inputs)
+ assert_raises(TypeError, _clean_inputs, _LPProblem(c=None))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub, b_ub=None))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_ub=b_ub))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=None, b_ub=b_ub))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq, b_eq=None))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_eq=b_eq))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=None, b_eq=b_eq))
+
+
+def test_too_many_dimensions():
+ cb = [1, 2, 3, 4]
+ rng = np.random.default_rng(1234)
+ A = rng.random((4, 4))
+ bad2D = [[1, 2], [3, 4]]
+ bad3D = rng.random((4, 4, 4))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=bad2D, A_ub=A, b_ub=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad3D, b_ub=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=A, b_ub=bad2D))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad3D, b_eq=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=A, b_eq=bad2D))
+
+
+def test_too_few_dimensions():
+ rng = np.random.default_rng(1234)
+ bad = rng.random((4, 4)).ravel()
+ cb = rng.random(4)
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad, b_ub=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad, b_eq=cb))
+
+
+def test_inconsistent_dimensions():
+ m = 2
+ n = 4
+ c = [1, 2, 3, 4]
+
+ rng = np.random.default_rng(122390)
+ Agood = rng.random((m, n))
+ Abad = rng.random((m, n + 1))
+ bgood = rng.random(m)
+ bbad = rng.random(m + 1)
+ boundsbad = [(0, 1)] * (n + 1)
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Abad, b_ub=bgood))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Agood, b_ub=bbad))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Abad, b_eq=bgood))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Agood, b_eq=bbad))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, bounds=boundsbad))
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Creating an ndarray from ragged", VisibleDeprecationWarning)
+ assert_raises(ValueError, _clean_inputs,
+ _LPProblem(c=c, bounds=[[1, 2], [2, 3], [3, 4], [4, 5, 6]]))
+
+
+def test_type_errors():
+ lp = _LPProblem(
+ c=[1, 2],
+ A_ub=np.array([[1, 1], [2, 2]]),
+ b_ub=np.array([1, 1]),
+ A_eq=np.array([[1, 1], [2, 2]]),
+ b_eq=np.array([1, 1]),
+ bounds=[(0, 1)]
+ )
+ bad = "hello"
+
+ assert_raises(TypeError, _clean_inputs, lp._replace(c=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(A_ub=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(b_ub=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(A_eq=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(b_eq=bad))
+
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=bad))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds="hi"))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=["hi"]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[("hi")]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, "")]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2), (1, "")]))
+ assert_raises(TypeError, _clean_inputs,
+ lp._replace(bounds=[(1, date(2020, 2, 29))]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[[[1, 2]]]))
+
+
+def test_non_finite_errors():
+ lp = _LPProblem(
+ c=[1, 2],
+ A_ub=np.array([[1, 1], [2, 2]]),
+ b_ub=np.array([1, 1]),
+ A_eq=np.array([[1, 1], [2, 2]]),
+ b_eq=np.array([1, 1]),
+ bounds=[(0, 1)]
+ )
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, None]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.inf, 0]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, -np.inf]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.nan, 0]))
+
+ assert_raises(ValueError, _clean_inputs, lp._replace(A_ub=[[1, 2], [None, 1]]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(b_ub=[np.inf, 1]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(A_eq=[[1, 2], [1, -np.inf]]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(b_eq=[1, np.nan]))
+
+
+def test__clean_inputs1():
+ lp = _LPProblem(
+ c=[1, 2],
+ A_ub=[[1, 1], [2, 2]],
+ b_ub=[1, 1],
+ A_eq=[[1, 1], [2, 2]],
+ b_eq=[1, 1],
+ bounds=None
+ )
+
+ lp_cleaned = _clean_inputs(lp)
+
+ assert_allclose(lp_cleaned.c, np.array(lp.c))
+ assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub))
+ assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub))
+ assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq))
+ assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq))
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ assert_(lp_cleaned.c.shape == (2,), "")
+ assert_(lp_cleaned.A_ub.shape == (2, 2), "")
+ assert_(lp_cleaned.b_ub.shape == (2,), "")
+ assert_(lp_cleaned.A_eq.shape == (2, 2), "")
+ assert_(lp_cleaned.b_eq.shape == (2,), "")
+
+
+def test__clean_inputs2():
+ lp = _LPProblem(
+ c=1,
+ A_ub=[[1]],
+ b_ub=1,
+ A_eq=[[1]],
+ b_eq=1,
+ bounds=(0, 1)
+ )
+
+ lp_cleaned = _clean_inputs(lp)
+
+ assert_allclose(lp_cleaned.c, np.array(lp.c))
+ assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub))
+ assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub))
+ assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq))
+ assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq))
+ assert_equal(lp_cleaned.bounds, [(0, 1)])
+
+ assert_(lp_cleaned.c.shape == (1,), "")
+ assert_(lp_cleaned.A_ub.shape == (1, 1), "")
+ assert_(lp_cleaned.b_ub.shape == (1,), "")
+ assert_(lp_cleaned.A_eq.shape == (1, 1), "")
+ assert_(lp_cleaned.b_eq.shape == (1,), "")
+
+
+def test__clean_inputs3():
+ rng = np.random.default_rng(1890908)
+ lp = _LPProblem(
+ c=[[1, 2]],
+ A_ub=rng.random((2, 2)),
+ b_ub=[[1], [2]],
+ A_eq=rng.random((2, 2)),
+ b_eq=[[1], [2]],
+ bounds=[(0, 1)]
+ )
+
+ lp_cleaned = _clean_inputs(lp)
+
+ assert_allclose(lp_cleaned.c, np.array([1, 2]))
+ assert_allclose(lp_cleaned.b_ub, np.array([1, 2]))
+ assert_allclose(lp_cleaned.b_eq, np.array([1, 2]))
+ assert_equal(lp_cleaned.bounds, [(0, 1)] * 2)
+
+ assert_(lp_cleaned.c.shape == (2,), "")
+ assert_(lp_cleaned.b_ub.shape == (2,), "")
+ assert_(lp_cleaned.b_eq.shape == (2,), "")
+
+
+def test_bad_bounds():
+ lp = _LPProblem(c=[1, 2])
+
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=(1, 2, 2)))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2, 2)]))
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Creating an ndarray from ragged", VisibleDeprecationWarning)
+ assert_raises(ValueError, _clean_inputs,
+ lp._replace(bounds=[(1, 2), (1, 2, 2)]))
+ assert_raises(ValueError, _clean_inputs,
+ lp._replace(bounds=[(1, 2), (1, 2), (1, 2)]))
+
+ lp = _LPProblem(c=[1, 2, 3, 4])
+
+ assert_raises(ValueError, _clean_inputs,
+ lp._replace(bounds=[(1, 2, 3, 4), (1, 2, 3, 4)]))
+
+
+def test_good_bounds():
+ lp = _LPProblem(c=[1, 2])
+
+ lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[]))
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[[]]))
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2)))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)]))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)]))
+ assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None), (-np.inf, None)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 2)
+
+ lp = _LPProblem(c=[1, 2, 3, 4])
+
+ lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2)))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)]))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)]))
+ assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None),
+ (-np.inf, None),
+ (None, np.inf),
+ (-np.inf, np.inf)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 4)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__numdiff.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__numdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee9446245223f2793cafb5ea2464f58ad2db1c1f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__numdiff.py
@@ -0,0 +1,944 @@
+import math
+from itertools import product
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+
+from scipy._lib._util import MapWrapper, _ScalarFunctionWrapper
+from scipy.sparse import csr_array, csc_array, lil_array
+from scipy._lib._array_api import xp_result_type
+
+from scipy.optimize._numdiff import (
+ _adjust_scheme_to_bounds, approx_derivative, check_derivative,
+ group_columns, _eps_for_method, _compute_absolute_step)
+from scipy.optimize import rosen
+
+
+def test_group_columns():
+ structure = [
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 0]
+ ]
+ for transform in [np.asarray, csr_array, csc_array, lil_array]:
+ A = transform(structure)
+ order = np.arange(6)
+ groups_true = np.array([0, 1, 2, 0, 1, 2])
+ groups = group_columns(A, order)
+ assert_equal(groups, groups_true)
+
+ order = [1, 2, 4, 3, 5, 0]
+ groups_true = np.array([2, 0, 1, 2, 0, 1])
+ groups = group_columns(A, order)
+ assert_equal(groups, groups_true)
+
+ # Test repeatability.
+ groups_1 = group_columns(A)
+ groups_2 = group_columns(A)
+ assert_equal(groups_1, groups_2)
+
+
+def test_correct_fp_eps():
+ # check that relative step size is correct for FP size
+ EPS = np.finfo(np.float64).eps
+ relative_step = {"2-point": EPS**0.5,
+ "3-point": EPS**(1/3),
+ "cs": EPS**0.5}
+ for method in ['2-point', '3-point', 'cs']:
+ assert_allclose(
+ _eps_for_method(np.float64, np.float64, method),
+ relative_step[method])
+ assert_allclose(
+ _eps_for_method(np.complex128, np.complex128, method),
+ relative_step[method]
+ )
+
+ # check another FP size
+ EPS = np.finfo(np.float32).eps
+ relative_step = {"2-point": EPS**0.5,
+ "3-point": EPS**(1/3),
+ "cs": EPS**0.5}
+
+ for method in ['2-point', '3-point', 'cs']:
+ assert_allclose(
+ _eps_for_method(np.float64, np.float32, method),
+ relative_step[method]
+ )
+ assert_allclose(
+ _eps_for_method(np.float32, np.float64, method),
+ relative_step[method]
+ )
+ assert_allclose(
+ _eps_for_method(np.float32, np.float32, method),
+ relative_step[method]
+ )
+
+
+class TestAdjustSchemeToBounds:
+ def test_no_bounds(self):
+ x0 = np.zeros(3)
+ h = np.full(3, 1e-2)
+ inf_lower = np.empty_like(x0)
+ inf_upper = np.empty_like(x0)
+ inf_lower.fill(-np.inf)
+ inf_upper.fill(np.inf)
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '1-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '1-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(~one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '2-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(~one_sided))
+
+ def test_with_bound(self):
+ x0 = np.array([0.0, 0.85, -0.85])
+ lb = -np.ones(3)
+ ub = np.ones(3)
+ h = np.array([1, 1, -1]) * 1e-1
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, h)
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1)
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.abs(h))
+ assert_(np.all(~one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1)
+ assert_equal(one_sided, np.array([False, True, True]))
+
+ def test_tight_bounds(self):
+ lb = np.array([-0.03, -0.03])
+ ub = np.array([0.05, 0.05])
+ x0 = np.array([0.0, 0.03])
+ h = np.array([-0.1, -0.1])
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.05, -0.06]))
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.025, -0.03]))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.03, -0.03]))
+ assert_equal(one_sided, np.array([False, True]))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.015, -0.015]))
+ assert_equal(one_sided, np.array([False, True]))
+
+
+class TestApproxDerivativesDense:
+ def fun_scalar_scalar(self, x):
+ return np.sinh(x)
+
+ def jac_scalar_scalar(self, x):
+ return np.cosh(x)
+
+ def fun_scalar_vector(self, x):
+ return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])])
+
+ def jac_scalar_vector(self, x):
+ return np.array(
+ [2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1)
+
+ def fun_vector_scalar(self, x):
+ return np.sin(x[0] * x[1]) * np.log(x[0])
+
+ def wrong_dimensions_fun(self, x):
+ return np.array([x**2, np.tan(x), np.exp(x)])
+
+ def jac_vector_scalar(self, x):
+ return np.array([
+ x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) +
+ np.sin(x[0] * x[1]) / x[0],
+ x[0] * np.cos(x[0] * x[1]) * np.log(x[0])
+ ])
+
+ def fun_vector_vector(self, x):
+ return np.array([
+ x[0] * np.sin(x[1]),
+ x[1] * np.cos(x[0]),
+ x[0] ** 3 * x[1] ** -0.5
+ ])
+
+ def fun_vector_vector_with_arg(self, x, arg):
+ """Used to test passing custom arguments with check_derivative()"""
+ assert arg == 42
+ return np.array([
+ x[0] * np.sin(x[1]),
+ x[1] * np.cos(x[0]),
+ x[0] ** 3 * x[1] ** -0.5
+ ])
+
+ def jac_vector_vector(self, x):
+ return np.array([
+ [np.sin(x[1]), x[0] * np.cos(x[1])],
+ [-x[1] * np.sin(x[0]), np.cos(x[0])],
+ [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
+ ])
+
+ def jac_vector_vector_with_arg(self, x, arg):
+ """Used to test passing custom arguments with check_derivative()"""
+ assert arg == 42
+ return np.array([
+ [np.sin(x[1]), x[0] * np.cos(x[1])],
+ [-x[1] * np.sin(x[0]), np.cos(x[0])],
+ [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
+ ])
+
+ def fun_parametrized(self, x, c0, c1=1.0):
+ return np.array([np.exp(c0 * x[0]), np.exp(c1 * x[1])])
+
+ def jac_parametrized(self, x, c0, c1=0.1):
+ return np.array([
+ [c0 * np.exp(c0 * x[0]), 0],
+ [0, c1 * np.exp(c1 * x[1])]
+ ])
+
+ def fun_with_nan(self, x):
+ return x if np.abs(x) <= 1e-8 else np.nan
+
+ def jac_with_nan(self, x):
+ return 1.0 if np.abs(x) <= 1e-8 else np.nan
+
+ def fun_zero_jacobian(self, x):
+ return np.array([x[0] * x[1], np.cos(x[0] * x[1])])
+
+ def jac_zero_jacobian(self, x):
+ return np.array([
+ [x[1], x[0]],
+ [-x[1] * np.sin(x[0] * x[1]), -x[0] * np.sin(x[0] * x[1])]
+ ])
+
+ def jac_non_numpy(self, x):
+ # x can be a scalar or an array [val].
+ # Cast to true scalar before handing over to math.exp
+ xp = np.asarray(x).item()
+ return math.exp(xp)
+
+ def test_scalar_scalar(self):
+ x0 = 1.0
+ jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0)
+ jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='cs')
+ jac_true = self.jac_scalar_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_scalar_scalar_abs_step(self):
+ # can approx_derivative use abs_step?
+ x0 = 1.0
+ jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='2-point', abs_step=1.49e-8)
+ jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0,
+ abs_step=1.49e-8)
+ jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='cs', abs_step=1.49e-8)
+ jac_true = self.jac_scalar_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_scalar_vector(self):
+ x0 = 0.5
+ with MapWrapper(2) as mapper:
+ jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0,
+ method='2-point', workers=mapper)
+ jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0, workers=map)
+ jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0,
+ method='cs', workers=None)
+ jac_true = self.jac_scalar_vector(np.atleast_1d(x0))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ @pytest.mark.fail_slow(5.0)
+ def test_workers_evaluations_and_nfev(self):
+ # check that nfev consumed by approx_derivative is tracked properly
+ # and that parallel evaluation is same as series
+ x0 = [0.5, 1.5, 2.0]
+ with MapWrapper(2) as mapper:
+ md2, mdct2 = approx_derivative(rosen, x0,
+ method='2-point', workers=mapper,
+ full_output=True)
+ md3, mdct3 = approx_derivative(rosen, x0,
+ workers=mapper, full_output=True)
+ # supply a number for workers. This is not normally recommended
+ # for upstream workers as setting up processes incurs a large overhead
+ md4, mdct4 = approx_derivative(rosen, x0,
+ method='cs', workers=2,
+ full_output=True)
+
+ sfr = _ScalarFunctionWrapper(rosen)
+ d2, dct2 = approx_derivative(sfr, x0, method='2-point', full_output=True)
+ assert_equal(dct2['nfev'], sfr.nfev)
+ sfr.nfev = 0
+ d3, dct3 = approx_derivative(sfr, x0, full_output=True)
+ assert_equal(dct3['nfev'], sfr.nfev)
+ sfr.nfev = 0
+ d4, dct4 = approx_derivative(sfr, x0, method='cs', full_output=True)
+ assert_equal(dct4['nfev'], sfr.nfev)
+
+ assert_equal(mdct2['nfev'], dct2['nfev'])
+ assert_equal(mdct3['nfev'], dct3['nfev'])
+ assert_equal(mdct4['nfev'], dct4['nfev'])
+ # also check that gradients are equivalent
+ assert_equal(md2, d2)
+ assert_equal(md3, d3)
+ assert_equal(md4, d4)
+
+ def test_vector_scalar(self):
+ x0 = np.array([100.0, -0.5])
+ jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0)
+ jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
+ method='cs')
+ jac_true = self.jac_vector_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-7)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_vector_scalar_abs_step(self):
+ # can approx_derivative use abs_step?
+ x0 = np.array([100.0, -0.5])
+ jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
+ method='2-point', abs_step=1.49e-8)
+ jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0,
+ abs_step=1.49e-8, rel_step=np.inf)
+ jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
+ method='cs', abs_step=1.49e-8)
+ jac_true = self.jac_vector_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=3e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_vector_vector(self):
+ x0 = np.array([-100.0, 0.2])
+ jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.fun_vector_vector, x0)
+ with MapWrapper(2) as mapper:
+ jac_diff_4 = approx_derivative(self.fun_vector_vector, x0,
+ method='cs', workers=mapper)
+ jac_true = self.jac_vector_vector(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-5)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_wrong_dimensions(self):
+ x0 = 1.0
+ assert_raises(RuntimeError, approx_derivative,
+ self.wrong_dimensions_fun, x0)
+ f0 = self.wrong_dimensions_fun(np.atleast_1d(x0))
+ assert_raises(ValueError, approx_derivative,
+ self.wrong_dimensions_fun, x0, f0=f0)
+
+ def test_custom_rel_step(self):
+ x0 = np.array([-0.1, 0.1])
+ jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point', rel_step=1e-4)
+ jac_diff_3 = approx_derivative(self.fun_vector_vector, x0,
+ rel_step=1e-4)
+ jac_true = self.jac_vector_vector(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-2)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-4)
+
+ def test_options(self):
+ x0 = np.array([1.0, 1.0])
+ c0 = -1.0
+ c1 = 1.0
+ lb = 0.0
+ ub = 2.0
+ f0 = self.fun_parametrized(x0, c0, c1=c1)
+ rel_step = np.array([-1e-6, 1e-7])
+ jac_true = self.jac_parametrized(x0, c0, c1)
+ jac_diff_2 = approx_derivative(
+ self.fun_parametrized, x0, method='2-point', rel_step=rel_step,
+ f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub))
+ jac_diff_3 = approx_derivative(
+ self.fun_parametrized, x0, rel_step=rel_step,
+ f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+
+ def test_with_bounds_2_point(self):
+ lb = -np.ones(2)
+ ub = np.ones(2)
+
+ x0 = np.array([-2.0, 0.2])
+ assert_raises(ValueError, approx_derivative,
+ self.fun_vector_vector, x0, bounds=(lb, ub))
+
+ x0 = np.array([-1.0, 1.0])
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point', bounds=(lb, ub))
+ jac_true = self.jac_vector_vector(x0)
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+
+ def test_with_bounds_3_point(self):
+ lb = np.array([1.0, 1.0])
+ ub = np.array([2.0, 2.0])
+
+ x0 = np.array([1.0, 2.0])
+ jac_true = self.jac_vector_vector(x0)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0)
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ bounds=(lb, np.inf))
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ bounds=(-np.inf, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ def test_tight_bounds(self):
+ x0 = np.array([10.0, 10.0])
+ lb = x0 - 3e-9
+ ub = x0 + 2e-9
+ jac_true = self.jac_vector_vector(x0)
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, method='2-point', bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, method='2-point',
+ rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_true, jac_diff, rtol=1e-6)
+
+ def test_bound_switches(self):
+ lb = -1e-8
+ ub = 1e-8
+ x0 = 0.0
+ jac_true = self.jac_with_nan(x0)
+ jac_diff_2 = approx_derivative(
+ self.fun_with_nan, x0, method='2-point', rel_step=1e-6,
+ bounds=(lb, ub))
+ jac_diff_3 = approx_derivative(
+ self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+
+ x0 = 1e-8
+ jac_true = self.jac_with_nan(x0)
+ jac_diff_2 = approx_derivative(
+ self.fun_with_nan, x0, method='2-point', rel_step=1e-6,
+ bounds=(lb, ub))
+ jac_diff_3 = approx_derivative(
+ self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+
+ def test_non_numpy(self):
+ x0 = 1.0
+ jac_true = self.jac_non_numpy(x0)
+ jac_diff_2 = approx_derivative(self.jac_non_numpy, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.jac_non_numpy, x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-8)
+
+ # math.exp cannot handle complex arguments, hence this raises
+ assert_raises(TypeError, approx_derivative, self.jac_non_numpy, x0,
+ **dict(method='cs'))
+
+ def test_fp(self):
+ # checks that approx_derivative works for FP size other than 64.
+ # Example is derived from the minimal working example in gh12991.
+ rng = np.random.default_rng(1)
+
+ def func(p, x):
+ return p[0] + p[1] * x
+
+ def err(p, x, y):
+ return func(p, x) - y
+
+ x = np.linspace(0, 1, 100, dtype=np.float64)
+ y = rng.random(size=100, dtype=np.float64)
+ p0 = np.array([-1.0, -1.0])
+
+ jac_fp64 = approx_derivative(err, p0, method='2-point', args=(x, y))
+
+ # parameter vector is float32, func output is float64
+ jac_fp = approx_derivative(err, p0.astype(np.float32),
+ method='2-point', args=(x, y))
+ assert err(p0, x, y).dtype == np.float64
+ assert_allclose(jac_fp, jac_fp64, atol=1e-3)
+
+ # parameter vector is float64, func output is float32
+ def err_fp32(p):
+ assert p.dtype == np.float32
+ return err(p, x, y).astype(np.float32)
+
+ jac_fp = approx_derivative(err_fp32, p0.astype(np.float32),
+ method='2-point')
+ assert_allclose(jac_fp, jac_fp64, atol=1e-3)
+ assert jac_fp.dtype == np.float32
+
+ # check upper bound of error on the derivative for 2-point
+ def f(x):
+ return np.sin(x)
+ def g(x):
+ return np.cos(x)
+ def hess(x):
+ return -np.sin(x)
+
+ def calc_atol(h, x0, f, hess, EPS):
+ # truncation error
+ t0 = h / 2 * max(np.abs(hess(x0)), np.abs(hess(x0 + h)))
+ # roundoff error. There may be a divisor (>1) missing from
+ # the following line, so this contribution is possibly
+ # overestimated
+ t1 = EPS / h * max(np.abs(f(x0)), np.abs(f(x0 + h)))
+ return t0 + t1
+
+ for dtype in [np.float16, np.float32, np.float64]:
+ EPS = np.finfo(dtype).eps
+ x0 = np.array(1.0).astype(dtype)
+ h = _compute_absolute_step(None, x0, f(x0), '2-point')
+ atol = calc_atol(h, x0, f, hess, EPS)
+ err = approx_derivative(f, x0, method='2-point',
+ abs_step=h) - g(x0)
+ assert abs(err) < atol
+
+
+ @pytest.mark.parametrize("x0_dtype", (np.float16, np.float32, np.float64))
+ @pytest.mark.parametrize("f0_dtype", (np.float16, np.float32, np.float64))
+ @pytest.mark.parametrize("method", ['2-point', '3-point'])
+ def test_check_dtype(self, x0_dtype, f0_dtype, method):
+ # the output of approx_derivative should be the promoted
+ # type of x0, f0.
+
+ # both are of the same dtype
+ x = np.array([2.0, 3.0, 4.0], dtype=x0_dtype)
+
+ def f(x):
+ return f0_dtype(rosen(x))
+
+ promoted_type = xp_result_type(
+ x,
+ f(x),
+ force_floating=True,
+ xp=np
+ )
+ g = approx_derivative(f, x, method=method)
+ assert g.dtype == promoted_type
+
+ # setting abs_step or rel_step shouldn't change output dtype
+ g = approx_derivative(f, x, rel_step=np.float16(0.1), method=method)
+ assert g.dtype == promoted_type
+
+ g = approx_derivative(f, x, abs_step=np.float16(0.1), method=method)
+ assert g.dtype == promoted_type
+
+ def test_check_derivative(self):
+ x0 = np.array([-10.0, 10])
+ accuracy = check_derivative(self.fun_vector_vector,
+ self.jac_vector_vector, x0)
+ assert_(accuracy < 1e-9)
+ accuracy = check_derivative(self.fun_vector_vector,
+ self.jac_vector_vector, x0)
+ assert_(accuracy < 1e-6)
+
+ x0 = np.array([0.0, 0.0])
+ accuracy = check_derivative(self.fun_zero_jacobian,
+ self.jac_zero_jacobian, x0)
+ assert_(accuracy == 0)
+ accuracy = check_derivative(self.fun_zero_jacobian,
+ self.jac_zero_jacobian, x0)
+ assert_(accuracy == 0)
+
+ def test_check_derivative_with_kwargs(self):
+ x0 = np.array([-10.0, 10])
+ accuracy = check_derivative(self.fun_vector_vector_with_arg,
+ self.jac_vector_vector_with_arg,
+ x0,
+ kwargs={'arg': 42})
+ assert_(accuracy < 1e-9)
+
+
+class TestApproxDerivativeSparse:
+ # Example from Numerical Optimization 2nd edition, p. 198.
+ def setup_method(self):
+ self.rng = np.random.default_rng(121091202)
+ self.n = 50
+ self.lb = -0.1 * (1 + np.arange(self.n))
+ self.ub = 0.1 * (1 + np.arange(self.n))
+ self.x0 = np.empty(self.n)
+ self.x0[::2] = (1 - 1e-7) * self.lb[::2]
+ self.x0[1::2] = (1 - 1e-7) * self.ub[1::2]
+
+ self.J_true = self.jac(self.x0)
+
+ def fun(self, x):
+ e = x[1:]**3 - x[:-1]**2
+ return np.hstack((0, 3 * e)) + np.hstack((2 * e, 0))
+
+ def jac(self, x):
+ n = x.size
+ J = np.zeros((n, n))
+ J[0, 0] = -4 * x[0]
+ J[0, 1] = 6 * x[1]**2
+ for i in range(1, n - 1):
+ J[i, i - 1] = -6 * x[i-1]
+ J[i, i] = 9 * x[i]**2 - 4 * x[i]
+ J[i, i + 1] = 6 * x[i+1]**2
+ J[-1, -1] = 9 * x[-1]**2
+ J[-1, -2] = -6 * x[-2]
+
+ return J
+
+ def structure(self, n):
+ A = np.zeros((n, n), dtype=int)
+ A[0, 0] = 1
+ A[0, 1] = 1
+ for i in range(1, n - 1):
+ A[i, i - 1: i + 2] = 1
+ A[-1, -1] = 1
+ A[-1, -2] = 1
+
+ return A
+
+ @pytest.mark.fail_slow(5)
+ def test_all(self):
+ A = self.structure(self.n)
+ order = np.arange(self.n)
+ groups_1 = group_columns(A, order)
+ self.rng.shuffle(order)
+ groups_2 = group_columns(A, order)
+
+ with MapWrapper(2) as mapper:
+ for method, groups, l, u, mf in product(
+ ['2-point', '3-point', 'cs'], [groups_1, groups_2],
+ [-np.inf, self.lb], [np.inf, self.ub], [map, mapper]):
+ J = approx_derivative(self.fun, self.x0, method=method,
+ bounds=(l, u), sparsity=(A, groups),
+ workers=mf)
+ assert_(isinstance(J, csr_array))
+ assert_allclose(J.toarray(), self.J_true, rtol=1e-6)
+
+ rel_step = np.full_like(self.x0, 1e-8)
+ rel_step[::2] *= -1
+ J = approx_derivative(self.fun, self.x0, method=method,
+ rel_step=rel_step, sparsity=(A, groups),
+ workers=mf)
+ assert_allclose(J.toarray(), self.J_true, rtol=1e-5)
+
+ def test_no_precomputed_groups(self):
+ A = self.structure(self.n)
+ J = approx_derivative(self.fun, self.x0, sparsity=A)
+ assert_allclose(J.toarray(), self.J_true, rtol=1e-6)
+
+ def test_equivalence(self):
+ structure = np.ones((self.n, self.n), dtype=int)
+ groups = np.arange(self.n)
+ for method in ['2-point', '3-point', 'cs']:
+ J_dense = approx_derivative(self.fun, self.x0, method=method)
+ J_sparse = approx_derivative(
+ self.fun, self.x0, sparsity=(structure, groups), method=method)
+ assert_allclose(J_dense, J_sparse.toarray(),
+ rtol=5e-16, atol=7e-15)
+
+ def test_check_derivative(self):
+ def jac(x):
+ return csr_array(self.jac(x))
+
+ accuracy = check_derivative(self.fun, jac, self.x0,
+ bounds=(self.lb, self.ub))
+ assert_(accuracy < 1e-9)
+
+ accuracy = check_derivative(self.fun, jac, self.x0,
+ bounds=(self.lb, self.ub))
+ assert_(accuracy < 1e-9)
+
+
+class TestApproxDerivativeLinearOperator:
+
+ def fun_scalar_scalar(self, x):
+ return np.sinh(x)
+
+ def jac_scalar_scalar(self, x):
+ return np.cosh(x)
+
+ def fun_scalar_vector(self, x):
+ return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])])
+
+ def jac_scalar_vector(self, x):
+ return np.array(
+ [2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1)
+
+ def fun_vector_scalar(self, x):
+ return np.sin(x[0] * x[1]) * np.log(x[0])
+
+ def jac_vector_scalar(self, x):
+ return np.array([
+ x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) +
+ np.sin(x[0] * x[1]) / x[0],
+ x[0] * np.cos(x[0] * x[1]) * np.log(x[0])
+ ])
+
+ def fun_vector_vector(self, x):
+ return np.array([
+ x[0] * np.sin(x[1]),
+ x[1] * np.cos(x[0]),
+ x[0] ** 3 * x[1] ** -0.5
+ ])
+
+ def jac_vector_vector(self, x):
+ return np.array([
+ [np.sin(x[1]), x[0] * np.cos(x[1])],
+ [-x[1] * np.sin(x[0]), np.cos(x[0])],
+ [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
+ ])
+
+ def test_scalar_scalar(self):
+ x0 = 1.0
+ jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_scalar_scalar(x0)
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=(1,))
+ assert_allclose(jac_diff_2.dot(p), jac_true*p,
+ rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), jac_true*p,
+ rtol=5e-6)
+ assert_allclose(jac_diff_4.dot(p), jac_true*p,
+ rtol=5e-6)
+
+ def test_scalar_vector(self):
+ x0 = 0.5
+ jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_scalar_vector(np.atleast_1d(x0))
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=(1,))
+ assert_allclose(jac_diff_2.dot(p), jac_true.dot(p),
+ rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), jac_true.dot(p),
+ rtol=5e-6)
+ assert_allclose(jac_diff_4.dot(p), jac_true.dot(p),
+ rtol=5e-6)
+
+ def test_vector_scalar(self):
+ x0 = np.array([100.0, -0.5])
+ jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_vector_scalar(x0)
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=x0.shape)
+ assert_allclose(jac_diff_2.dot(p), np.atleast_1d(jac_true.dot(p)),
+ rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), np.atleast_1d(jac_true.dot(p)),
+ rtol=5e-6)
+ assert_allclose(jac_diff_4.dot(p), np.atleast_1d(jac_true.dot(p)),
+ rtol=1e-7)
+
+ def test_vector_vector(self):
+ x0 = np.array([-100.0, 0.2])
+ jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_vector_vector, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_vector_vector, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_vector_vector(x0)
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=x0.shape)
+ assert_allclose(jac_diff_2.dot(p), jac_true.dot(p), rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), jac_true.dot(p), rtol=1e-6)
+ assert_allclose(jac_diff_4.dot(p), jac_true.dot(p), rtol=1e-7)
+
+ def test_exception(self):
+ x0 = np.array([-100.0, 0.2])
+ assert_raises(ValueError, approx_derivative,
+ self.fun_vector_vector, x0,
+ method='2-point', bounds=(1, np.inf))
+
+
+def test_absolute_step_sign():
+ # test for gh12487
+ # if an absolute step is specified for 2-point differences make sure that
+ # the side corresponds to the step. i.e. if step is positive then forward
+ # differences should be used, if step is negative then backwards
+ # differences should be used.
+
+ # function has double discontinuity at x = [-1, -1]
+ # first component is \/, second component is /\
+ def f(x):
+ return -np.abs(x[0] + 1) + np.abs(x[1] + 1)
+
+ # check that the forward difference is used
+ grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=1e-8)
+ assert_allclose(grad, [-1.0, 1.0])
+
+ # check that the backwards difference is used
+ grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=-1e-8)
+ assert_allclose(grad, [1.0, -1.0])
+
+ # check that the forwards difference is used with a step for both
+ # parameters
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=[1e-8, 1e-8]
+ )
+ assert_allclose(grad, [-1.0, 1.0])
+
+ # check that we can mix forward/backwards steps.
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=[1e-8, -1e-8]
+ )
+ assert_allclose(grad, [-1.0, -1.0])
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=[-1e-8, 1e-8]
+ )
+ assert_allclose(grad, [1.0, 1.0])
+
+ # the forward step should reverse to a backwards step if it runs into a
+ # bound
+ # This is kind of tested in TestAdjustSchemeToBounds, but only for a lower level
+ # function.
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=1e-8,
+ bounds=(-np.inf, -1)
+ )
+ assert_allclose(grad, [1.0, -1.0])
+
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=-1e-8, bounds=(-1, np.inf)
+ )
+ assert_allclose(grad, [-1.0, 1.0])
+
+
+def test__compute_absolute_step():
+ # tests calculation of absolute step from rel_step
+ methods = ['2-point', '3-point', 'cs']
+
+ x0 = np.array([1e-5, 0, 1, 1e5])
+
+ EPS = np.finfo(np.float64).eps
+ relative_step = {
+ "2-point": EPS**0.5,
+ "3-point": EPS**(1/3),
+ "cs": EPS**0.5
+ }
+ f0 = np.array(1.0)
+
+ for method in methods:
+ rel_step = relative_step[method]
+ correct_step = np.array([rel_step,
+ rel_step * 1.,
+ rel_step * 1.,
+ rel_step * np.abs(x0[3])])
+
+ abs_step = _compute_absolute_step(None, x0, f0, method)
+ assert_allclose(abs_step, correct_step)
+
+ sign_x0 = (-x0 >= 0).astype(float) * 2 - 1
+ abs_step = _compute_absolute_step(None, -x0, f0, method)
+ assert_allclose(abs_step, sign_x0 * correct_step)
+
+ # if a relative step is provided it should be used
+ rel_step = np.array([0.1, 1, 10, 100])
+ correct_step = np.array([rel_step[0] * x0[0],
+ relative_step['2-point'],
+ rel_step[2] * 1.,
+ rel_step[3] * np.abs(x0[3])])
+
+ abs_step = _compute_absolute_step(rel_step, x0, f0, '2-point')
+ assert_allclose(abs_step, correct_step)
+
+ sign_x0 = (-x0 >= 0).astype(float) * 2 - 1
+ abs_step = _compute_absolute_step(rel_step, -x0, f0, '2-point')
+ assert_allclose(abs_step, sign_x0 * correct_step)
+
+ # the dtype of absolute step should be the same as x0
+ #def _compute_absolute_step(rel_step, x0, f0, method):
+ x0 = np.array([1e-5, 0, 1, 1e5], dtype=np.float32)
+ abs_step = _compute_absolute_step(None, x0, f0, '3-point')
+ assert abs_step.dtype == np.float32
+ abs_step = _compute_absolute_step(None, x0, f0, '2-point')
+ assert abs_step.dtype == np.float32
+
+ x0 = np.array([0.1, 0, 1, 50], dtype=np.float16)
+ abs_step = _compute_absolute_step(None, x0, f0, '3-point')
+ assert abs_step.dtype == np.float16
+ abs_step = _compute_absolute_step(None, x0, f0, '2-point')
+ assert abs_step.dtype == np.float16
+
+ x0 = np.array([1e-3, 0, 1, 10], dtype=np.float64)
+ f0 = np.array(1.0, dtype=np.float16)
+ abs_step = _compute_absolute_step(rel_step, x0, f0, '2-point')
+ assert abs_step.dtype == np.float64
+
+ x0 = np.array([1e-5, 0, 1, 1e5], dtype=np.float32)
+ abs_step = _compute_absolute_step(rel_step, x0, f0, '2-point')
+ assert abs_step.dtype == np.float32
+
+ x0 = np.array([1e-3, 0, 1, 10], dtype=np.float16)
+ abs_step = _compute_absolute_step(rel_step, x0, f0, '2-point')
+ assert abs_step.dtype == np.float16
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__remove_redundancy.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d583bcb97049861ba842632419b54ade4cd0caab
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__remove_redundancy.py
@@ -0,0 +1,227 @@
+"""
+Unit test for Linear Programming via Simplex Algorithm.
+"""
+
+# TODO: add tests for:
+# https://github.com/scipy/scipy/issues/5400
+# https://github.com/scipy/scipy/issues/6690
+
+import numpy as np
+from numpy.testing import (
+ assert_,
+ assert_allclose,
+ assert_equal)
+
+from .test_linprog import magic_square
+from scipy.optimize._remove_redundancy import _remove_redundancy_svd
+from scipy.optimize._remove_redundancy import _remove_redundancy_pivot_dense
+from scipy.optimize._remove_redundancy import _remove_redundancy_pivot_sparse
+from scipy.optimize._remove_redundancy import _remove_redundancy_id
+
+from scipy.sparse import csc_array
+
+
+def redundancy_removed(A, B):
+ """Checks whether a matrix contains only independent rows of another"""
+ for rowA in A:
+ # `rowA in B` is not a reliable check
+ for rowB in B:
+ if np.all(rowA == rowB):
+ break
+ else:
+ return False
+ return A.shape[0] == np.linalg.matrix_rank(A) == np.linalg.matrix_rank(B)
+
+
+class RRCommonTests:
+ def setup_method(self):
+ self.rng = np.random.default_rng(2017)
+
+ def test_no_redundancy(self):
+ m, n = 10, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_allclose(A0, A1)
+ assert_allclose(b0, b1)
+ assert_equal(status, 0)
+
+ def test_infeasible_zero_row(self):
+ A = np.eye(3)
+ A[1, :] = 0
+ b = self.rng.random(3)
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 2)
+
+ def test_remove_zero_row(self):
+ A = np.eye(3)
+ A[1, :] = 0
+ b = self.rng.random(3)
+ b[1] = 0
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_allclose(A1, A[[0, 2], :])
+ assert_allclose(b1, b[[0, 2]])
+
+ def test_infeasible_m_gt_n(self):
+ m, n = 20, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 2)
+
+ def test_infeasible_m_eq_n(self):
+ m, n = 10, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A0[-1, :] = 2 * A0[-2, :]
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 2)
+
+ def test_infeasible_m_lt_n(self):
+ m, n = 9, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A0[-1, :] = np.arange(m - 1).dot(A0[:-1])
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 2)
+
+ def test_m_gt_n(self):
+ rng = np.random.default_rng(2032)
+ m, n = 20, 10
+ A0 = rng.random((m, n))
+ b0 = rng.random(m)
+ x = np.linalg.solve(A0[:n, :], b0[:n])
+ b0[n:] = A0[n:, :].dot(x)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], n)
+ assert_equal(np.linalg.matrix_rank(A1), n)
+
+ def test_m_gt_n_rank_deficient(self):
+ m, n = 20, 10
+ A0 = np.zeros((m, n))
+ A0[:, 0] = 1
+ b0 = np.ones(m)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 0)
+ assert_allclose(A1, A0[0:1, :])
+ assert_allclose(b1, b0[0])
+
+ def test_m_lt_n_rank_deficient(self):
+ m, n = 9, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A0[-1, :] = np.arange(m - 1).dot(A0[:-1])
+ b0[-1] = np.arange(m - 1).dot(b0[:-1])
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], 8)
+ assert_equal(np.linalg.matrix_rank(A1), 8)
+
+ def test_dense1(self):
+ A = np.ones((6, 6))
+ A[0, :3] = 0
+ A[1, 3:] = 0
+ A[3:, ::2] = -1
+ A[3, :2] = 0
+ A[4, 2:] = 0
+ b = np.zeros(A.shape[0])
+
+ A1, b1, status, message = self.rr(A, b)
+ assert_(redundancy_removed(A1, A))
+ assert_equal(status, 0)
+
+ def test_dense2(self):
+ A = np.eye(6)
+ A[-2, -1] = 1
+ A[-1, :] = 1
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_(redundancy_removed(A1, A))
+ assert_equal(status, 0)
+
+ def test_dense3(self):
+ A = np.eye(6)
+ A[-2, -1] = 1
+ A[-1, :] = 1
+ b = self.rng.random(A.shape[0])
+ b[-1] = np.sum(b[:-1])
+ A1, b1, status, message = self.rr(A, b)
+ assert_(redundancy_removed(A1, A))
+ assert_equal(status, 0)
+
+ def test_m_gt_n_sparse(self):
+ rng = np.random.default_rng(2013)
+ m, n = 20, 5
+ p = 0.1
+ A = rng.random((m, n))
+ A[rng.random((m, n)) > p] = 0
+ rank = np.linalg.matrix_rank(A)
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], rank)
+ assert_equal(np.linalg.matrix_rank(A1), rank)
+
+ def test_m_lt_n_sparse(self):
+ rng = np.random.default_rng(2017)
+ m, n = 20, 50
+ p = 0.05
+ A = rng.random((m, n))
+ A[rng.random((m, n)) > p] = 0
+ rank = np.linalg.matrix_rank(A)
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], rank)
+ assert_equal(np.linalg.matrix_rank(A1), rank)
+
+ def test_m_eq_n_sparse(self):
+ rng = np.random.default_rng(2017)
+ m, n = 100, 100
+ p = 0.01
+ A = rng.random((m, n))
+ A[rng.random((m, n)) > p] = 0
+ rank = np.linalg.matrix_rank(A)
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], rank)
+ assert_equal(np.linalg.matrix_rank(A1), rank)
+
+ def test_magic_square(self):
+ A, b, c, numbers, _ = magic_square(3)
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], 23)
+ assert_equal(np.linalg.matrix_rank(A1), 23)
+
+ def test_magic_square2(self):
+ A, b, c, numbers, _ = magic_square(4)
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], 39)
+ assert_equal(np.linalg.matrix_rank(A1), 39)
+
+
+class TestRRSVD(RRCommonTests):
+ def rr(self, A, b):
+ return _remove_redundancy_svd(A, b)
+
+
+class TestRRPivotDense(RRCommonTests):
+ def rr(self, A, b):
+ return _remove_redundancy_pivot_dense(A, b)
+
+
+class TestRRID(RRCommonTests):
+ def rr(self, A, b):
+ return _remove_redundancy_id(A, b)
+
+
+class TestRRPivotSparse(RRCommonTests):
+ def rr(self, A, b):
+ rr_res = _remove_redundancy_pivot_sparse(csc_array(A), b)
+ A1, b1, status, message = rr_res
+ return A1.toarray(), b1, status, message
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__root.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__root.py
new file mode 100644
index 0000000000000000000000000000000000000000..271123240cabbe93d976c8edfbd745ecf596b5a9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__root.py
@@ -0,0 +1,123 @@
+"""
+Unit tests for optimization routines from _root.py.
+"""
+from numpy.testing import assert_, assert_equal
+import pytest
+from pytest import raises as assert_raises, warns as assert_warns
+import numpy as np
+
+from scipy.optimize import root
+
+
+class TestRoot:
+ def test_tol_parameter(self):
+ # Check that the minimize() tol= argument does something
+ def func(z):
+ x, y = z
+ return np.array([x**3 - 1, y**3 - 1])
+
+ def dfunc(z):
+ x, y = z
+ return np.array([[3*x**2, 0], [0, 3*y**2]])
+
+ for method in ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson',
+ 'diagbroyden', 'krylov']:
+ if method in ('linearmixing', 'excitingmixing'):
+ # doesn't converge
+ continue
+
+ if method in ('hybr', 'lm'):
+ jac = dfunc
+ else:
+ jac = None
+
+ sol1 = root(func, [1.1,1.1], jac=jac, tol=1e-4, method=method)
+ sol2 = root(func, [1.1,1.1], jac=jac, tol=0.5, method=method)
+ msg = f"{method}: {func(sol1.x)} vs. {func(sol2.x)}"
+ assert_(sol1.success, msg)
+ assert_(sol2.success, msg)
+ assert_(abs(func(sol1.x)).max() < abs(func(sol2.x)).max(),
+ msg)
+
+ def test_tol_norm(self):
+
+ def norm(x):
+ return abs(x[0])
+
+ for method in ['excitingmixing',
+ 'diagbroyden',
+ 'linearmixing',
+ 'anderson',
+ 'broyden1',
+ 'broyden2',
+ 'krylov']:
+
+ root(np.zeros_like, np.zeros(2), method=method,
+ options={"tol_norm": norm})
+
+ def test_minimize_scalar_coerce_args_param(self):
+ # GitHub issue #3503
+ def func(z, f=1):
+ x, y = z
+ return np.array([x**3 - 1, y**3 - f])
+ root(func, [1.1, 1.1], args=1.5)
+
+ def test_f_size(self):
+ # gh8320
+ # check that decreasing the size of the returned array raises an error
+ # and doesn't segfault
+ class fun:
+ def __init__(self):
+ self.count = 0
+
+ def __call__(self, x):
+ self.count += 1
+
+ if not (self.count % 5):
+ ret = x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0
+ else:
+ ret = ([x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0,
+ 0.5 * (x[1] - x[0]) ** 3 + x[1]])
+
+ return ret
+
+ F = fun()
+ with assert_raises(ValueError):
+ root(F, [0.1, 0.0], method='lm')
+
+ def test_gh_10370(self):
+ # gh-10370 reported that passing both `args` and `jac` to `root` with
+ # `method='krylov'` caused a failure. Ensure that this is fixed whether
+ # the gradient is passed via `jac` or as a second output of `fun`.
+ def fun(x, ignored):
+ return [3*x[0] - 0.25*x[1]**2 + 10, 0.1*x[0]**2 + 5*x[1] - 2]
+
+ def grad(x, ignored):
+ return [[3, 0.5 * x[1]], [0.2 * x[0], 5]]
+
+ def fun_grad(x, ignored):
+ return fun(x, ignored), grad(x, ignored)
+
+ x0 = np.zeros(2)
+
+ ref = root(fun, x0, args=(1,), method='krylov')
+ message = 'Method krylov does not use the jacobian'
+ with assert_warns(RuntimeWarning, match=message):
+ res1 = root(fun, x0, args=(1,), method='krylov', jac=grad)
+ with assert_warns(RuntimeWarning, match=message):
+ res2 = root(fun_grad, x0, args=(1,), method='krylov', jac=True)
+
+ assert_equal(res1.x, ref.x)
+ assert_equal(res2.x, ref.x)
+ assert res1.success is res2.success is ref.success is True
+
+ @pytest.mark.parametrize("method", ["hybr", "lm", "broyden1", "broyden2",
+ "anderson", "linearmixing",
+ "diagbroyden", "excitingmixing",
+ "krylov", "df-sane"])
+ def test_method_in_result(self, method):
+ def func(x):
+ return x - 1
+
+ res = root(func, x0=[1], method=method)
+ assert res.method == method
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__shgo.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..715ce1e803024c9981e40fb3ddb156757e09b89f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__shgo.py
@@ -0,0 +1,1225 @@
+import logging
+import warnings
+
+import numpy as np
+import time
+from multiprocessing import Pool
+from numpy.testing import assert_allclose
+import pytest
+from pytest import raises as assert_raises, warns
+from scipy.optimize import (shgo, Bounds, minimize_scalar, minimize, rosen,
+ rosen_der, rosen_hess, NonlinearConstraint, OptimizeWarning)
+from scipy.optimize._constraints import new_constraint_to_old
+from scipy.optimize._shgo import SHGO
+from scipy.optimize.tests.test_minimize_constrained import MaratosTestArgs
+
+
+class StructTestFunction:
+ def __init__(self, bounds, expected_x, expected_fun=None,
+ expected_xl=None, expected_funl=None):
+ self.bounds = bounds
+ self.expected_x = expected_x
+ self.expected_fun = expected_fun
+ self.expected_xl = expected_xl
+ self.expected_funl = expected_funl
+
+
+def wrap_constraints(g):
+ cons = []
+ if g is not None:
+ if not isinstance(g, tuple | list):
+ g = (g,)
+ else:
+ pass
+ for g in g:
+ cons.append({'type': 'ineq',
+ 'fun': g})
+ cons = tuple(cons)
+ else:
+ cons = None
+ return cons
+
+
+class StructTest1(StructTestFunction):
+ def f(self, x):
+ return x[0] ** 2 + x[1] ** 2
+
+ def g(x):
+ return -(np.sum(x, axis=0) - 6.0)
+
+ cons = wrap_constraints(g)
+
+
+test1_1 = StructTest1(bounds=[(-1, 6), (-1, 6)],
+ expected_x=[0, 0])
+test1_2 = StructTest1(bounds=[(0, 1), (0, 1)],
+ expected_x=[0, 0])
+test1_3 = StructTest1(bounds=[(None, None), (None, None)],
+ expected_x=[0, 0])
+
+
+class StructTest2(StructTestFunction):
+ """
+ Scalar function with several minima to test all minimiser retrievals
+ """
+
+ def f(self, x):
+ return (x - 30) * np.sin(x)
+
+ def g(x):
+ return 58 - np.sum(x, axis=0)
+
+ cons = wrap_constraints(g)
+
+
+test2_1 = StructTest2(bounds=[(0, 60)],
+ expected_x=[1.53567906],
+ expected_fun=-28.44677132,
+ # Important: test that funl return is in the correct
+ # order
+ expected_xl=np.array([[1.53567906],
+ [55.01782167],
+ [7.80894889],
+ [48.74797493],
+ [14.07445705],
+ [42.4913859],
+ [20.31743841],
+ [36.28607535],
+ [26.43039605],
+ [30.76371366]]),
+
+ expected_funl=np.array([-28.44677132, -24.99785984,
+ -22.16855376, -18.72136195,
+ -15.89423937, -12.45154942,
+ -9.63133158, -6.20801301,
+ -3.43727232, -0.46353338])
+ )
+
+test2_2 = StructTest2(bounds=[(0, 4.5)],
+ expected_x=[1.53567906],
+ expected_fun=[-28.44677132],
+ expected_xl=np.array([[1.53567906]]),
+ expected_funl=np.array([-28.44677132])
+ )
+
+
+class StructTest3(StructTestFunction):
+ """
+ Hock and Schittkowski 18 problem (HS18). Hoch and Schittkowski (1981)
+ http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf
+ Minimize: f = 0.01 * (x_1)**2 + (x_2)**2
+
+ Subject to: x_1 * x_2 - 25.0 >= 0,
+ (x_1)**2 + (x_2)**2 - 25.0 >= 0,
+ 2 <= x_1 <= 50,
+ 0 <= x_2 <= 50.
+
+ Approx. Answer:
+ f([(250)**0.5 , (2.5)**0.5]) = 5.0
+
+
+ """
+
+ # amended to test vectorisation of constraints
+ def f(self, x):
+ return 0.01 * (x[0]) ** 2 + (x[1]) ** 2
+
+ def g1(x):
+ return x[0] * x[1] - 25.0
+
+ def g2(x):
+ return x[0] ** 2 + x[1] ** 2 - 25.0
+
+ # g = (g1, g2)
+ # cons = wrap_constraints(g)
+
+ def g(x):
+ return x[0] * x[1] - 25.0, x[0] ** 2 + x[1] ** 2 - 25.0
+
+ # this checks that shgo can be sent new-style constraints
+ __nlc = NonlinearConstraint(g, 0, np.inf)
+ cons = (__nlc,)
+
+test3_1 = StructTest3(bounds=[(2, 50), (0, 50)],
+ expected_x=[250 ** 0.5, 2.5 ** 0.5],
+ expected_fun=5.0
+ )
+
+
+class StructTest4(StructTestFunction):
+ """
+ Hock and Schittkowski 11 problem (HS11). Hoch and Schittkowski (1981)
+
+ NOTE: Did not find in original reference to HS collection, refer to
+ Henderson (2015) problem 7 instead. 02.03.2016
+ """
+
+ def f(self, x):
+ return ((x[0] - 10) ** 2 + 5 * (x[1] - 12) ** 2 + x[2] ** 4
+ + 3 * (x[3] - 11) ** 2 + 10 * x[4] ** 6 + 7 * x[5] ** 2 + x[
+ 6] ** 4
+ - 4 * x[5] * x[6] - 10 * x[5] - 8 * x[6]
+ )
+
+ def g1(x):
+ return -(2 * x[0] ** 2 + 3 * x[1] ** 4 + x[2] + 4 * x[3] ** 2
+ + 5 * x[4] - 127)
+
+ def g2(x):
+ return -(7 * x[0] + 3 * x[1] + 10 * x[2] ** 2 + x[3] - x[4] - 282.0)
+
+ def g3(x):
+ return -(23 * x[0] + x[1] ** 2 + 6 * x[5] ** 2 - 8 * x[6] - 196)
+
+ def g4(x):
+ return -(4 * x[0] ** 2 + x[1] ** 2 - 3 * x[0] * x[1] + 2 * x[2] ** 2
+ + 5 * x[5] - 11 * x[6])
+
+ g = (g1, g2, g3, g4)
+
+ cons = wrap_constraints(g)
+
+
+test4_1 = StructTest4(bounds=[(-10, 10), ] * 7,
+ expected_x=[2.330499, 1.951372, -0.4775414,
+ 4.365726, -0.6244870, 1.038131, 1.594227],
+ expected_fun=680.6300573
+ )
+
+
+class StructTest5(StructTestFunction):
+ def f(self, x):
+ return (
+ -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0))))
+ - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
+ )
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+test5_1 = StructTest5(bounds=[(-512, 512), (-512, 512)],
+ expected_fun=[-959.64066272085051],
+ expected_x=[512., 404.23180542])
+
+
+class StructTestLJ(StructTestFunction):
+ """
+ LennardJones objective function. Used to test symmetry constraints
+ settings.
+ """
+
+ def f(self, x, *args):
+ print(f'x = {x}')
+ self.N = args[0]
+ k = int(self.N / 3)
+ s = 0.0
+
+ for i in range(k - 1):
+ for j in range(i + 1, k):
+ a = 3 * i
+ b = 3 * j
+ xd = x[a] - x[b]
+ yd = x[a + 1] - x[b + 1]
+ zd = x[a + 2] - x[b + 2]
+ ed = xd * xd + yd * yd + zd * zd
+ ud = ed * ed * ed
+ if ed > 0.0:
+ s += (1.0 / ud - 2.0) / ud
+
+ return s
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+N = 6
+boundsLJ = list(zip([-4.0] * 6, [4.0] * 6))
+
+testLJ = StructTestLJ(bounds=boundsLJ,
+ expected_fun=[-1.0],
+ expected_x=None,
+ # expected_x=[-2.71247337e-08,
+ # -2.71247337e-08,
+ # -2.50000222e+00,
+ # -2.71247337e-08,
+ # -2.71247337e-08,
+ # -1.50000222e+00]
+ )
+
+
+class StructTestS(StructTestFunction):
+ def f(self, x):
+ return ((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2
+ + (x[2] - 0.5) ** 2 + (x[3] - 0.5) ** 2)
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+test_s = StructTestS(bounds=[(0, 2.0), ] * 4,
+ expected_fun=0.0,
+ expected_x=np.ones(4) - 0.5
+ )
+
+
+class StructTestTable(StructTestFunction):
+ def f(self, x):
+ if x[0] == 3.0 and x[1] == 3.0:
+ return 50
+ else:
+ return 100
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+test_table = StructTestTable(bounds=[(-10, 10), (-10, 10)],
+ expected_fun=[50],
+ expected_x=[3.0, 3.0])
+
+
+class StructTestInfeasible(StructTestFunction):
+ """
+ Test function with no feasible domain.
+ """
+
+ def f(self, x, *args):
+ return x[0] ** 2 + x[1] ** 2
+
+ def g1(x):
+ return x[0] + x[1] - 1
+
+ def g2(x):
+ return -(x[0] + x[1] - 1)
+
+ def g3(x):
+ return -x[0] + x[1] - 1
+
+ def g4(x):
+ return -(-x[0] + x[1] - 1)
+
+ g = (g1, g2, g3, g4)
+ cons = wrap_constraints(g)
+
+
+test_infeasible = StructTestInfeasible(bounds=[(2, 50), (-1, 1)],
+ expected_fun=None,
+ expected_x=None
+ )
+
+
+@pytest.mark.skip("Not a test")
+def run_test(test, args=(), test_atol=1e-5, n=100, iters=None,
+ callback=None, minimizer_kwargs=None, options=None,
+ sampling_method='sobol', workers=1):
+ res = shgo(test.f, test.bounds, args=args, constraints=test.cons,
+ n=n, iters=iters, callback=callback,
+ minimizer_kwargs=minimizer_kwargs, options=options,
+ sampling_method=sampling_method, workers=workers)
+
+ print(f'res = {res}')
+ logging.info(f'res = {res}')
+ if test.expected_x is not None:
+ np.testing.assert_allclose(res.x, test.expected_x,
+ rtol=test_atol,
+ atol=test_atol)
+
+ # (Optional tests)
+ if test.expected_fun is not None:
+ np.testing.assert_allclose(res.fun,
+ test.expected_fun,
+ atol=test_atol)
+
+ if test.expected_xl is not None:
+ np.testing.assert_allclose(res.xl,
+ test.expected_xl,
+ atol=test_atol)
+
+ if test.expected_funl is not None:
+ np.testing.assert_allclose(res.funl,
+ test.expected_funl,
+ atol=test_atol)
+ return
+
+
+# Base test functions:
+class TestShgoSobolTestFunctions:
+ """
+ Global optimisation tests with Sobol sampling:
+ """
+
+ # Sobol algorithm
+ def test_f1_1_sobol(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
+ run_test(test1_1)
+
+ def test_f1_2_sobol(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]"""
+ run_test(test1_2)
+
+ def test_f1_3_sobol(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(None, None),(None, None)]"""
+ options = {'disp': True}
+ run_test(test1_3, options=options)
+
+ def test_f2_1_sobol(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]"""
+ run_test(test2_1)
+
+ def test_f2_2_sobol(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]"""
+ run_test(test2_2)
+
+ def test_f3_sobol(self):
+ """NLP: Hock and Schittkowski problem 18"""
+ run_test(test3_1)
+
+ @pytest.mark.slow
+ def test_f4_sobol(self):
+ """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)"""
+ options = {'infty_constraints': False}
+ # run_test(test4_1, n=990, options=options)
+ run_test(test4_1, n=990 * 2, options=options)
+
+ def test_f5_1_sobol(self):
+ """NLP: Eggholder, multimodal"""
+ # run_test(test5_1, n=30)
+ run_test(test5_1, n=60)
+
+ def test_f5_2_sobol(self):
+ """NLP: Eggholder, multimodal"""
+ # run_test(test5_1, n=60, iters=5)
+ run_test(test5_1, n=60, iters=5)
+
+ # def test_t911(self):
+ # """1D tabletop function"""
+ # run_test(test11_1)
+
+
+class TestShgoSimplicialTestFunctions:
+ """
+ Global optimisation tests with Simplicial sampling:
+ """
+
+ def test_f1_1_simplicial(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
+ run_test(test1_1, n=1, sampling_method='simplicial')
+
+ def test_f1_2_simplicial(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]"""
+ run_test(test1_2, n=1, sampling_method='simplicial')
+
+ def test_f1_3_simplicial(self):
+ """Multivariate test function 1: x[0]**2 + x[1]**2
+ with bounds=[(None, None),(None, None)]"""
+ run_test(test1_3, n=5, sampling_method='simplicial')
+
+ def test_f2_1_simplicial(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]"""
+ options = {'minimize_every_iter': False}
+ run_test(test2_1, n=200, iters=7, options=options,
+ sampling_method='simplicial')
+
+ def test_f2_2_simplicial(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]"""
+ run_test(test2_2, n=1, sampling_method='simplicial')
+
+ def test_f3_simplicial(self):
+ """NLP: Hock and Schittkowski problem 18"""
+ run_test(test3_1, n=1, sampling_method='simplicial')
+
+ @pytest.mark.slow
+ def test_f4_simplicial(self):
+ """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)"""
+ run_test(test4_1, n=1, sampling_method='simplicial')
+
+ def test_lj_symmetry_old(self):
+ """LJ: Symmetry-constrained test function"""
+ options = {'symmetry': True,
+ 'disp': True}
+ args = (6,) # Number of atoms
+ run_test(testLJ, args=args, n=300,
+ options=options, iters=1,
+ sampling_method='simplicial')
+
+ def test_f5_1_lj_symmetry(self):
+ """LJ: Symmetry constrained test function"""
+ options = {'symmetry': [0, ] * 6,
+ 'disp': True}
+ args = (6,) # No. of atoms
+
+ run_test(testLJ, args=args, n=300,
+ options=options, iters=1,
+ sampling_method='simplicial')
+
+ def test_f5_2_cons_symmetry(self):
+ """Symmetry constrained test function"""
+ options = {'symmetry': [0, 0],
+ 'disp': True}
+
+ run_test(test1_1, n=200,
+ options=options, iters=1,
+ sampling_method='simplicial')
+
+ @pytest.mark.fail_slow(10)
+ def test_f5_3_cons_symmetry(self):
+ """Asymmetrically constrained test function"""
+ options = {'symmetry': [0, 0, 0, 3],
+ 'disp': True}
+
+ run_test(test_s, n=10000,
+ options=options,
+ iters=1,
+ sampling_method='simplicial')
+
+ @pytest.mark.skip("Not a test")
+ def test_f0_min_variance(self):
+ """Return a minimum on a perfectly symmetric problem, based on
+ gh10429"""
+ avg = 0.5 # Given average value of x
+ cons = {'type': 'eq', 'fun': lambda x: np.mean(x) - avg}
+
+ # Minimize the variance of x under the given constraint
+ res = shgo(np.var, bounds=6 * [(0, 1)], constraints=cons)
+ assert res.success
+ assert_allclose(res.fun, 0, atol=1e-15)
+ assert_allclose(res.x, 0.5)
+
+ @pytest.mark.skip("Not a test")
+ def test_f0_min_variance_1D(self):
+ """Return a minimum on a perfectly symmetric 1D problem, based on
+ gh10538"""
+
+ def fun(x):
+ return x * (x - 1.0) * (x - 0.5)
+
+ bounds = [(0, 1)]
+ res = shgo(fun, bounds=bounds)
+ ref = minimize_scalar(fun, bounds=bounds[0])
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, rtol=1e-6)
+
+# Argument test functions
+class TestShgoArguments:
+ def test_1_1_simpl_iter(self):
+ """Iterative simplicial sampling on TestFunction 1 (multivariate)"""
+ run_test(test1_2, n=None, iters=2, sampling_method='simplicial')
+
+ def test_1_2_simpl_iter(self):
+ """Iterative simplicial on TestFunction 2 (univariate)"""
+ options = {'minimize_every_iter': False}
+ run_test(test2_1, n=None, iters=9, options=options,
+ sampling_method='simplicial')
+
+ def test_2_1_sobol_iter(self):
+ """Iterative Sobol sampling on TestFunction 1 (multivariate)"""
+ run_test(test1_2, n=None, iters=1, sampling_method='sobol')
+
+ def test_2_2_sobol_iter(self):
+ """Iterative Sobol sampling on TestFunction 2 (univariate)"""
+ res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,
+ n=None, iters=1, sampling_method='sobol')
+
+ np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5)
+ np.testing.assert_allclose(res.fun, test2_1.expected_fun, atol=1e-5)
+
+ def test_3_1_disp_simplicial(self):
+ """Iterative sampling on TestFunction 1 and 2 (multi and univariate)
+ """
+
+ def callback_func(x):
+ print("Local minimization callback test")
+
+ for test in [test1_1, test2_1]:
+ shgo(test.f, test.bounds, iters=1,
+ sampling_method='simplicial',
+ callback=callback_func, options={'disp': True})
+ shgo(test.f, test.bounds, n=1, sampling_method='simplicial',
+ callback=callback_func, options={'disp': True})
+
+ def test_3_2_disp_sobol(self):
+ """Iterative sampling on TestFunction 1 and 2 (multi and univariate)"""
+
+ def callback_func(x):
+ print("Local minimization callback test")
+
+ for test in [test1_1, test2_1]:
+ shgo(test.f, test.bounds, iters=1, sampling_method='sobol',
+ callback=callback_func, options={'disp': True})
+
+ shgo(test.f, test.bounds, n=1, sampling_method='simplicial',
+ callback=callback_func, options={'disp': True})
+
+ def test_args_gh14589(self):
+ """Using `args` used to cause `shgo` to fail; see #14589, #15986,
+ #16506"""
+ res = shgo(func=lambda x, y, z: x * z + y, bounds=[(0, 3)], args=(1, 2)
+ )
+ ref = shgo(func=lambda x: 2 * x + 1, bounds=[(0, 3)])
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x)
+
+ def test_args_gh23517(self):
+ """
+ Checks that using `args` for func, jac and hess works
+ """
+ obj = MaratosTestArgs("a", 234)
+ obj.bounds = Bounds([-5, -5], [5, 5])
+ res2 = minimize(
+ obj.fun,
+ [4.0, 4.0],
+ constraints=obj.constr,
+ bounds=obj.bounds,
+ method='trust-constr',
+ args=("a", 234),
+ jac=obj.grad
+ )
+ assert_allclose(res2.x, obj.x_opt, atol=1e-6)
+
+ obj = MaratosTestArgs("a", 234)
+ obj.bounds = Bounds([-10., -10.], [10., 10.])
+ with warnings.catch_warnings():
+ # warnings are from initialization of NonlinearConstraint and
+ # poor initialization of the constraint by shgo
+ warnings.simplefilter(
+ "ignore",
+ (OptimizeWarning, RuntimeWarning)
+ )
+ res = shgo(
+ func=obj.fun,
+ bounds=obj.bounds,
+ args=("a", 234),
+ minimizer_kwargs={
+ "method": 'trust-constr',
+ "constraints": obj.constr,
+ "bounds": obj.bounds,
+ "jac": obj.grad,
+ "args": ("a", 234),
+ },
+ constraints=obj.constr,
+ sampling_method='sobol',
+ )
+ assert_allclose(res.x, obj.x_opt, atol=1e-6)
+
+ res = shgo(
+ func=obj.fun,
+ bounds=obj.bounds,
+ args=("a", 234),
+ minimizer_kwargs={
+ "method": 'trust-constr',
+ "constraints": obj.constr,
+ "bounds": obj.bounds,
+ "jac": obj.grad,
+ "hess": obj.hess,
+ },
+ constraints=obj.constr,
+ sampling_method='sobol',
+ )
+ assert_allclose(res.x, obj.x_opt, atol=1e-6)
+
+ @pytest.mark.slow
+ def test_4_1_known_f_min(self):
+ """Test known function minima stopping criteria"""
+ # Specify known function value
+ options = {'f_min': test4_1.expected_fun,
+ 'f_tol': 1e-6,
+ 'minimize_every_iter': True}
+ # TODO: Make default n higher for faster tests
+ run_test(test4_1, n=None, test_atol=1e-5, options=options,
+ sampling_method='simplicial')
+
+ @pytest.mark.slow
+ def test_4_2_known_f_min(self):
+ """Test Global mode limiting local evaluations"""
+ options = { # Specify known function value
+ 'f_min': test4_1.expected_fun,
+ 'f_tol': 1e-6,
+ # Specify number of local iterations to perform
+ 'minimize_every_iter': True,
+ 'local_iter': 1}
+
+ run_test(test4_1, n=None, test_atol=1e-5, options=options,
+ sampling_method='simplicial')
+
+ def test_4_4_known_f_min(self):
+ """Test Global mode limiting local evaluations for 1D funcs"""
+ options = { # Specify known function value
+ 'f_min': test2_1.expected_fun,
+ 'f_tol': 1e-6,
+ # Specify number of local iterations to perform+
+ 'minimize_every_iter': True,
+ 'local_iter': 1,
+ 'infty_constraints': False}
+
+ res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,
+ n=None, iters=None, options=options,
+ sampling_method='sobol')
+ np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5)
+
+ def test_5_1_simplicial_argless(self):
+ """Test Default simplicial sampling settings on TestFunction 1"""
+ res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons)
+ np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5)
+
+ def test_5_2_sobol_argless(self):
+ """Test Default sobol sampling settings on TestFunction 1"""
+ res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons,
+ sampling_method='sobol')
+ np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5)
+
+ def test_6_1_simplicial_max_iter(self):
+ """Test that maximum iteration option works on TestFunction 3"""
+ options = {'max_iter': 2}
+ res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,
+ options=options, sampling_method='simplicial')
+ np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5)
+ np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)
+
+ def test_6_2_simplicial_min_iter(self):
+ """Test that maximum iteration option works on TestFunction 3"""
+ options = {'min_iter': 2}
+ res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,
+ options=options, sampling_method='simplicial')
+ np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5)
+ np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)
+
+ def test_7_1_minkwargs(self):
+ """Test the minimizer_kwargs arguments for solvers with constraints"""
+ # Test solvers
+ for solver in ['COBYLA', 'COBYQA', 'SLSQP']:
+ # Note that passing global constraints to SLSQP is tested in other
+ # unittests which run test4_1 normally
+ minimizer_kwargs = {'method': solver,
+ 'constraints': test3_1.cons}
+ run_test(test3_1, n=100, test_atol=1e-3,
+ minimizer_kwargs=minimizer_kwargs,
+ sampling_method='sobol')
+
+ def test_7_2_minkwargs(self):
+ """Test the minimizer_kwargs default inits"""
+ minimizer_kwargs = {'ftol': 1e-5}
+ options = {'disp': True} # For coverage purposes
+ SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0],
+ minimizer_kwargs=minimizer_kwargs, options=options)
+
+ def test_7_3_minkwargs(self):
+ """Test minimizer_kwargs arguments for solvers without constraints"""
+ for solver in ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG',
+ 'L-BFGS-B', 'TNC', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov']:
+ def jac(x):
+ return np.array([2 * x[0], 2 * x[1]]).T
+
+ def hess(x):
+ return np.array([[2, 0], [0, 2]])
+
+ minimizer_kwargs = {'method': solver,
+ 'jac': jac,
+ 'hess': hess}
+ logging.info(f"Solver = {solver}")
+ logging.info("=" * 100)
+ run_test(test1_1, n=100, test_atol=1e-3,
+ minimizer_kwargs=minimizer_kwargs,
+ sampling_method='sobol')
+
+ def test_8_homology_group_diff(self):
+ options = {'minhgrd': 1,
+ 'minimize_every_iter': True}
+
+ run_test(test1_1, n=None, iters=None, options=options,
+ sampling_method='simplicial')
+
+ def test_9_cons_g(self):
+ """Test single function constraint passing"""
+ SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0])
+
+ def test_10_finite_time(self):
+ """Test single function constraint passing"""
+ options = {'maxtime': 1e-15}
+
+ def f(x):
+ time.sleep(1e-14)
+ return 0.0
+
+ res = shgo(f, test1_1.bounds, iters=5, options=options)
+ # Assert that only 1 rather than 5 requested iterations ran:
+ assert res.nit == 1
+
+ def test_11_f_min_0(self):
+ """Test to cover the case where f_lowest == 0"""
+ options = {'f_min': 0.0,
+ 'disp': True}
+ res = shgo(test1_2.f, test1_2.bounds, n=10, iters=None,
+ options=options, sampling_method='sobol')
+ np.testing.assert_equal(0, res.x[0])
+ np.testing.assert_equal(0, res.x[1])
+
+ # @nottest
+ @pytest.mark.skip(reason="no way of currently testing this")
+ def test_12_sobol_inf_cons(self):
+ """Test to cover the case where f_lowest == 0"""
+ # TODO: This test doesn't cover anything new, it is unknown what the
+ # original test was intended for as it was never complete. Delete or
+ # replace in the future.
+ options = {'maxtime': 1e-15,
+ 'f_min': 0.0}
+ res = shgo(test1_2.f, test1_2.bounds, n=1, iters=None,
+ options=options, sampling_method='sobol')
+ np.testing.assert_equal(0.0, res.fun)
+
+ def test_13_high_sobol(self):
+ """Test init of high-dimensional sobol sequences"""
+
+ def f(x):
+ return 0
+
+ bounds = [(None, None), ] * 41
+ SHGOc = SHGO(f, bounds, sampling_method='sobol')
+ # SHGOc.sobol_points(2, 50)
+ SHGOc.sampling_function(2, 50)
+
+ def test_14_local_iter(self):
+ """Test limited local iterations for a pseudo-global mode"""
+ options = {'local_iter': 4}
+ run_test(test5_1, n=60, options=options)
+
+ def test_15_min_every_iter(self):
+ """Test minimize every iter options and cover function cache"""
+ options = {'minimize_every_iter': True}
+ run_test(test1_1, n=1, iters=7, options=options,
+ sampling_method='sobol')
+
+ def test_16_disp_bounds_minimizer(self, capsys):
+ """Test disp=True with minimizers that do not support bounds """
+ options = {'disp': True}
+ minimizer_kwargs = {'method': 'nelder-mead'}
+ run_test(test1_2, sampling_method='simplicial',
+ options=options, minimizer_kwargs=minimizer_kwargs)
+
+ def test_17_custom_sampling(self):
+ """Test the functionality to add custom sampling methods to shgo"""
+
+ def sample(n, d):
+ return np.random.uniform(size=(n, d))
+
+ run_test(test1_1, n=30, sampling_method=sample)
+
+ def test_18_bounds_class(self):
+ # test that new and old bounds yield same result
+ def f(x):
+ return np.square(x).sum()
+
+ lb = [-6., 1., -5.]
+ ub = [-1., 3., 5.]
+ bounds_old = list(zip(lb, ub))
+ bounds_new = Bounds(lb, ub)
+
+ res_old_bounds = shgo(f, bounds_old)
+ res_new_bounds = shgo(f, bounds_new)
+
+ assert res_new_bounds.nfev == res_old_bounds.nfev
+ assert res_new_bounds.message == res_old_bounds.message
+ assert res_new_bounds.success == res_old_bounds.success
+ x_opt = np.array([-1., 1., 0.])
+ np.testing.assert_allclose(res_new_bounds.x, x_opt)
+ np.testing.assert_allclose(res_new_bounds.x, res_old_bounds.x)
+
+ @pytest.mark.fail_slow(10)
+ def test_19_parallelization(self):
+ """Test the functionality to add custom sampling methods to shgo"""
+
+ with Pool(2) as p:
+ run_test(test1_1, n=30, workers=p.map) # Constrained
+ run_test(test1_1, n=30, workers=map) # Constrained
+ with Pool(2) as p:
+ run_test(test_s, n=30, workers=p.map) # Unconstrained
+ run_test(test_s, n=30, workers=map) # Unconstrained
+
+ def test_20_constrained_args(self):
+ """Test that constraints can be passed to arguments"""
+
+ def eggholder(x):
+ return (
+ -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0] / 2.0 + (x[1] + 47.0))))
+ - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
+ )
+
+ def f(x): # (cattle-feed)
+ return 24.55 * x[0] + 26.75 * x[1] + 39 * x[2] + 40.50 * x[3]
+
+ bounds = [(0, 1.0), ] * 4
+
+ def g1_modified(x, i):
+ return i * 2.3 * x[0] + i * 5.6 * x[1] + 11.1 * x[2] + 1.3 * x[
+ 3] - 5 # >=0
+
+ def g2(x):
+ return (
+ 12*x[0] + 11.9*x[1] + 41.8*x[2] + 52.1*x[3] - 21
+ - 1.645*np.sqrt(
+ 0.28*x[0]**2 + 0.19*x[1]**2 + 20.5*x[2]**2 + 0.62*x[3]**2
+ )
+ ) # >=0
+
+ def h1(x):
+ return x[0] + x[1] + x[2] + x[3] - 1 # == 0
+
+ cons = ({'type': 'ineq', 'fun': g1_modified, "args": (0,)},
+ {'type': 'ineq', 'fun': g2},
+ {'type': 'eq', 'fun': h1})
+
+ shgo(f, bounds, n=300, iters=1, constraints=cons)
+ # using constrain with arguments AND sampling method sobol
+ shgo(f, bounds, n=300, iters=1, constraints=cons,
+ sampling_method='sobol')
+
+ def test_21_1_jac_true(self):
+ """Test that shgo can handle objective functions that return the
+ gradient alongside the objective value. Fixes gh-13547"""
+ # previous
+ def func(x):
+ return np.sum(np.power(x, 2)), 2 * x
+
+ min_kwds = {"method": "SLSQP", "jac": True}
+ opt_kwds = {"jac": True}
+ shgo(
+ func,
+ bounds=[[-1, 1], [1, 2]],
+ n=100, iters=5,
+ sampling_method="sobol",
+ minimizer_kwargs=min_kwds,
+ options=opt_kwds
+ )
+ assert min_kwds['jac'] is True
+ assert "jac" in opt_kwds
+
+ # new
+ def func(x):
+ return np.sum(x ** 2), 2 * x
+
+ bounds = [[-1, 1], [1, 2], [-1, 1], [1, 2], [0, 3]]
+
+ res = shgo(func, bounds=bounds, sampling_method="sobol",
+ minimizer_kwargs={'method': 'SLSQP', 'jac': True})
+ ref = minimize(func, x0=[1, 1, 1, 1, 1], bounds=bounds,
+ jac=True)
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, atol=1e-15)
+
+ # Testing the passing of jac via options dict
+ res = shgo(func, bounds=bounds, sampling_method="sobol",
+ minimizer_kwargs={'method': 'SLSQP'},
+ options={'jac': True})
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, atol=1e-15)
+
+ @pytest.mark.parametrize('derivative', ['jac', 'hess', 'hessp'])
+ def test_21_2_derivative_options(self, derivative):
+ """shgo used to raise an error when passing `options` with 'jac'
+ # see gh-12963. check that this is resolved
+ """
+
+ def objective(x):
+ return 3 * x[0] * x[0] + 2 * x[0] + 5
+
+ def gradient(x):
+ return 6 * x[0] + 2
+
+ def hess(x):
+ return 6
+
+ def hessp(x, p):
+ return 6 * p
+
+ derivative_funcs = {'jac': gradient, 'hess': hess, 'hessp': hessp}
+ options = {derivative: derivative_funcs[derivative]}
+ minimizer_kwargs = {'method': 'trust-constr'}
+
+ bounds = [(-100, 100)]
+ res = shgo(objective, bounds, minimizer_kwargs=minimizer_kwargs,
+ options=options)
+ ref = minimize(objective, x0=[0], bounds=bounds, **minimizer_kwargs,
+ **options)
+
+ assert res.success
+ np.testing.assert_allclose(res.fun, ref.fun)
+ np.testing.assert_allclose(res.x, ref.x)
+
+ def test_21_3_hess_options_rosen(self):
+ """Ensure the Hessian gets passed correctly to the local minimizer
+ routine. Previous report gh-14533.
+ """
+ bounds = [(0, 1.6), (0, 1.6), (0, 1.4), (0, 1.4), (0, 1.4)]
+ options = {'jac': rosen_der, 'hess': rosen_hess}
+ minimizer_kwargs = {'method': 'Newton-CG'}
+ res = shgo(rosen, bounds, minimizer_kwargs=minimizer_kwargs,
+ options=options)
+ ref = minimize(rosen, np.zeros(5), method='Newton-CG',
+ **options)
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, atol=1e-15)
+
+ def test_21_arg_tuple_sobol(self):
+ """shgo used to raise an error when passing `args` with Sobol sampling
+ # see gh-12114. check that this is resolved"""
+
+ def fun(x, k):
+ return x[0] ** k
+
+ constraints = ({'type': 'ineq', 'fun': lambda x: x[0] - 1})
+
+ bounds = [(0, 10)]
+ res = shgo(fun, bounds, args=(1,), constraints=constraints,
+ sampling_method='sobol')
+ ref = minimize(fun, np.zeros(1), bounds=bounds, args=(1,),
+ constraints=constraints)
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x)
+
+
+# Failure test functions
+class TestShgoFailures:
+ def test_1_maxiter(self):
+ """Test failure on insufficient iterations"""
+ options = {'maxiter': 2}
+ res = shgo(test4_1.f, test4_1.bounds, n=2, iters=None,
+ options=options, sampling_method='sobol')
+
+ np.testing.assert_equal(False, res.success)
+ # np.testing.assert_equal(4, res.nfev)
+ np.testing.assert_equal(4, res.tnev)
+
+ def test_2_sampling(self):
+ """Rejection of unknown sampling method"""
+ assert_raises(ValueError, shgo, test1_1.f, test1_1.bounds,
+ sampling_method='not_Sobol')
+
+ def test_3_1_no_min_pool_sobol(self):
+ """Check that the routine stops when no minimiser is found
+ after maximum specified function evaluations"""
+ options = {'maxfev': 10,
+ # 'maxev': 10,
+ 'disp': True}
+ res = shgo(test_table.f, test_table.bounds, n=3, options=options,
+ sampling_method='sobol')
+ np.testing.assert_equal(False, res.success)
+ # np.testing.assert_equal(9, res.nfev)
+ np.testing.assert_equal(12, res.nfev)
+
+ def test_3_2_no_min_pool_simplicial(self):
+ """Check that the routine stops when no minimiser is found
+ after maximum specified sampling evaluations"""
+ options = {'maxev': 10,
+ 'disp': True}
+ res = shgo(test_table.f, test_table.bounds, n=3, options=options,
+ sampling_method='simplicial')
+ np.testing.assert_equal(False, res.success)
+
+ def test_4_1_bound_err(self):
+ """Specified bounds ub > lb"""
+ bounds = [(6, 3), (3, 5)]
+ assert_raises(ValueError, shgo, test1_1.f, bounds)
+
+ def test_4_2_bound_err(self):
+ """Specified bounds are of the form (lb, ub)"""
+ bounds = [(3, 5, 5), (3, 5)]
+ assert_raises(ValueError, shgo, test1_1.f, bounds)
+
+ def test_5_1_1_infeasible_sobol(self):
+ """Ensures the algorithm terminates on infeasible problems
+ after maxev is exceeded. Use infty constraints option"""
+ options = {'maxev': 100,
+ 'disp': True}
+
+ res = shgo(test_infeasible.f, test_infeasible.bounds,
+ constraints=test_infeasible.cons, n=100, options=options,
+ sampling_method='sobol')
+
+ np.testing.assert_equal(False, res.success)
+
+ def test_5_1_2_infeasible_sobol(self):
+ """Ensures the algorithm terminates on infeasible problems
+ after maxev is exceeded. Do not use infty constraints option"""
+ options = {'maxev': 100,
+ 'disp': True,
+ 'infty_constraints': False}
+
+ res = shgo(test_infeasible.f, test_infeasible.bounds,
+ constraints=test_infeasible.cons, n=100, options=options,
+ sampling_method='sobol')
+
+ np.testing.assert_equal(False, res.success)
+
+ def test_5_2_infeasible_simplicial(self):
+ """Ensures the algorithm terminates on infeasible problems
+ after maxev is exceeded."""
+ options = {'maxev': 1000,
+ 'disp': False}
+
+ res = shgo(test_infeasible.f, test_infeasible.bounds,
+ constraints=test_infeasible.cons, n=100, options=options,
+ sampling_method='simplicial')
+
+ np.testing.assert_equal(False, res.success)
+
+ def test_6_1_lower_known_f_min(self):
+ """Test Global mode limiting local evaluations with f* too high"""
+ options = { # Specify known function value
+ 'f_min': test2_1.expected_fun + 2.0,
+ 'f_tol': 1e-6,
+ # Specify number of local iterations to perform+
+ 'minimize_every_iter': True,
+ 'local_iter': 1,
+ 'infty_constraints': False}
+ args = (test2_1.f, test2_1.bounds)
+ kwargs = {'constraints': test2_1.cons,
+ 'n': None,
+ 'iters': None,
+ 'options': options,
+ 'sampling_method': 'sobol'
+ }
+ warns(UserWarning, shgo, *args, **kwargs)
+
+ def test(self):
+ from scipy.optimize import rosen, shgo
+ bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
+
+ def fun(x):
+ fun.nfev += 1
+ return rosen(x)
+
+ fun.nfev = 0
+
+ result = shgo(fun, bounds)
+ print(result.x, result.fun, fun.nfev) # 50
+
+
+# Returns
+class TestShgoReturns:
+ def test_1_nfev_simplicial(self):
+ bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
+
+ def fun(x):
+ fun.nfev += 1
+ return rosen(x)
+
+ fun.nfev = 0
+
+ result = shgo(fun, bounds)
+ np.testing.assert_equal(fun.nfev, result.nfev)
+
+ def test_1_nfev_sobol(self):
+ bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
+
+ def fun(x):
+ fun.nfev += 1
+ return rosen(x)
+
+ fun.nfev = 0
+
+ result = shgo(fun, bounds, sampling_method='sobol')
+ np.testing.assert_equal(fun.nfev, result.nfev)
+
+
+def test_vector_constraint():
+ # gh15514
+ def quad(x):
+ x = np.asarray(x)
+ return [np.sum(x ** 2)]
+
+ nlc = NonlinearConstraint(quad, [2.2], [3])
+ oldc = new_constraint_to_old(nlc, np.array([1.0, 1.0]))
+
+ res = shgo(rosen, [(0, 10), (0, 10)], constraints=oldc, sampling_method='sobol')
+ assert np.all(np.sum((res.x)**2) >= 2.2)
+ assert np.all(np.sum((res.x) ** 2) <= 3.0)
+ assert res.success
+
+
+@pytest.mark.filterwarnings("ignore:delta_grad")
+def test_trust_constr():
+ def quad(x):
+ x = np.asarray(x)
+ return [np.sum(x ** 2)]
+
+ nlc = NonlinearConstraint(quad, [2.6], [3])
+ minimizer_kwargs = {'method': 'trust-constr'}
+ # note that we don't supply the constraints in minimizer_kwargs,
+ # so if the final result obeys the constraints we know that shgo
+ # passed them on to 'trust-constr'
+ res = shgo(
+ rosen,
+ [(0, 10), (0, 10)],
+ constraints=nlc,
+ sampling_method='sobol',
+ minimizer_kwargs=minimizer_kwargs
+ )
+ assert np.all(np.sum((res.x)**2) >= 2.6)
+ assert np.all(np.sum((res.x) ** 2) <= 3.0)
+ assert res.success
+
+
+def test_equality_constraints():
+ # gh16260
+ bounds = [(0.9, 4.0)] * 2 # Constrain probabilities to 0 and 1.
+
+ def faulty(x):
+ return x[0] + x[1]
+
+ nlc = NonlinearConstraint(faulty, 3.9, 3.9)
+ res = shgo(rosen, bounds=bounds, constraints=nlc)
+ assert_allclose(np.sum(res.x), 3.9)
+
+ def faulty(x):
+ return x[0] + x[1] - 3.9
+
+ constraints = {'type': 'eq', 'fun': faulty}
+ res = shgo(rosen, bounds=bounds, constraints=constraints)
+ assert_allclose(np.sum(res.x), 3.9)
+
+ bounds = [(0, 1.0)] * 4
+ # sum of variable should equal 1.
+ def faulty(x):
+ return x[0] + x[1] + x[2] + x[3] - 1
+
+ # options = {'minimize_every_iter': True, 'local_iter':10}
+ constraints = {'type': 'eq', 'fun': faulty}
+ res = shgo(
+ lambda x: - np.prod(x),
+ bounds=bounds,
+ constraints=constraints,
+ sampling_method='sobol'
+ )
+ assert_allclose(np.sum(res.x), 1.0)
+
+def test_gh16971():
+ def cons(x):
+ return np.sum(x**2) - 0
+
+ c = {'fun': cons, 'type': 'ineq'}
+ minimizer_kwargs = {
+ 'method': 'COBYLA',
+ 'options': {'rhobeg': 5, 'tol': 5e-1, 'catol': 0.05}
+ }
+
+ s = SHGO(
+ rosen, [(0, 10)]*2, constraints=c, minimizer_kwargs=minimizer_kwargs
+ )
+
+ assert s.minimizer_kwargs['method'].lower() == 'cobyla'
+ assert s.minimizer_kwargs['options']['catol'] == 0.05
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__spectral.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..00f233671133b1ce5a3f7cc25673569fb003326c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test__spectral.py
@@ -0,0 +1,225 @@
+import itertools
+
+import numpy as np
+from numpy import exp
+from numpy.testing import assert_, assert_equal
+
+from scipy.optimize import root
+
+
+def test_performance():
+ # Compare performance results to those listed in
+ # [Cheng & Li, IMA J. Num. An. 29, 814 (2008)]
+ # and
+ # [W. La Cruz, J.M. Martinez, M. Raydan, Math. Comp. 75, 1429 (2006)].
+ # and those produced by dfsane.f from M. Raydan's website.
+ #
+ # Where the results disagree, the largest limits are taken.
+
+ e_a = 1e-5
+ e_r = 1e-4
+
+ table_1 = [
+ dict(F=F_1, x0=x0_1, n=1000, nit=5, nfev=5),
+ dict(F=F_1, x0=x0_1, n=10000, nit=2, nfev=2),
+ dict(F=F_2, x0=x0_2, n=500, nit=11, nfev=11),
+ dict(F=F_2, x0=x0_2, n=2000, nit=11, nfev=11),
+ # dict(F=F_4, x0=x0_4, n=999, nit=243, nfev=1188) removed:
+ # too sensitive to rounding errors
+ # Results from dfsane.f; papers list nit=3, nfev=3
+ dict(F=F_6, x0=x0_6, n=100, nit=6, nfev=6),
+ # Must have n%3==0, typo in papers?
+ dict(F=F_7, x0=x0_7, n=99, nit=23, nfev=29),
+ # Must have n%3==0, typo in papers?
+ dict(F=F_7, x0=x0_7, n=999, nit=23, nfev=29),
+ # Results from dfsane.f; papers list nit=nfev=6?
+ dict(F=F_9, x0=x0_9, n=100, nit=12, nfev=18),
+ dict(F=F_9, x0=x0_9, n=1000, nit=12, nfev=18),
+ # Results from dfsane.f; papers list nit=2, nfev=12
+ dict(F=F_10, x0=x0_10, n=1000, nit=5, nfev=5),
+ ]
+
+ # Check also scaling invariance
+ for xscale, yscale, line_search in itertools.product(
+ [1.0, 1e-10, 1e10], [1.0, 1e-10, 1e10], ['cruz', 'cheng']
+ ):
+ for problem in table_1:
+ n = problem['n']
+ def func(x, n):
+ return yscale * problem['F'](x / xscale, n)
+ args = (n,)
+ x0 = problem['x0'](n) * xscale
+
+ fatol = np.sqrt(n) * e_a * yscale + e_r * np.linalg.norm(func(x0, n))
+
+ sigma_eps = 1e-10 * min(yscale/xscale, xscale/yscale)
+ sigma_0 = xscale/yscale
+
+ with np.errstate(over='ignore'):
+ sol = root(func, x0, args=args,
+ options=dict(ftol=0, fatol=fatol, maxfev=problem['nfev'] + 1,
+ sigma_0=sigma_0, sigma_eps=sigma_eps,
+ line_search=line_search),
+ method='DF-SANE')
+
+ err_msg = repr(
+ [xscale, yscale, line_search, problem, np.linalg.norm(func(sol.x, n)),
+ fatol, sol.success, sol.nit, sol.nfev]
+ )
+ assert sol.success, err_msg
+ # nfev+1: dfsane.f doesn't count first eval
+ assert sol.nfev <= problem['nfev'] + 1, err_msg
+ assert sol.nit <= problem['nit'], err_msg
+ assert np.linalg.norm(func(sol.x, n)) <= fatol, err_msg
+
+
+def test_complex():
+ def func(z):
+ return z**2 - 1 + 2j
+ x0 = 2.0j
+
+ ftol = 1e-4
+ sol = root(func, x0, tol=ftol, method='DF-SANE')
+
+ assert_(sol.success)
+
+ f0 = np.linalg.norm(func(x0))
+ fx = np.linalg.norm(func(sol.x))
+ assert_(fx <= ftol*f0)
+
+
+def test_linear_definite():
+ # The DF-SANE paper proves convergence for "strongly isolated"
+ # solutions.
+ #
+ # For linear systems F(x) = A x - b = 0, with A positive or
+ # negative definite, the solution is strongly isolated.
+
+ def check_solvability(A, b, line_search='cruz'):
+ def func(x):
+ return A.dot(x) - b
+ xp = np.linalg.solve(A, b)
+ eps = np.linalg.norm(func(xp)) * 1e3
+ sol = root(
+ func, b,
+ options=dict(fatol=eps, ftol=0, maxfev=17523, line_search=line_search),
+ method='DF-SANE',
+ )
+ assert_(sol.success)
+ assert_(np.linalg.norm(func(sol.x)) <= eps)
+
+ n = 90
+
+ # Test linear pos.def. system
+ A = np.arange(n*n).reshape(n, n)
+ A = A + n*n * np.diag(1 + np.arange(n))
+ assert_(np.linalg.eigvals(A).min() > 0)
+ b = np.arange(n) * 1.0
+ check_solvability(A, b, 'cruz')
+ check_solvability(A, b, 'cheng')
+
+ # Test linear neg.def. system
+ check_solvability(-A, b, 'cruz')
+ check_solvability(-A, b, 'cheng')
+
+
+def test_shape():
+ def f(x, arg):
+ return x - arg
+
+ for dt in [float, complex]:
+ x = np.zeros([2,2])
+ arg = np.ones([2,2], dtype=dt)
+
+ sol = root(f, x, args=(arg,), method='DF-SANE')
+ assert_(sol.success)
+ assert_equal(sol.x.shape, x.shape)
+
+
+# Some of the test functions and initial guesses listed in
+# [W. La Cruz, M. Raydan. Optimization Methods and Software, 18, 583 (2003)]
+
+def F_1(x, n):
+ g = np.zeros([n])
+ i = np.arange(2, n+1)
+ g[0] = exp(x[0] - 1) - 1
+ g[1:] = i*(exp(x[1:] - 1) - x[1:])
+ return g
+
+def x0_1(n):
+ x0 = np.empty([n])
+ x0.fill(n/(n-1))
+ return x0
+
+def F_2(x, n):
+ g = np.zeros([n])
+ i = np.arange(2, n+1)
+ g[0] = exp(x[0]) - 1
+ g[1:] = 0.1*i*(exp(x[1:]) + x[:-1] - 1)
+ return g
+
+def x0_2(n):
+ x0 = np.empty([n])
+ x0.fill(1/n**2)
+ return x0
+
+
+def F_4(x, n): # skip name check
+ assert_equal(n % 3, 0)
+ g = np.zeros([n])
+ # Note: the first line is typoed in some of the references;
+ # correct in original [Gasparo, Optimization Meth. 13, 79 (2000)]
+ g[::3] = 0.6 * x[::3] + 1.6 * x[1::3]**3 - 7.2 * x[1::3]**2 + 9.6 * x[1::3] - 4.8
+ g[1::3] = (0.48 * x[::3] - 0.72 * x[1::3]**3 + 3.24 * x[1::3]**2 - 4.32 * x[1::3]
+ - x[2::3] + 0.2 * x[2::3]**3 + 2.16)
+ g[2::3] = 1.25 * x[2::3] - 0.25*x[2::3]**3
+ return g
+
+
+def x0_4(n): # skip name check
+ assert_equal(n % 3, 0)
+ x0 = np.array([-1, 1/2, -1] * (n//3))
+ return x0
+
+def F_6(x, n):
+ c = 0.9
+ mu = (np.arange(1, n+1) - 0.5)/n
+ return x - 1/(1 - c/(2*n) * (mu[:,None]*x / (mu[:,None] + mu)).sum(axis=1))
+
+def x0_6(n):
+ return np.ones([n])
+
+def F_7(x, n):
+ assert_equal(n % 3, 0)
+
+ def phi(t):
+ v = 0.5*t - 2
+ v[t > -1] = ((-592*t**3 + 888*t**2 + 4551*t - 1924)/1998)[t > -1]
+ v[t >= 2] = (0.5*t + 2)[t >= 2]
+ return v
+ g = np.zeros([n])
+ g[::3] = 1e4 * x[1::3]**2 - 1
+ g[1::3] = exp(-x[::3]) + exp(-x[1::3]) - 1.0001
+ g[2::3] = phi(x[2::3])
+ return g
+
+def x0_7(n):
+ assert_equal(n % 3, 0)
+ return np.array([1e-3, 18, 1] * (n//3))
+
+def F_9(x, n):
+ g = np.zeros([n])
+ i = np.arange(2, n)
+ g[0] = x[0]**3/3 + x[1]**2/2
+ g[1:-1] = -x[1:-1]**2/2 + i*x[1:-1]**3/3 + x[2:]**2/2
+ g[-1] = -x[-1]**2/2 + n*x[-1]**3/3
+ return g
+
+def x0_9(n):
+ return np.ones([n])
+
+def F_10(x, n):
+ return np.log(1 + x) - x/n
+
+def x0_10(n):
+ return np.ones([n])
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_bracket.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..09ebbf58024554945c60f32cf891c7ddcdc0c34f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_bracket.py
@@ -0,0 +1,916 @@
+import pytest
+
+import numpy as np
+
+from scipy.optimize._bracket import _ELIMITS
+from scipy.optimize.elementwise import (bracket_root, bracket_minimum,
+ find_root, find_minimum)
+import scipy._lib._elementwise_iterative_method as eim
+from scipy import stats
+from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal,
+ xp_assert_less)
+from scipy._lib._array_api import xp_ravel, make_xp_test_case
+
+
+# These tests were originally written for the private `optimize._bracket`
+# interfaces, but now we want the tests to check the behavior of the public
+# `optimize.elementwise` interfaces. Therefore, rather than importing
+# `_bracket_root`/`_bracket_minimum` from `_bracket.py`, we import
+# `bracket_root`/`bracket_minimum` from `optimize.elementwise` and wrap those
+# functions to conform to the private interface. This may look a little strange,
+# since it effectively just inverts the interface transformation done within the
+# `bracket_root`/`bracket_minimum` functions, but it allows us to run the original,
+# unmodified tests on the public interfaces, simplifying the PR that adds
+# the public interfaces. We'll refactor this when we want to @parametrize the
+# tests over multiple `method`s.
+def _bracket_root(*args, **kwargs):
+ res = bracket_root(*args, **kwargs)
+ res.xl, res.xr = res.bracket
+ res.fl, res.fr = res.f_bracket
+ del res.bracket
+ del res.f_bracket
+ return res
+
+
+def _bracket_minimum(*args, **kwargs):
+ res = bracket_minimum(*args, **kwargs)
+ res.xl, res.xm, res.xr = res.bracket
+ res.fl, res.fm, res.fr = res.f_bracket
+ del res.bracket
+ del res.f_bracket
+ return res
+
+
+@make_xp_test_case(bracket_root)
+class TestBracketRoot:
+ @pytest.mark.parametrize("seed", (615655101, 3141866013, 238075752))
+ @pytest.mark.parametrize("use_xmin", (False, True))
+ @pytest.mark.parametrize("other_side", (False, True))
+ @pytest.mark.parametrize("fix_one_side", (False, True))
+ def test_nfev_expected(self, seed, use_xmin, other_side, fix_one_side, xp):
+ # Property-based test to confirm that _bracket_root is behaving as
+ # expected. The basic case is when root < a < b.
+ # The number of times bracket expands (per side) can be found by
+ # setting the expression for the left endpoint of the bracket to the
+ # root of f (x=0), solving for i, and rounding up. The corresponding
+ # lower and upper ends of the bracket are found by plugging this back
+ # into the expression for the ends of the bracket.
+ # `other_side=True` is the case that a < b < root
+ # Special cases like a < root < b are tested separately
+ rng = np.random.default_rng(seed)
+ xl0, d, factor = xp.asarray(rng.random(size=3) * [1e5, 10, 5])
+ factor = 1 + factor # factor must be greater than 1
+ xr0 = xl0 + d # xr0 must be greater than a in basic case
+
+ def f(x):
+ f.count += 1
+ return x # root is 0
+
+ if use_xmin:
+ xmin = xp.asarray(-rng.random())
+ n = xp.ceil(xp.log(-(xl0 - xmin) / xmin) / xp.log(factor))
+ l, u = xmin + (xl0 - xmin)*factor**-n, xmin + (xl0 - xmin)*factor**-(n - 1)
+ kwargs = dict(xl0=xl0, xr0=xr0, factor=factor, xmin=xmin)
+ else:
+ n = xp.ceil(xp.log(xr0/d) / xp.log(factor))
+ l, u = xr0 - d*factor**n, xr0 - d*factor**(n-1)
+ kwargs = dict(xl0=xl0, xr0=xr0, factor=factor)
+
+ if other_side:
+ kwargs['xl0'], kwargs['xr0'] = -kwargs['xr0'], -kwargs['xl0']
+ l, u = -u, -l
+ if 'xmin' in kwargs:
+ kwargs['xmax'] = -kwargs.pop('xmin')
+
+ if fix_one_side:
+ if other_side:
+ kwargs['xmin'] = -xr0
+ else:
+ kwargs['xmax'] = xr0
+
+ f.count = 0
+ res = _bracket_root(f, **kwargs)
+
+ # Compare reported number of function evaluations `nfev` against
+ # reported `nit`, actual function call count `f.count`, and theoretical
+ # number of expansions `n`.
+ # When both sides are free, these get multiplied by 2 because function
+ # is evaluated on the left and the right each iteration.
+ # When one side is fixed, however, we add one: on the right side, the
+ # function gets evaluated once at b.
+ # Add 1 to `n` and `res.nit` because function evaluations occur at
+ # iterations *0*, 1, ..., `n`. Subtract 1 from `f.count` because
+ # function is called separately for left and right in iteration 0.
+ if not fix_one_side:
+ assert res.nfev == 2*(res.nit+1) == 2*(f.count-1) == 2*(n + 1)
+ else:
+ assert res.nfev == (res.nit+1)+1 == (f.count-1)+1 == (n+1)+1
+
+ # Compare reported bracket to theoretical bracket and reported function
+ # values to function evaluated at bracket.
+ bracket = xp.asarray([res.xl, res.xr])
+ xp_assert_close(bracket, xp.asarray([l, u]))
+ f_bracket = xp.asarray([res.fl, res.fr])
+ xp_assert_close(f_bracket, f(bracket))
+
+ # Check that bracket is valid and that status and success are correct
+ assert res.xr > res.xl
+ signs = xp.sign(f_bracket)
+ assert signs[0] == -signs[1]
+ assert res.status == 0
+ assert res.success
+
+ def f(self, q, p):
+ return stats._stats_py._SimpleNormal().cdf(q) - p
+
+ @pytest.mark.parametrize('p', [0.6, np.linspace(0.05, 0.95, 10)])
+ @pytest.mark.parametrize('xmin', [-5, None])
+ @pytest.mark.parametrize('xmax', [5, None])
+ @pytest.mark.parametrize('factor', [1.2, 2])
+ def test_basic(self, p, xmin, xmax, factor, xp):
+ # Test basic functionality to bracket root (distribution PPF)
+ res = _bracket_root(self.f, xp.asarray(-0.01), 0.01, xmin=xmin, xmax=xmax,
+ factor=factor, args=(xp.asarray(p),))
+ xp_assert_equal(-xp.sign(res.fl), xp.sign(res.fr))
+
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for various
+ # input shapes.
+ p = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else np.float64(0.6)
+ args = (p,)
+ maxiter = 10
+
+ @np.vectorize
+ def bracket_root_single(xl0, xr0, xmin, xmax, factor, p):
+ return _bracket_root(self.f, xl0, xr0, xmin=xmin, xmax=xmax,
+ factor=factor, args=(p,),
+ maxiter=maxiter)
+
+ def f(*args, **kwargs):
+ f.f_evals += 1
+ return self.f(*args, **kwargs)
+ f.f_evals = 0
+
+ rng = np.random.default_rng(2348234)
+ xl0 = -rng.random(size=shape)
+ xr0 = rng.random(size=shape)
+ xmin, xmax = 1e3*xl0, 1e3*xr0
+ if shape: # make some elements un
+ i = rng.random(size=shape) > 0.5
+ xmin[i], xmax[i] = -np.inf, np.inf
+ factor = rng.random(size=shape) + 1.5
+ refs = bracket_root_single(xl0, xr0, xmin, xmax, factor, p).ravel()
+ xl0, xr0, xmin, xmax, factor = (xp.asarray(xl0), xp.asarray(xr0),
+ xp.asarray(xmin), xp.asarray(xmax),
+ xp.asarray(factor))
+ args = tuple(map(xp.asarray, args))
+ res = _bracket_root(f, xl0, xr0, xmin=xmin, xmax=xmax, factor=factor,
+ args=args, maxiter=maxiter)
+
+ attrs = ['xl', 'xr', 'fl', 'fr', 'success', 'nfev', 'nit']
+ for attr in attrs:
+ ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs]
+ res_attr = getattr(res, attr)
+ xp_assert_close(xp_ravel(res_attr, xp=xp), xp.stack(ref_attr))
+ assert res_attr.shape == shape
+
+ assert res.success.dtype == xp.bool
+ if shape:
+ assert xp.all(res.success[1:-1])
+ assert res.status.dtype == xp.int32
+ assert res.nfev.dtype == xp.int32
+ assert res.nit.dtype == xp.int32
+ assert xp.max(res.nit) == f.f_evals - 2
+ xp_assert_less(res.xl, res.xr)
+ xp_assert_close(res.fl, xp.asarray(self.f(res.xl, *args)))
+ xp_assert_close(res.fr, xp.asarray(self.f(res.xr, *args)))
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously.
+ def f(xs, js):
+ funcs = [lambda x: x - 1.5,
+ lambda x: x - 1000,
+ lambda x: x - 1000,
+ lambda x: x * xp.nan,
+ lambda x: x]
+
+ return [funcs[int(j)](x) for x, j in zip(xs, js)]
+
+ args = (xp.arange(5, dtype=xp.int64),)
+ res = _bracket_root(f,
+ xl0=xp.asarray([-1., -1., -1., -1., 4.]),
+ xr0=xp.asarray([1, 1, 1, 1, -4]),
+ xmin=xp.asarray([-xp.inf, -1, -xp.inf, -xp.inf, 6]),
+ xmax=xp.asarray([xp.inf, 1, xp.inf, xp.inf, 2]),
+ args=args, maxiter=3)
+
+ ref_flags = xp.asarray([eim._ECONVERGED,
+ _ELIMITS,
+ eim._ECONVERR,
+ eim._EVALUEERR,
+ eim._EINPUTERR],
+ dtype=xp.int32)
+
+ xp_assert_equal(res.status, ref_flags)
+
+ @pytest.mark.parametrize("root", (0.622, [0.622, 0.623]))
+ @pytest.mark.parametrize('xmin', [-5, None])
+ @pytest.mark.parametrize('xmax', [5, None])
+ @pytest.mark.parametrize("dtype", ("float16", "float32", "float64"))
+ def test_dtype(self, root, xmin, xmax, dtype, xp):
+ # Test that dtypes are preserved
+ dtype = getattr(xp, dtype)
+ xmin = xmin if xmin is None else xp.asarray(xmin, dtype=dtype)
+ xmax = xmax if xmax is None else xp.asarray(xmax, dtype=dtype)
+ root = xp.asarray(root, dtype=dtype)
+ def f(x, root):
+ return xp.astype((x - root) ** 3, dtype)
+
+ bracket = xp.asarray([-0.01, 0.01], dtype=dtype)
+ res = _bracket_root(f, *bracket, xmin=xmin, xmax=xmax, args=(root,))
+ assert xp.all(res.success)
+ assert res.xl.dtype == res.xr.dtype == dtype
+ assert res.fl.dtype == res.fr.dtype == dtype
+
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ message = '`func` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(None, -4, 4)
+
+ message = '...must be numeric and real.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4+1j, 4)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, xmin=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, xmax=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, factor=4+1j)
+
+ message = "All elements of `factor` must be greater than 1."
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, factor=0.5)
+
+ message = "broadcast"
+ # raised by `xp.broadcast, but the traceback is readable IMO
+ with pytest.raises(Exception, match=message):
+ _bracket_root(lambda x: x, xp.asarray([-2, -3]), xp.asarray([3, 4, 5]))
+ # Consider making this give a more readable error message
+ # with pytest.raises(ValueError, match=message):
+ # _bracket_root(lambda x: [x[0], x[1], x[1]], [-3, -3], [5, 5])
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, maxiter=-1)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, maxiter="shrubbery")
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases
+ # Test that integers are not passed to `f`
+ # (otherwise this would overflow)
+ def f(x):
+ assert xp.isdtype(x.dtype, "real floating")
+ return x ** 99 - 1
+
+ res = _bracket_root(f, xp.asarray(-7.), xp.asarray(5.))
+ assert res.success
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return x - 10
+
+ bracket = (xp.asarray(-3.), xp.asarray(5.))
+ res = _bracket_root(f, *bracket, maxiter=0)
+ assert res.xl, res.xr == bracket
+ assert res.nit == 0
+ assert res.nfev == 2
+ assert res.status == -2
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return c*x - 1
+
+ res = _bracket_root(f, xp.asarray(-1.), xp.asarray(1.),
+ args=xp.asarray(3.))
+ assert res.success
+ xp_assert_close(res.fl, f(res.xl, 3))
+
+ # Test other edge cases
+
+ def f(x):
+ f.count += 1
+ return x
+
+ # 1. root lies within guess of bracket
+ f.count = 0
+ _bracket_root(f, xp.asarray(-10), xp.asarray(20))
+ assert f.count == 2
+
+ # 2. bracket endpoint hits root exactly
+ f.count = 0
+ res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.),
+ factor=2)
+
+ assert res.nfev == 4
+ xp_assert_close(res.xl, xp.asarray(0.), atol=1e-15)
+ xp_assert_close(res.xr, xp.asarray(5.), atol=1e-15)
+
+ # 3. bracket limit hits root exactly
+ with np.errstate(over='ignore'):
+ res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.),
+ xmin=0)
+ xp_assert_close(res.xl, xp.asarray(0.), atol=1e-15)
+
+ with np.errstate(over='ignore'):
+ res = _bracket_root(f, xp.asarray(-10.), xp.asarray(-5.),
+ xmax=0)
+ xp_assert_close(res.xr, xp.asarray(0.), atol=1e-15)
+
+ # 4. bracket not within min, max
+ with np.errstate(over='ignore'):
+ res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.),
+ xmin=1)
+ assert not res.success
+
+ def test_bug_fixes(self):
+ # 1. Bug in double sided bracket search.
+ # Happened in some cases where there are terminations on one side
+ # after corresponding searches on other side failed due to reaching the
+ # boundary.
+
+ # https://github.com/scipy/scipy/pull/22560#discussion_r1962853839
+ def f(x, p):
+ return np.exp(x) - p
+
+ p = np.asarray([0.29, 0.35])
+ res = _bracket_root(f, xl0=-1, xmin=-np.inf, xmax=0, args=(p, ))
+
+ # https://github.com/scipy/scipy/pull/22560/files#r1962952517
+ def f(x, p, c):
+ return np.exp(x*c) - p
+
+ p = [0.32061201, 0.39175242, 0.40047535, 0.50527218, 0.55654373,
+ 0.11911647, 0.37507896, 0.66554191]
+ c = [1., -1., 1., 1., -1., 1., 1., 1.]
+ xl0 = [-7.63108551, 3.27840947, -8.36968526, -1.78124372,
+ 0.92201295, -2.48930123, -0.66733533, -0.44606749]
+ xr0 = [-6.63108551, 4.27840947, -7.36968526, -0.78124372,
+ 1.92201295, -1.48930123, 0., 0.]
+ xmin = [-np.inf, 0., -np.inf, -np.inf, 0., -np.inf, -np.inf,
+ -np.inf]
+ xmax = [0., np.inf, 0., 0., np.inf, 0., 0., 0.]
+
+ res = _bracket_root(f, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=(p, c))
+
+ # 2. Default xl0 + 1 for xr0 exceeds xmax.
+ # https://github.com/scipy/scipy/pull/22560#discussion_r1962947434
+ res = _bracket_root(lambda x: x + 0.25, xl0=-0.5, xmin=-np.inf, xmax=0)
+ assert res.success
+
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+ def test_kwargs(self, xp, dtype):
+ # test that `kwargs` is used, broadcasts correctly, and affects dtype
+ def f(x, c, *, p):
+ return x - (p + c)
+
+ a = xp.zeros((), dtype=xp.float32)
+ c = xp.asarray([1, 2, 3], dtype=xp.float32)
+ p = xp.asarray([2, 3, 4], dtype=getattr(xp, dtype))[:, xp.newaxis]
+ bracket = bracket_root(f, a, args=(c,), kwargs={'p': p})
+ res = find_root(f, bracket.bracket, args=(c,), kwargs={'p': p})
+ ref = p + c
+ xp_assert_close(res.x, ref)
+
+@make_xp_test_case(bracket_minimum)
+class TestBracketMinimum:
+ def init_f(self):
+ def f(x, a, b):
+ f.count += 1
+ return (x - a)**2 + b
+ f.count = 0
+ return f
+
+ def assert_valid_bracket(self, result, xp):
+ assert xp.all(
+ (result.xl < result.xm) & (result.xm < result.xr)
+ )
+ assert xp.all(
+ (result.fl >= result.fm) & (result.fr > result.fm)
+ | (result.fl > result.fm) & (result.fr > result.fm)
+ )
+
+ def get_kwargs(
+ self, *, xl0=None, xr0=None, factor=None, xmin=None, xmax=None, args=None
+ ):
+ names = ("xl0", "xr0", "xmin", "xmax", "factor", "args")
+ return {
+ name: val for name, val in zip(names, (xl0, xr0, xmin, xmax, factor, args))
+ if val is not None
+ }
+
+ @pytest.mark.parametrize(
+ "seed",
+ (
+ 307448016549685229886351382450158984917,
+ 11650702770735516532954347931959000479,
+ 113767103358505514764278732330028568336,
+ )
+ )
+ @pytest.mark.parametrize("use_xmin", (False, True))
+ @pytest.mark.parametrize("other_side", (False, True))
+ def test_nfev_expected(self, seed, use_xmin, other_side, xp):
+ rng = np.random.default_rng(seed)
+ args = (xp.asarray(0.), xp.asarray(0.)) # f(x) = x^2 with minimum at 0
+ # xl0, xm0, xr0 are chosen such that the initial bracket is to
+ # the right of the minimum, and the bracket will expand
+ # downhill towards zero.
+ xl0, d1, d2, factor = xp.asarray(rng.random(size=4) * [1e5, 10, 10, 5])
+ xm0 = xl0 + d1
+ xr0 = xm0 + d2
+ # Factor should be greater than one.
+ factor += 1
+
+ if use_xmin:
+ xmin = xp.asarray(-rng.random() * 5, dtype=xp.float64)
+ n = int(xp.ceil(xp.log(-(xl0 - xmin) / xmin) / xp.log(factor)))
+ lower = xmin + (xl0 - xmin)*factor**-n
+ middle = xmin + (xl0 - xmin)*factor**-(n-1)
+ upper = xmin + (xl0 - xmin)*factor**-(n-2) if n > 1 else xm0
+ # It may be the case the lower is below the minimum, but we still
+ # don't have a valid bracket.
+ if middle**2 > lower**2:
+ n += 1
+ lower, middle, upper = (
+ xmin + (xl0 - xmin)*factor**-n, lower, middle
+ )
+ else:
+ xmin = None
+ n = int(xp.ceil(xp.log(xl0 / d1) / xp.log(factor)))
+ lower = xl0 - d1*factor**n
+ middle = xl0 - d1*factor**(n-1) if n > 1 else xl0
+ upper = xl0 - d1*factor**(n-2) if n > 1 else xm0
+ # It may be the case the lower is below the minimum, but we still
+ # don't have a valid bracket.
+ if middle**2 > lower**2:
+ n += 1
+ lower, middle, upper = (
+ xl0 - d1*factor**n, lower, middle
+ )
+ f = self.init_f()
+
+ xmax = None
+ if other_side:
+ xl0, xm0, xr0 = -xr0, -xm0, -xl0
+ xmin, xmax = None, -xmin if xmin is not None else None
+ lower, middle, upper = -upper, -middle, -lower
+
+ kwargs = self.get_kwargs(
+ xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, factor=factor, args=args
+ )
+ result = _bracket_minimum(f, xp.asarray(xm0), **kwargs)
+
+ # Check that `nfev` and `nit` have the correct relationship
+ assert result.nfev == result.nit + 3
+ # Check that `nfev` reports the correct number of function evaluations.
+ assert result.nfev == f.count
+ # Check that the number of iterations matches the theoretical value.
+ assert result.nit == n
+
+ # Compare reported bracket to theoretical bracket and reported function
+ # values to function evaluated at bracket.
+ xp_assert_close(result.xl, lower)
+ xp_assert_close(result.xm, middle)
+ xp_assert_close(result.xr, upper)
+ xp_assert_close(result.fl, f(lower, *args))
+ xp_assert_close(result.fm, f(middle, *args))
+ xp_assert_close(result.fr, f(upper, *args))
+
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously
+ def f(xs, js):
+ funcs = [lambda x: (x - 1.5)**2,
+ lambda x: x,
+ lambda x: x,
+ lambda x: xp.asarray(xp.nan),
+ lambda x: x**2]
+
+ return [funcs[int(j)](x) for x, j in zip(xs, js)]
+
+ args = (xp.arange(5, dtype=xp.int64),)
+ xl0 = xp.asarray([-1.0, -1.0, -1.0, -1.0, 6.0])
+ xm0 = xp.asarray([0.0, 0.0, 0.0, 0.0, 4.0])
+ xr0 = xp.asarray([1.0, 1.0, 1.0, 1.0, 2.0])
+ xmin = xp.asarray([-xp.inf, -1.0, -xp.inf, -xp.inf, 8.0])
+
+ result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, xmin=xmin,
+ args=args, maxiter=3)
+
+ reference_flags = xp.asarray([eim._ECONVERGED, _ELIMITS,
+ eim._ECONVERR, eim._EVALUEERR,
+ eim._EINPUTERR], dtype=xp.int32)
+ xp_assert_equal(result.status, reference_flags)
+
+ @pytest.mark.parametrize("minimum", (0.622, [0.622, 0.623]))
+ @pytest.mark.parametrize("dtype", ("float16", "float32", "float64"))
+ @pytest.mark.parametrize("xmin", [-5, None])
+ @pytest.mark.parametrize("xmax", [5, None])
+ def test_dtypes(self, minimum, xmin, xmax, dtype, xp):
+ dtype = getattr(xp, dtype)
+ xmin = xmin if xmin is None else xp.asarray(xmin, dtype=dtype)
+ xmax = xmax if xmax is None else xp.asarray(xmax, dtype=dtype)
+ minimum = xp.asarray(minimum, dtype=dtype)
+
+ def f(x, minimum):
+ return xp.astype((x - minimum)**2, dtype)
+
+ xl0, xm0, xr0 = [-0.01, 0.0, 0.01]
+ result = _bracket_minimum(
+ f, xp.asarray(xm0, dtype=dtype), xl0=xp.asarray(xl0, dtype=dtype),
+ xr0=xp.asarray(xr0, dtype=dtype), xmin=xmin, xmax=xmax, args=(minimum, )
+ )
+ assert xp.all(result.success)
+ assert result.xl.dtype == result.xm.dtype == result.xr.dtype == dtype
+ assert result.fl.dtype == result.fm.dtype == result.fr.dtype == dtype
+
+ @pytest.mark.skip_xp_backends(np_only=True, reason="str/object arrays")
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ message = '`func` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(None, -4, xl0=4)
+
+ message = '...must be numeric and real.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(4+1j))
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xl0=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmin=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmax=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), factor=4+1j)
+
+ message = "All elements of `factor` must be greater than 1."
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x, xp.asarray(-4), factor=0.5)
+
+ message = "Array shapes are incompatible for broadcasting."
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray([-2, -3]), xl0=[-3, -4, -5])
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter=-1)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter="ekki")
+
+ @pytest.mark.parametrize("xl0", [0.0, None])
+ @pytest.mark.parametrize("xm0", (0.05, 0.1, 0.15))
+ @pytest.mark.parametrize("xr0", (0.2, 0.4, 0.6, None))
+ # Minimum is ``a`` for each tuple ``(a, b)`` below. Tests cases where minimum
+ # is within, or at varying distances to the left or right of the initial
+ # bracket.
+ @pytest.mark.parametrize(
+ "args",
+ (
+ (1.2, 0), (-0.5, 0), (0.1, 0), (0.2, 0), (3.6, 0), (21.4, 0),
+ (121.6, 0), (5764.1, 0), (-6.4, 0), (-12.9, 0), (-146.2, 0)
+ )
+ )
+ def test_scalar_no_limits(self, xl0, xm0, xr0, args, xp):
+ f = self.init_f()
+ kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, args=tuple(map(xp.asarray, args)))
+ result = _bracket_minimum(f, xp.asarray(xm0, dtype=xp.float64), **kwargs)
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize(
+ # xmin is set at 0.0 in all cases.
+ "xl0,xm0,xr0,xmin",
+ (
+ # Initial bracket at varying distances from the xmin.
+ (0.5, 0.75, 1.0, 0.0),
+ (1.0, 2.5, 4.0, 0.0),
+ (2.0, 4.0, 6.0, 0.0),
+ (12.0, 16.0, 20.0, 0.0),
+ # Test default initial left endpoint selection. It should not
+ # be below xmin.
+ (None, 0.75, 1.0, 0.0),
+ (None, 2.5, 4.0, 0.0),
+ (None, 4.0, 6.0, 0.0),
+ (None, 16.0, 20.0, 0.0),
+ )
+ )
+ @pytest.mark.parametrize(
+ "args", (
+ (0.0, 0.0), # Minimum is directly at xmin.
+ (1e-300, 0.0), # Minimum is extremely close to xmin.
+ (1e-20, 0.0), # Minimum is very close to xmin.
+ # Minimum at varying distances from xmin.
+ (0.1, 0.0),
+ (0.2, 0.0),
+ (0.4, 0.0)
+ )
+ )
+ def test_scalar_with_limit_left(self, xl0, xm0, xr0, xmin, args, xp):
+ f = self.init_f()
+ kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, xmin=xmin,
+ args=tuple(map(xp.asarray, args)))
+ result = _bracket_minimum(f, xp.asarray(xm0), **kwargs)
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize(
+ #xmax is set to 1.0 in all cases.
+ "xl0,xm0,xr0,xmax",
+ (
+ # Bracket at varying distances from xmax.
+ (0.2, 0.3, 0.4, 1.0),
+ (0.05, 0.075, 0.1, 1.0),
+ (-0.2, -0.1, 0.0, 1.0),
+ (-21.2, -17.7, -14.2, 1.0),
+ # Test default right endpoint selection. It should not exceed xmax.
+ (0.2, 0.3, None, 1.0),
+ (0.05, 0.075, None, 1.0),
+ (-0.2, -0.1, None, 1.0),
+ (-21.2, -17.7, None, 1.0),
+ )
+ )
+ @pytest.mark.parametrize(
+ "args", (
+ (0.9999999999999999, 0.0), # Minimum very close to xmax.
+ # Minimum at varying distances from xmax.
+ (0.9, 0.0),
+ (0.7, 0.0),
+ (0.5, 0.0)
+ )
+ )
+ def test_scalar_with_limit_right(self, xl0, xm0, xr0, xmax, args, xp):
+ f = self.init_f()
+ args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args)
+ kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, xmax=xmax, args=args)
+ result = _bracket_minimum(f, xp.asarray(xm0, dtype=xp.float64), **kwargs)
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize(
+ "xl0,xm0,xr0,xmin,xmax,args",
+ (
+ ( # Case 1:
+ # Initial bracket.
+ 0.2,
+ 0.3,
+ 0.4,
+ # Function slopes down to the right from the bracket to a minimum
+ # at 1.0. xmax is also at 1.0
+ None,
+ 1.0,
+ (1.0, 0.0)
+ ),
+ ( # Case 2:
+ # Initial bracket.
+ 1.4,
+ 1.95,
+ 2.5,
+ # Function slopes down to the left from the bracket to a minimum at
+ # 0.3 with xmin set to 0.3.
+ 0.3,
+ None,
+ (0.3, 0.0)
+ ),
+ (
+ # Case 3:
+ # Initial bracket.
+ 2.6,
+ 3.25,
+ 3.9,
+ # Function slopes down and to the right to a minimum at 99.4 with xmax
+ # at 99.4. Tests case where minimum is at xmax relatively further from
+ # the bracket.
+ None,
+ 99.4,
+ (99.4, 0)
+ ),
+ (
+ # Case 4:
+ # Initial bracket.
+ 4,
+ 4.5,
+ 5,
+ # Function slopes down and to the left away from the bracket with a
+ # minimum at -26.3 with xmin set to -26.3. Tests case where minimum is
+ # at xmin relatively far from the bracket.
+ -26.3,
+ None,
+ (-26.3, 0)
+ ),
+ (
+ # Case 5:
+ # Similar to Case 1 above, but tests default values of xl0 and xr0.
+ None,
+ 0.3,
+ None,
+ None,
+ 1.0,
+ (1.0, 0.0)
+ ),
+ ( # Case 6:
+ # Similar to Case 2 above, but tests default values of xl0 and xr0.
+ None,
+ 1.95,
+ None,
+ 0.3,
+ None,
+ (0.3, 0.0)
+ ),
+ (
+ # Case 7:
+ # Similar to Case 3 above, but tests default values of xl0 and xr0.
+ None,
+ 3.25,
+ None,
+ None,
+ 99.4,
+ (99.4, 0)
+ ),
+ (
+ # Case 8:
+ # Similar to Case 4 above, but tests default values of xl0 and xr0.
+ None,
+ 4.5,
+ None,
+ -26.3,
+ None,
+ (-26.3, 0)
+ ),
+ )
+ )
+ def test_minimum_at_boundary_point(self, xl0, xm0, xr0, xmin, xmax, args, xp):
+ f = self.init_f()
+ kwargs = self.get_kwargs(xr0=xr0, xmin=xmin, xmax=xmax,
+ args=tuple(map(xp.asarray, args)))
+ result = _bracket_minimum(f, xp.asarray(xm0), **kwargs)
+ assert result.status == -1
+ assert args[0] in (result.xl, result.xr)
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize('shape', [tuple(), (12, ), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for
+ # various input shapes.
+ a = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
+ args = (a, 0.)
+ maxiter = 10
+
+ @np.vectorize
+ def bracket_minimum_single(xm0, xl0, xr0, xmin, xmax, factor, a):
+ return _bracket_minimum(self.init_f(), xm0, xl0=xl0, xr0=xr0, xmin=xmin,
+ xmax=xmax, factor=factor, maxiter=maxiter,
+ args=(a, 0.0))
+
+ f = self.init_f()
+
+ rng = np.random.default_rng(2348234)
+ xl0 = -rng.random(size=shape)
+ xr0 = rng.random(size=shape)
+ xm0 = xl0 + rng.random(size=shape) * (xr0 - xl0)
+ xmin, xmax = 1e3*xl0, 1e3*xr0
+ if shape: # make some elements un
+ i = rng.random(size=shape) > 0.5
+ xmin[i], xmax[i] = -np.inf, np.inf
+ factor = rng.random(size=shape) + 1.5
+ refs = bracket_minimum_single(xm0, xl0, xr0, xmin, xmax, factor, a).ravel()
+ args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args)
+ res = _bracket_minimum(f, xp.asarray(xm0), xl0=xp.asarray(xl0),
+ xr0=xp.asarray(xr0), xmin=xp.asarray(xmin),
+ xmax=xp.asarray(xmax), factor=xp.asarray(factor),
+ args=args, maxiter=maxiter)
+
+ attrs = ['xl', 'xm', 'xr', 'fl', 'fm', 'fr', 'success', 'nfev', 'nit']
+ for attr in attrs:
+ ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs]
+ res_attr = getattr(res, attr)
+ xp_assert_close(xp_ravel(res_attr, xp=xp), xp.stack(ref_attr))
+ assert res_attr.shape == shape
+
+ assert res.success.dtype == xp.bool
+ if shape:
+ assert xp.all(res.success[1:-1])
+ assert res.status.dtype == xp.int32
+ assert res.nfev.dtype == xp.int32
+ assert res.nit.dtype == xp.int32
+ assert xp.max(res.nit) == f.count - 3
+ self.assert_valid_bracket(res, xp)
+ xp_assert_close(res.fl, f(res.xl, *args))
+ xp_assert_close(res.fm, f(res.xm, *args))
+ xp_assert_close(res.fr, f(res.xr, *args))
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases.
+
+ # Test that integers are not passed to `f`
+ # (otherwise this would overflow)
+ def f(x):
+ assert xp.isdtype(x.dtype, "numeric")
+ return x ** 98 - 1
+
+ result = _bracket_minimum(f, xp.asarray(-7., dtype=xp.float64), xr0=5)
+ assert result.success
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return x**2 - 10
+
+ xl0, xm0, xr0 = xp.asarray(-3.), xp.asarray(-1.), xp.asarray(2.)
+ result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, maxiter=0)
+ xp_assert_equal(result.xl, xl0)
+ xp_assert_equal(result.xm, xm0)
+ xp_assert_equal(result.xr, xr0)
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return c*x**2 - 1
+
+ result = _bracket_minimum(f, xp.asarray(-1.), args=xp.asarray(3.))
+ assert result.success
+ xp_assert_close(result.fl, f(result.xl, 3))
+
+ # Initial bracket is valid.
+ f = self.init_f()
+ xl0, xm0, xr0 = xp.asarray(-1.0), xp.asarray(-0.2), xp.asarray(1.0)
+ args = (xp.asarray(0.), xp.asarray(0.))
+ result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, args=args)
+ assert f.count == 3
+
+ xp_assert_equal(result.xl, xl0)
+ xp_assert_equal(result.xm , xm0)
+ xp_assert_equal(result.xr, xr0)
+ xp_assert_equal(result.fl, f(xl0, *args))
+ xp_assert_equal(result.fm, f(xm0, *args))
+ xp_assert_equal(result.fr, f(xr0, *args))
+
+ def test_gh_20562_left(self, xp):
+ # Regression test for https://github.com/scipy/scipy/issues/20562
+ # minimum of f in [xmin, xmax] is at xmin.
+ xmin, xmax = xp.asarray(0.21933608), xp.asarray(1.39713606)
+
+ def f(x):
+ log_a, log_b = xp.log(xmin), xp.log(xmax)
+ return -((log_b - log_a)*x)**-1
+
+ result = _bracket_minimum(f, xp.asarray(0.5535723499480897), xmin=xmin,
+ xmax=xmax)
+ xp_assert_close(result.xl, xmin)
+
+ def test_gh_20562_right(self, xp):
+ # Regression test for https://github.com/scipy/scipy/issues/20562
+ # minimum of f in [xmin, xmax] is at xmax.
+ xmin, xmax = xp.asarray(-1.39713606), xp.asarray(-0.21933608)
+
+ def f(x):
+ log_a, log_b = xp.log(-xmax), xp.log(-xmin)
+ return ((log_b - log_a)*x)**-1
+
+ result = _bracket_minimum(f, xp.asarray(-0.5535723499480897),
+ xmin=xmin, xmax=xmax)
+ xp_assert_close(result.xr, xmax)
+
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+ def test_kwargs(self, xp, dtype):
+ # test that `kwargs` is used, broadcasts correctly, and affects dtype
+ def f(x, c, *, p):
+ return (x - (p + c))**2
+
+ a = xp.zeros((), dtype=xp.float32)
+ c = xp.asarray([1, 2, 3], dtype=xp.float32)
+ p = xp.asarray([2, 3, 4], dtype=getattr(xp, dtype))[:, xp.newaxis]
+ bracket = bracket_minimum(f, a, args=(c,), kwargs={'p': p})
+ res = find_minimum(f, bracket.bracket, args=(c,), kwargs={'p': p})
+ ref = p + c
+ xp_assert_close(res.x, ref)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_chandrupatla.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2103dec02b866d683c13a8a44f5f6420e128fbe
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_chandrupatla.py
@@ -0,0 +1,976 @@
+import math
+import pytest
+import numpy as np
+from copy import deepcopy
+
+from scipy import stats, special
+import scipy._lib._elementwise_iterative_method as eim
+import scipy._external.array_api_extra as xpx
+from scipy._lib._array_api import (array_namespace, is_cupy, is_numpy, xp_ravel,
+ xp_size, make_xp_test_case)
+from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal,
+ xp_assert_less)
+
+from scipy.optimize.elementwise import find_minimum, find_root
+from scipy.optimize._tstutils import _CHANDRUPATLA_TESTS
+
+from itertools import permutations
+
+
+def _vectorize(xp):
+ # xp-compatible version of np.vectorize
+ # assumes arguments are all arrays of the same shape
+ def decorator(f):
+ def wrapped(*arg_arrays):
+ shape = arg_arrays[0].shape
+ arg_arrays = [xp_ravel(arg_array, xp=xp) for arg_array in arg_arrays]
+ res = []
+ for i in range(math.prod(shape)):
+ arg_scalars = [arg_array[i] for arg_array in arg_arrays]
+ res.append(f(*arg_scalars))
+ return res
+
+ return wrapped
+
+ return decorator
+
+
+# These tests were originally written for the private `optimize._chandrupatla`
+# interfaces, but now we want the tests to check the behavior of the public
+# `optimize.elementwise` interfaces. Therefore, rather than importing
+# `_chandrupatla`/`_chandrupatla_minimize` from `_chandrupatla.py`, we import
+# `find_root`/`find_minimum` from `optimize.elementwise` and wrap those
+# functions to conform to the private interface. This may look a little strange,
+# since it effectively just inverts the interface transformation done within the
+# `find_root`/`find_minimum` functions, but it allows us to run the original,
+# unmodified tests on the public interfaces, simplifying the PR that adds
+# the public interfaces. We'll refactor this when we want to @parametrize the
+# tests over multiple `method`s.
+def _wrap_chandrupatla(func):
+ def _chandrupatla_wrapper(f, *bracket, **kwargs):
+ # avoid passing arguments to `find_minimum` to this function
+ tol_keys = {'xatol', 'xrtol', 'fatol', 'frtol'}
+ tolerances = {key: kwargs.pop(key) for key in tol_keys if key in kwargs}
+ _callback = kwargs.pop('callback', None)
+ if callable(_callback):
+ def callback(res):
+ if func == find_root:
+ res.xl, res.xr = res.bracket
+ res.fl, res.fr = res.f_bracket
+ else:
+ res.xl, res.xm, res.xr = res.bracket
+ res.fl, res.fm, res.fr = res.f_bracket
+ res.fun = res.f_x
+ del res.bracket
+ del res.f_bracket
+ del res.f_x
+ return _callback(res)
+ else:
+ callback = _callback
+
+ res = func(f, bracket, tolerances=tolerances, callback=callback, **kwargs)
+ if func == find_root:
+ res.xl, res.xr = res.bracket
+ res.fl, res.fr = res.f_bracket
+ else:
+ res.xl, res.xm, res.xr = res.bracket
+ res.fl, res.fm, res.fr = res.f_bracket
+ res.fun = res.f_x
+ del res.bracket
+ del res.f_bracket
+ del res.f_x
+ return res
+ return _chandrupatla_wrapper
+
+
+_chandrupatla_minimize = _wrap_chandrupatla(find_minimum)
+
+
+def f1(x):
+ return 100*(1 - x**3.)**2 + (1-x**2.) + 2*(1-x)**2.
+
+
+def f2(x):
+ return 5 + (x - 2.)**6
+
+
+def f3(x):
+ xp = array_namespace(x)
+ return xp.exp(x) - 5*x
+
+
+def f4(x):
+ return x**5. - 5*x**3. - 20.*x + 5.
+
+
+def f5(x):
+ return 8*x**3 - 2*x**2 - 7*x + 3
+
+
+def _bracket_minimum(func, x1, x2):
+ phi = 1.61803398875
+ maxiter = 100
+ f1 = func(x1)
+ f2 = func(x2)
+ step = x2 - x1
+ x1, x2, f1, f2, step = ((x2, x1, f2, f1, -step) if f2 > f1
+ else (x1, x2, f1, f2, step))
+
+ for i in range(maxiter):
+ step *= phi
+ x3 = x2 + step
+ f3 = func(x3)
+ if f3 < f2:
+ x1, x2, f1, f2 = x2, x3, f2, f3
+ else:
+ break
+ return x1, x2, x3, f1, f2, f3
+
+
+cases = [
+ (f1, -1, 11),
+ (f1, -2, 13),
+ (f1, -4, 13),
+ (f1, -8, 15),
+ (f1, -16, 16),
+ (f1, -32, 19),
+ (f1, -64, 20),
+ (f1, -128, 21),
+ (f1, -256, 21),
+ (f1, -512, 19),
+ (f1, -1024, 24),
+ (f2, -1, 8),
+ (f2, -2, 6),
+ (f2, -4, 6),
+ (f2, -8, 7),
+ (f2, -16, 8),
+ (f2, -32, 8),
+ (f2, -64, 9),
+ (f2, -128, 11),
+ (f2, -256, 13),
+ (f2, -512, 12),
+ (f2, -1024, 13),
+ (f3, -1, 11),
+ (f3, -2, 11),
+ (f3, -4, 11),
+ (f3, -8, 10),
+ (f3, -16, 14),
+ (f3, -32, 12),
+ (f3, -64, 15),
+ (f3, -128, 18),
+ (f3, -256, 18),
+ (f3, -512, 19),
+ (f3, -1024, 19),
+ (f4, -0.05, 9),
+ (f4, -0.10, 11),
+ (f4, -0.15, 11),
+ (f4, -0.20, 11),
+ (f4, -0.25, 11),
+ (f4, -0.30, 9),
+ (f4, -0.35, 9),
+ (f4, -0.40, 9),
+ (f4, -0.45, 10),
+ (f4, -0.50, 10),
+ (f4, -0.55, 10),
+ (f5, -0.05, 6),
+ (f5, -0.10, 7),
+ (f5, -0.15, 8),
+ (f5, -0.20, 10),
+ (f5, -0.25, 9),
+ (f5, -0.30, 8),
+ (f5, -0.35, 7),
+ (f5, -0.40, 7),
+ (f5, -0.45, 9),
+ (f5, -0.50, 9),
+ (f5, -0.55, 8)
+]
+
+
+@make_xp_test_case(find_minimum)
+class TestChandrupatlaMinimize:
+
+ def f(self, x, loc):
+ xp = array_namespace(x, loc)
+ res = -xp.exp(-1/2 * (x-loc)**2) / (2*xp.pi)**0.5
+ return xp.asarray(res, dtype=x.dtype)[()]
+
+ @pytest.mark.parametrize('dtype', ('float32', 'float64'))
+ @pytest.mark.parametrize('loc', [0.6, np.linspace(-1.05, 1.05, 10)])
+ def test_basic(self, loc, xp, dtype):
+ # Find mode of normal distribution. Compare mode against location
+ # parameter and value of pdf at mode against expected pdf.
+ rtol = {'float32': 5e-3, 'float64': 5e-7}[dtype]
+ dtype = getattr(xp, dtype)
+ bracket = (xp.asarray(xi, dtype=dtype) for xi in (-5, 0, 5))
+ loc = xp.asarray(loc, dtype=dtype)
+ fun = xp.broadcast_to(xp.asarray(-stats.norm.pdf(0), dtype=dtype), loc.shape)
+
+ res = _chandrupatla_minimize(self.f, *bracket, args=(loc,))
+ xp_assert_close(res.x, loc, rtol=rtol)
+ xp_assert_equal(res.fun, fun)
+
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for various
+ # input shapes.
+ loc = xp.linspace(-0.05, 1.05, 12).reshape(shape) if shape else xp.asarray(0.6)
+ args = (loc,)
+ bracket = xp.asarray(-5.), xp.asarray(0.), xp.asarray(5.)
+
+ @_vectorize(xp)
+ def chandrupatla_single(loc_single):
+ return _chandrupatla_minimize(self.f, *bracket, args=(loc_single,))
+
+ def f(*args, **kwargs):
+ f.f_evals += 1
+ return self.f(*args, **kwargs)
+ f.f_evals = 0
+
+ res = _chandrupatla_minimize(f, *bracket, args=args)
+ refs = chandrupatla_single(loc)
+
+ attrs = ['x', 'fun', 'success', 'status', 'nfev', 'nit',
+ 'xl', 'xm', 'xr', 'fl', 'fm', 'fr']
+ for attr in attrs:
+ ref_attr = xp.stack([getattr(ref, attr) for ref in refs])
+ res_attr = xp_ravel(getattr(res, attr))
+ xp_assert_equal(res_attr, ref_attr)
+ assert getattr(res, attr).shape == shape
+
+ xp_assert_equal(res.fun, self.f(res.x, *args))
+ xp_assert_equal(res.fl, self.f(res.xl, *args))
+ xp_assert_equal(res.fm, self.f(res.xm, *args))
+ xp_assert_equal(res.fr, self.f(res.xr, *args))
+ assert xp.max(res.nfev) == f.f_evals
+ assert xp.max(res.nit) == f.f_evals - 3
+
+ assert xp.isdtype(res.success.dtype, 'bool')
+ assert xp.isdtype(res.status.dtype, 'integral')
+ assert xp.isdtype(res.nfev.dtype, 'integral')
+ assert xp.isdtype(res.nit.dtype, 'integral')
+
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously.
+ def f(xs, js):
+ funcs = [lambda x: (x - 2.5) ** 2,
+ lambda x: x - 10,
+ lambda x: (x - 2.5) ** 4,
+ lambda x: xp.full_like(x, xp.asarray(xp.nan))]
+ res = []
+ for i in range(xp_size(js)):
+ x = xs[i, ...]
+ j = int(xp_ravel(js)[i])
+ res.append(funcs[j](x))
+ return xp.stack(res)
+
+ args = (xp.arange(4, dtype=xp.int64),)
+ bracket = (xp.asarray([0]*4, dtype=xp.float64),
+ xp.asarray([2]*4, dtype=xp.float64),
+ xp.asarray([np.pi]*4, dtype=xp.float64))
+ res = _chandrupatla_minimize(f, *bracket, args=args, maxiter=10)
+
+ ref_flags = xp.asarray([eim._ECONVERGED, eim._ESIGNERR, eim._ECONVERR,
+ eim._EVALUEERR], dtype=xp.int32)
+ xp_assert_equal(res.status, ref_flags)
+
+ def test_convergence(self, xp):
+ # Test that the convergence tolerances behave as expected
+ rng = np.random.default_rng(2585255913088665241)
+ p = xp.asarray(rng.random(size=3))
+ bracket = (xp.asarray(-5, dtype=xp.float64), xp.asarray(0), xp.asarray(5))
+ args = (p,)
+ kwargs0 = dict(args=args, xatol=0, xrtol=0, fatol=0, frtol=0)
+
+ kwargs = kwargs0.copy()
+ kwargs['xatol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j1 = xp.abs(res1.xr - res1.xl)
+ tol = xp.asarray(4*kwargs['xatol'], dtype=p.dtype)
+ xp_assert_less(j1, xp.full((3,), tol, dtype=p.dtype))
+ kwargs['xatol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j2 = xp.abs(res2.xr - res2.xl)
+ tol = xp.asarray(4*kwargs['xatol'], dtype=p.dtype)
+ xp_assert_less(j2, xp.full((3,), tol, dtype=p.dtype))
+ xp_assert_less(j2, j1)
+
+ kwargs = kwargs0.copy()
+ kwargs['xrtol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j1 = xp.abs(res1.xr - res1.xl)
+ tol = xp.asarray(4*kwargs['xrtol']*xp.abs(res1.x), dtype=p.dtype)
+ xp_assert_less(j1, tol)
+ kwargs['xrtol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j2 = xp.abs(res2.xr - res2.xl)
+ tol = xp.asarray(4*kwargs['xrtol']*xp.abs(res2.x), dtype=p.dtype)
+ xp_assert_less(j2, tol)
+ xp_assert_less(j2, j1)
+
+ kwargs = kwargs0.copy()
+ kwargs['fatol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h1 = xp.abs(res1.fl - 2 * res1.fm + res1.fr)
+ tol = xp.asarray(2*kwargs['fatol'], dtype=p.dtype)
+ xp_assert_less(h1, xp.full((3,), tol, dtype=p.dtype))
+ kwargs['fatol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h2 = xp.abs(res2.fl - 2 * res2.fm + res2.fr)
+ tol = xp.asarray(2*kwargs['fatol'], dtype=p.dtype)
+ xp_assert_less(h2, xp.full((3,), tol, dtype=p.dtype))
+ xp_assert_less(h2, h1)
+
+ kwargs = kwargs0.copy()
+ kwargs['frtol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h1 = xp.abs(res1.fl - 2 * res1.fm + res1.fr)
+ tol = xp.asarray(2*kwargs['frtol']*xp.abs(res1.fun), dtype=p.dtype)
+ xp_assert_less(h1, tol)
+ kwargs['frtol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h2 = xp.abs(res2.fl - 2 * res2.fm + res2.fr)
+ tol = xp.asarray(2*kwargs['frtol']*abs(res2.fun), dtype=p.dtype)
+ xp_assert_less(h2, tol)
+ xp_assert_less(h2, h1)
+
+ def test_maxiter_callback(self, xp):
+ # Test behavior of `maxiter` parameter and `callback` interface
+ loc = xp.asarray(0.612814)
+ bracket = (xp.asarray(-5), xp.asarray(0), xp.asarray(5))
+ maxiter = 5
+
+ res = _chandrupatla_minimize(self.f, *bracket, args=(loc,),
+ maxiter=maxiter)
+ assert not xp.any(res.success)
+ assert xp.all(res.nfev == maxiter+3)
+ assert xp.all(res.nit == maxiter)
+
+ def callback(res):
+ callback.iter += 1
+ callback.res = res
+ assert hasattr(res, 'x')
+ if callback.iter == 0:
+ # callback is called once with initial bracket
+ assert (res.xl, res.xm, res.xr) == bracket
+ else:
+ changed_xr = (res.xl == callback.xl) & (res.xr != callback.xr)
+ changed_xl = (res.xl != callback.xl) & (res.xr == callback.xr)
+ assert xp.all(changed_xr | changed_xl)
+
+ callback.xl = res.xl
+ callback.xr = res.xr
+ assert res.status == eim._EINPROGRESS
+ xp_assert_equal(self.f(res.xl, loc), res.fl)
+ xp_assert_equal(self.f(res.xm, loc), res.fm)
+ xp_assert_equal(self.f(res.xr, loc), res.fr)
+ xp_assert_equal(self.f(res.x, loc), res.fun)
+ if callback.iter == maxiter:
+ raise StopIteration
+
+ callback.xl = xp.nan
+ callback.xr = xp.nan
+ callback.iter = -1 # callback called once before first iteration
+ callback.res = None
+
+ res2 = _chandrupatla_minimize(self.f, *bracket, args=(loc,),
+ callback=callback)
+
+ # terminating with callback is identical to terminating due to maxiter
+ # (except for `status`)
+ for key in res.keys():
+ if key == 'status':
+ assert res[key] == eim._ECONVERR
+ # assert callback.res[key] == eim._EINPROGRESS
+ assert res2[key] == eim._ECALLBACK
+ else:
+ assert res2[key] == callback.res[key] == res[key]
+
+ @pytest.mark.parametrize('case', cases)
+ def test_nit_expected(self, case, xp):
+ # Test that `_chandrupatla` implements Chandrupatla's algorithm:
+ # in all 55 test cases, the number of iterations performed
+ # matches the number reported in the original paper.
+ func, x1, nit = case
+
+ # Find bracket using the algorithm in the paper
+ step = 0.2
+ x2 = x1 + step
+ x1, x2, x3, f1, f2, f3 = _bracket_minimum(func, x1, x2)
+
+ # Use tolerances from original paper
+ xatol = 0.0001
+ fatol = 0.000001
+ xrtol = 1e-16
+ frtol = 1e-16
+
+ bracket = xp.asarray(x1), xp.asarray(x2), xp.asarray(x3, dtype=xp.float64)
+ res = _chandrupatla_minimize(func, *bracket, xatol=xatol,
+ fatol=fatol, xrtol=xrtol, frtol=frtol)
+ xp_assert_equal(res.nit, xp.asarray(nit, dtype=xp.int32))
+
+ @pytest.mark.parametrize("loc", (0.65, [0.65, 0.7]))
+ @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64'))
+ def test_dtype(self, loc, dtype, xp):
+ # Test that dtypes are preserved
+ dtype = getattr(xp, dtype)
+
+ loc = xp.asarray(loc, dtype=dtype)
+ bracket = (xp.asarray(-3, dtype=dtype),
+ xp.asarray(1, dtype=dtype),
+ xp.asarray(5, dtype=dtype))
+
+ def f(x, loc):
+ assert x.dtype == dtype
+ return xp.astype((x - loc)**2, dtype)
+
+ res = _chandrupatla_minimize(f, *bracket, args=(loc,))
+ assert res.x.dtype == dtype
+ xp_assert_close(res.x, loc, rtol=math.sqrt(xp.finfo(dtype).eps))
+
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ message = '`func` must be callable.'
+ bracket = xp.asarray(-4), xp.asarray(0), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(None, *bracket)
+
+ message = 'Abscissae and function output must be real numbers.'
+ bracket = xp.asarray(-4 + 1j), xp.asarray(0), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket)
+
+ message = "...be broadcast..."
+ bracket = xp.asarray([-2, -3]), xp.asarray([0, 0]), xp.asarray([3, 4, 5])
+ # raised by `np.broadcast, but the traceback is readable IMO
+ with pytest.raises((ValueError, RuntimeError), match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket)
+
+ message = "The shape of the array returned by `func` must be the same"
+ bracket = xp.asarray([-3, -3]), xp.asarray([0, 0]), xp.asarray([5, 5])
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: [x[0, ...], x[1, ...], x[1, ...]],
+ *bracket)
+
+ message = 'Tolerances must be non-negative scalars.'
+ bracket = xp.asarray(-4), xp.asarray(0), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, xatol=-1)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, xrtol=xp.nan)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, fatol='ekki')
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, frtol=xp.nan)
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, maxiter=-1)
+
+ message = '`callback` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, callback='shrubbery')
+
+ def test_bracket_order(self, xp):
+ # Confirm that order of points in bracket doesn't
+ loc = xp.linspace(-1, 1, 6)[:, xp.newaxis]
+ brackets = xp.asarray(list(permutations([-5, 0, 5]))).T
+ res = _chandrupatla_minimize(self.f, *brackets, args=(loc,))
+ assert xp.all(xpx.isclose(res.x, loc) | (res.fun == self.f(loc, loc)))
+ ref = res.x[:, 0] # all columns should be the same
+ xp_assert_close(*xp.broadcast_arrays(res.x.T, ref), rtol=1e-15)
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases
+
+ # Test that integers are not passed to `f`
+ def f(x):
+ assert xp.isdtype(x.dtype, "real floating")
+ return (x - 1)**2
+
+ bracket = xp.asarray(-7), xp.asarray(0), xp.asarray(8)
+ with np.errstate(invalid='ignore'):
+ res = _chandrupatla_minimize(f, *bracket, fatol=0, frtol=0)
+ assert res.success
+ xp_assert_close(res.x, xp.asarray(1.), rtol=1e-3)
+ xp_assert_close(res.fun, xp.asarray(0.), atol=1e-200)
+
+ # Test that if all elements of bracket equal minimizer, algorithm
+ # reports convergence
+ def f(x):
+ return (x-1)**2
+
+ bracket = xp.asarray(1), xp.asarray(1), xp.asarray(1)
+ res = _chandrupatla_minimize(f, *bracket)
+ assert res.success
+ xp_assert_equal(res.x, xp.asarray(1.))
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return (x-1)**2
+
+ bracket = xp.asarray(-3), xp.asarray(1.1), xp.asarray(5)
+ res = _chandrupatla_minimize(f, *bracket, maxiter=0)
+ assert res.xl, res.xr == bracket
+ assert res.nit == 0
+ assert res.nfev == 3
+ assert res.status == -2
+ assert res.x == 1.1 # best so far
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return (x-c)**2 - 1
+
+ bracket = xp.asarray(-1), xp.asarray(0), xp.asarray(1)
+ c = xp.asarray(1/3)
+ res = _chandrupatla_minimize(f, *bracket, args=(c,))
+ xp_assert_close(res.x, c)
+
+ # Test zero tolerances
+ def f(x):
+ return -xp.sin(x)
+
+ bracket = xp.asarray(0), xp.asarray(1), xp.asarray(xp.pi)
+ res = _chandrupatla_minimize(f, *bracket, xatol=0, xrtol=0, fatol=0, frtol=0)
+ assert res.success
+ # found a minimum exactly (according to floating point arithmetic)
+ assert res.xl < res.xm < res.xr
+ assert f(res.xl) == f(res.xm) == f(res.xr)
+
+
+@make_xp_test_case(find_root)
+class TestFindRoot:
+
+ def f(self, q, p):
+ return special.ndtr(q) - p
+
+ @pytest.mark.parametrize('p', [0.6, np.linspace(-0.05, 1.05, 10)])
+ def test_basic(self, p, xp):
+ # Invert distribution CDF and compare against distribution `ppf`
+ a, b = xp.asarray(-5.), xp.asarray(5.)
+ res = find_root(self.f, (a, b), args=(xp.asarray(p),))
+ ref = xp.asarray(stats.norm().ppf(p), dtype=xp.asarray(p).dtype)
+ xp_assert_close(res.x, ref)
+
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for various
+ # input shapes.
+ p = (np.linspace(-0.05, 1.05, 12).reshape(shape) if shape
+ else np.float64(0.6))
+ p_xp = xp.asarray(p)
+ args_xp = (p_xp,)
+ dtype = p_xp.dtype
+
+ @np.vectorize
+ def find_root_single(p):
+ return find_root(self.f, (-5, 5), args=(p,))
+
+ def f(*args, **kwargs):
+ f.f_evals += 1
+ return self.f(*args, **kwargs)
+ f.f_evals = 0
+
+ bracket = xp.asarray(-5., dtype=xp.float64), xp.asarray(5., dtype=xp.float64)
+ res = find_root(f, bracket, args=args_xp)
+ refs = find_root_single(p).ravel()
+
+ ref_x = [ref.x for ref in refs]
+ ref_x = xp.reshape(xp.asarray(ref_x, dtype=dtype), shape)
+ xp_assert_close(res.x, ref_x)
+
+ ref_f = [ref.f_x for ref in refs]
+ ref_f = xp.reshape(xp.asarray(ref_f, dtype=dtype), shape)
+ xp_assert_close(res.f_x, ref_f, atol=1e-15)
+ xp_assert_equal(res.f_x, self.f(res.x, *args_xp))
+
+ ref_success = [bool(ref.success) for ref in refs]
+ ref_success = xp.reshape(xp.asarray(ref_success, dtype=xp.bool), shape)
+ xp_assert_equal(res.success, ref_success)
+
+ ref_status = [ref.status for ref in refs]
+ ref_status = xp.reshape(xp.asarray(ref_status, dtype=xp.int32), shape)
+ xp_assert_equal(res.status, ref_status)
+
+ ref_nfev = [ref.nfev for ref in refs]
+ ref_nfev = xp.reshape(xp.asarray(ref_nfev, dtype=xp.int32), shape)
+ if is_numpy(xp):
+ xp_assert_equal(res.nfev, ref_nfev)
+ assert xp.max(res.nfev) == f.f_evals
+ else: # different backend may lead to different nfev
+ assert res.nfev.shape == shape
+ assert res.nfev.dtype == xp.int32
+
+ ref_nit = [ref.nit for ref in refs]
+ ref_nit = xp.reshape(xp.asarray(ref_nit, dtype=xp.int32), shape)
+ if is_numpy(xp):
+ xp_assert_equal(res.nit, ref_nit)
+ assert xp.max(res.nit) == f.f_evals-2
+ else:
+ assert res.nit.shape == shape
+ assert res.nit.dtype == xp.int32
+
+ ref_xl = [ref.bracket[0] for ref in refs]
+ ref_xl = xp.reshape(xp.asarray(ref_xl, dtype=dtype), shape)
+ xp_assert_close(res.bracket[0], ref_xl)
+
+ ref_xr = [ref.bracket[1] for ref in refs]
+ ref_xr = xp.reshape(xp.asarray(ref_xr, dtype=dtype), shape)
+ xp_assert_close(res.bracket[1], ref_xr)
+
+ xp_assert_less(res.bracket[0], res.bracket[1])
+ finite = xp.isfinite(res.x)
+ assert xp.all((res.x[finite] == res.bracket[0][finite])
+ | (res.x[finite] == res.bracket[1][finite]))
+
+ # PyTorch and CuPy don't solve to the same accuracy as NumPy - that's OK.
+ atol = 1e-15 if is_numpy(xp) else 1e-9
+
+ ref_fl = [ref.f_bracket[0] for ref in refs]
+ ref_fl = xp.reshape(xp.asarray(ref_fl, dtype=dtype), shape)
+ xp_assert_close(res.f_bracket[0], ref_fl, atol=atol)
+ xp_assert_equal(res.f_bracket[0], self.f(res.bracket[0], *args_xp))
+
+ ref_fr = [ref.f_bracket[1] for ref in refs]
+ ref_fr = xp.reshape(xp.asarray(ref_fr, dtype=dtype), shape)
+ xp_assert_close(res.f_bracket[1], ref_fr, atol=atol)
+ xp_assert_equal(res.f_bracket[1], self.f(res.bracket[1], *args_xp))
+
+ assert xp.all(xp.abs(res.f_x[finite]) ==
+ xp.minimum(xp.abs(res.f_bracket[0][finite]),
+ xp.abs(res.f_bracket[1][finite])))
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously.
+ def f(xs, js):
+ # Note that full_like and int(j) shouldn't really be required. CuPy
+ # is just really picky here, so I'm making it a special case to
+ # make sure the other backends work when the user is less careful.
+ assert js.dtype == xp.int64
+ if is_cupy(xp):
+ funcs = [lambda x: x - 2.5,
+ lambda x: x - 10,
+ lambda x: (x - 0.1)**3,
+ lambda x: xp.full_like(x, xp.asarray(xp.nan))]
+ return [funcs[int(j)](x) for x, j in zip(xs, js)]
+
+ funcs = [lambda x: x - 2.5,
+ lambda x: x - 10,
+ lambda x: (x - 0.1) ** 3,
+ lambda x: xp.nan]
+ return [funcs[j](x) for x, j in zip(xs, js)]
+
+ args = (xp.arange(4, dtype=xp.int64),)
+ a, b = xp.asarray([0.]*4), xp.asarray([xp.pi]*4)
+ res = find_root(f, (a, b), args=args, maxiter=2)
+
+ ref_flags = xp.asarray([eim._ECONVERGED,
+ eim._ESIGNERR,
+ eim._ECONVERR,
+ eim._EVALUEERR], dtype=xp.int32)
+ xp_assert_equal(res.status, ref_flags)
+
+ def test_convergence(self, xp):
+ # Test that the convergence tolerances behave as expected
+ rng = np.random.default_rng(2585255913088665241)
+ p = xp.asarray(rng.random(size=3))
+ bracket = (-xp.asarray(5.), xp.asarray(5.))
+ args = (p,)
+ kwargs0 = dict(args=args, tolerances=dict(xatol=0, xrtol=0, fatol=0, frtol=0))
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['xatol'] = 1e-3
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res1.bracket[1] - res1.bracket[0],
+ xp.full_like(p, xp.asarray(1e-3)))
+ kwargs['tolerances']['xatol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ xp.full_like(p, xp.asarray(1e-6)))
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ res1.bracket[1] - res1.bracket[0])
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['xrtol'] = 1e-3
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res1.bracket[1] - res1.bracket[0], 1e-3 * xp.abs(res1.x))
+ kwargs['tolerances']['xrtol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ 1e-6 * xp.abs(res2.x))
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ res1.bracket[1] - res1.bracket[0])
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['fatol'] = 1e-3
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res1.f_x), xp.full_like(p, xp.asarray(1e-3)))
+ kwargs['tolerances']['fatol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res2.f_x), xp.full_like(p, xp.asarray(1e-6)))
+ xp_assert_less(xp.abs(res2.f_x), xp.abs(res1.f_x))
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['frtol'] = 1e-3
+ x1, x2 = bracket
+ f0 = xp.minimum(xp.abs(self.f(x1, *args)), xp.abs(self.f(x2, *args)))
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res1.f_x), 1e-3*f0)
+ kwargs['tolerances']['frtol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res2.f_x), 1e-6*f0)
+ xp_assert_less(xp.abs(res2.f_x), xp.abs(res1.f_x))
+
+ def test_maxiter_callback(self, xp):
+ # Test behavior of `maxiter` parameter and `callback` interface
+ p = xp.asarray(0.612814)
+ bracket = (xp.asarray(-5.), xp.asarray(5.))
+ maxiter = 5
+
+ def f(q, p):
+ res = special.ndtr(q) - p
+ f.x = q
+ f.f_x = res
+ return res
+ f.x = None
+ f.f_x = None
+
+ res = find_root(f, bracket, args=(p,), maxiter=maxiter)
+ assert not xp.any(res.success)
+ assert xp.all(res.nfev == maxiter+2)
+ assert xp.all(res.nit == maxiter)
+
+ def callback(res):
+ callback.iter += 1
+ callback.res = res
+ assert hasattr(res, 'x')
+ if callback.iter == 0:
+ # callback is called once with initial bracket
+ assert (res.bracket[0], res.bracket[1]) == bracket
+ else:
+ changed = (((res.bracket[0] == callback.bracket[0])
+ & (res.bracket[1] != callback.bracket[1]))
+ | ((res.bracket[0] != callback.bracket[0])
+ & (res.bracket[1] == callback.bracket[1])))
+ assert xp.all(changed)
+
+ callback.bracket[0] = res.bracket[0]
+ callback.bracket[1] = res.bracket[1]
+ assert res.status == eim._EINPROGRESS
+ xp_assert_equal(self.f(res.bracket[0], p), res.f_bracket[0])
+ xp_assert_equal(self.f(res.bracket[1], p), res.f_bracket[1])
+ xp_assert_equal(self.f(res.x, p), res.f_x)
+ if callback.iter == maxiter:
+ raise StopIteration
+ callback.iter = -1 # callback called once before first iteration
+ callback.res = None
+ callback.bracket = [None, None]
+
+ res2 = find_root(f, bracket, args=(p,), callback=callback)
+
+ # terminating with callback is identical to terminating due to maxiter
+ # (except for `status`)
+ for key in res.keys():
+ if key == 'status':
+ xp_assert_equal(res[key], xp.asarray(eim._ECONVERR, dtype=xp.int32))
+ xp_assert_equal(res2[key], xp.asarray(eim._ECALLBACK, dtype=xp.int32))
+ elif key in {'bracket', 'f_bracket'}:
+ xp_assert_equal(res2[key][0], res[key][0])
+ xp_assert_equal(res2[key][1], res[key][1])
+ elif key.startswith('_'):
+ continue
+ else:
+ xp_assert_equal(res2[key], res[key])
+
+ @pytest.mark.parametrize('case', _CHANDRUPATLA_TESTS)
+ def test_nit_expected(self, case, xp):
+ # Test that `_chandrupatla` implements Chandrupatla's algorithm:
+ # in all 40 test cases, the number of iterations performed
+ # matches the number reported in the original paper.
+ f, bracket, root, nfeval, id = case
+ # Chandrupatla's criterion is equivalent to
+ # abs(x2-x1) < 4*abs(xmin)*xrtol + xatol, but we use the more standard
+ # abs(x2-x1) < abs(xmin)*xrtol + xatol. Therefore, set xrtol to 4x
+ # that used by Chandrupatla in tests.
+ bracket = (xp.asarray(bracket[0], dtype=xp.float64),
+ xp.asarray(bracket[1], dtype=xp.float64))
+ root = xp.asarray(root, dtype=xp.float64)
+
+ res = find_root(f, bracket, tolerances=dict(xrtol=4e-10, xatol=1e-5))
+ xp_assert_close(res.f_x, xp.asarray(f(root), dtype=xp.float64),
+ rtol=1e-8, atol=2e-3)
+ xp_assert_equal(res.nfev, xp.asarray(nfeval, dtype=xp.int32))
+
+ @pytest.mark.parametrize("root", (0.622, [0.622, 0.623]))
+ @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64'))
+ def test_dtype(self, root, dtype, xp):
+ # Test that dtypes are preserved
+ not_numpy = not is_numpy(xp)
+ if not_numpy and dtype == 'float16':
+ pytest.skip("`float16` dtype only supported for NumPy arrays.")
+
+ dtype = getattr(xp, dtype, None)
+ if dtype is None:
+ pytest.skip(f"{xp} does not support {dtype}")
+
+ def f(x, root):
+ res = (x - root) ** 3.
+ if is_numpy(xp): # NumPy does not preserve dtype
+ return xp.asarray(res, dtype=dtype)
+ return res
+
+ a, b = xp.asarray(-3, dtype=dtype), xp.asarray(3, dtype=dtype)
+ root = xp.asarray(root, dtype=dtype)
+ res = find_root(f, (a, b), args=(root,), tolerances={'xatol': 1e-3})
+ try:
+ xp_assert_close(res.x, root, atol=1e-3)
+ except AssertionError:
+ assert res.x.dtype == dtype
+ xp.all(res.f_x == 0)
+
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ def func(x):
+ return x
+
+ message = '`func` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ bracket = xp.asarray(-4), xp.asarray(4)
+ find_root(None, bracket)
+
+ message = 'Abscissae and function output must be real numbers.'
+ with pytest.raises(ValueError, match=message):
+ bracket = xp.asarray(-4+1j), xp.asarray(4)
+ find_root(func, bracket)
+
+ # raised by `np.broadcast, but the traceback is readable IMO
+ # all messages include this part
+ message = "(not be broadcast|Attempting to broadcast a dimension of length)"
+ with pytest.raises((ValueError, RuntimeError), match=message):
+ bracket = xp.asarray([-2, -3]), xp.asarray([3, 4, 5])
+ find_root(func, bracket)
+
+ message = "The shape of the array returned by `func`..."
+ with pytest.raises(ValueError, match=message):
+ bracket = xp.asarray([-3, -3]), xp.asarray([5, 5])
+ find_root(lambda x: [x[0], x[1], x[1]], bracket)
+
+ message = 'Tolerances must be non-negative scalars.'
+ bracket = xp.asarray(-4), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(xatol=-1))
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(xrtol=xp.nan))
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(fatol='ekki'))
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(frtol=xp.nan))
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, maxiter=-1)
+
+ message = '`callback` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, callback='shrubbery')
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases
+
+ # Test infinite function values
+ def f(x):
+ return 1 / x + 1 - 1 / (-x + 1)
+
+ a, b = xp.asarray([0.1, 0., 0., 0.1]), xp.asarray([0.9, 1.0, 0.9, 1.0])
+
+ with np.errstate(divide='ignore', invalid='ignore'):
+ res = find_root(f, (a, b))
+
+ assert xp.all(res.success)
+ xp_assert_close(res.x[1:], xp.full((3,), res.x[0]))
+
+ # Test that integers are not passed to `f`
+ # (otherwise this would overflow)
+ def f(x):
+ assert xp.isdtype(x.dtype, "real floating")
+ # this would overflow if x were an xp integer dtype
+ return x ** 31 - 1
+
+ # note that all inputs are integer type; result is automatically default float
+ res = find_root(f, (xp.asarray(-7), xp.asarray(5)))
+ assert res.success
+ xp_assert_close(res.x, xp.asarray(1.))
+
+ # Test that if both ends of bracket equal root, algorithm reports
+ # convergence.
+ def f(x, root):
+ return x**2 - root
+
+ root = xp.asarray([0, 1])
+ res = find_root(f, (xp.asarray(1), xp.asarray(1)), args=(root,))
+ xp_assert_equal(res.success, xp.asarray([False, True]))
+ xp_assert_equal(res.x, xp.asarray([xp.nan, 1.]))
+
+ def f(x):
+ return 1/x
+
+ with np.errstate(invalid='ignore'):
+ inf = xp.asarray(xp.inf)
+ res = find_root(f, (inf, inf))
+ assert res.success
+ xp_assert_equal(res.x, xp.asarray(xp.inf))
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return x**3 - 1
+
+ a, b = xp.asarray(-3.), xp.asarray(5.)
+ res = find_root(f, (a, b), maxiter=0)
+ xp_assert_equal(res.success, xp.asarray(False))
+ xp_assert_equal(res.status, xp.asarray(-2, dtype=xp.int32))
+ xp_assert_equal(res.nit, xp.asarray(0, dtype=xp.int32))
+ xp_assert_equal(res.nfev, xp.asarray(2, dtype=xp.int32))
+ xp_assert_equal(res.bracket[0], a)
+ xp_assert_equal(res.bracket[1], b)
+ # The `x` attribute is the one with the smaller function value
+ xp_assert_equal(res.x, a)
+ # Reverse bracket; check that this is still true
+ res = find_root(f, (-b, -a), maxiter=0)
+ xp_assert_equal(res.x, -a)
+
+ # Test maxiter = 1
+ res = find_root(f, (a, b), maxiter=1)
+ xp_assert_equal(res.success, xp.asarray(True))
+ xp_assert_equal(res.status, xp.asarray(0, dtype=xp.int32))
+ xp_assert_equal(res.nit, xp.asarray(1, dtype=xp.int32))
+ xp_assert_equal(res.nfev, xp.asarray(3, dtype=xp.int32))
+ xp_assert_close(res.x, xp.asarray(1.))
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return c*x - 1
+
+ res = find_root(f, (xp.asarray(-1), xp.asarray(1)), args=xp.asarray(3))
+ xp_assert_close(res.x, xp.asarray(1/3))
+
+ # # TODO: Test zero tolerance
+ # # ~~What's going on here - why are iterations repeated?~~
+ # # tl goes to zero when xatol=xrtol=0. When function is nearly linear,
+ # # this causes convergence issues.
+ # def f(x):
+ # return np.cos(x)
+ #
+ # res = _chandrupatla_root(f, 0, np.pi, xatol=0, xrtol=0)
+ # assert res.nit < 100
+ # xp = np.nextafter(res.x, np.inf)
+ # xm = np.nextafter(res.x, -np.inf)
+ # assert np.abs(res.fun) < np.abs(f(xp))
+ # assert np.abs(res.fun) < np.abs(f(xm))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyla.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c4c4de8f37367da8c00043cb5f929f368ef6ace
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyla.py
@@ -0,0 +1,195 @@
+import math
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_almost_equal
+
+from scipy.optimize import (
+ fmin_cobyla, minimize, Bounds, NonlinearConstraint, LinearConstraint,
+ OptimizeResult
+)
+
+
+class TestCobyla:
+ def setup_method(self):
+ # The algorithm is very fragile on 32 bit, so unfortunately we need to start
+ # very near the solution in order for the test to pass.
+ self.x0 = [np.sqrt(25 - (2.0/3)**2), 2.0/3 + 1e-4]
+ self.solution = [math.sqrt(25 - (2.0/3)**2), 2.0/3]
+ self.opts = {'disp': 0, 'rhobeg': 1, 'tol': 1e-6,
+ 'maxiter': 100}
+
+ def fun(self, x):
+ return x[0]**2 + abs(x[1])**3
+
+ def con1(self, x):
+ return x[0]**2 + x[1]**2 - 25
+
+ def con2(self, x):
+ return -self.con1(x)
+
+ def test_simple(self):
+ # use disp=True as smoke test for gh-8118
+ x = fmin_cobyla(self.fun, self.x0, [self.con1, self.con2], rhobeg=1,
+ rhoend=1e-5, maxfun=100, disp=1)
+ assert_allclose(x, self.solution, atol=1e-4)
+
+ def test_minimize_simple(self):
+ class Callback:
+ def __init__(self):
+ self.n_calls = 0
+ self.last_x = None
+
+ def __call__(self, x):
+ self.n_calls += 1
+ self.last_x = x
+
+ class CallbackNewSyntax:
+ def __init__(self):
+ self.n_calls = 0
+
+ def __call__(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ self.n_calls += 1
+
+ callback = Callback()
+ callback_new_syntax = CallbackNewSyntax()
+
+ # Minimize with method='COBYLA'
+ cons = (NonlinearConstraint(self.con1, 0, np.inf),
+ {'type': 'ineq', 'fun': self.con2})
+ sol = minimize(self.fun, self.x0, method='cobyla', constraints=cons,
+ callback=callback, options=self.opts)
+ sol_new = minimize(self.fun, self.x0, method='cobyla', constraints=cons,
+ callback=callback_new_syntax, options=self.opts)
+ assert_allclose(sol.x, self.solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-5, sol
+ assert sol.nfev < 70, sol
+ assert sol.fun < self.fun(self.solution) + 1e-3, sol
+ assert_array_almost_equal(
+ sol.x,
+ callback.last_x,
+ decimal=5,
+ err_msg="Last design vector sent to the callback is not equal to"
+ " returned value.",
+ )
+ assert sol_new.success, sol_new.message
+ assert sol.fun == sol_new.fun
+ assert sol.maxcv == sol_new.maxcv
+ assert sol.nfev == sol_new.nfev
+ assert callback.n_calls == callback_new_syntax.n_calls, \
+ "Callback is not called the same amount of times for old and new syntax."
+
+ def test_minimize_constraint_violation(self):
+ # We set up conflicting constraints so that the algorithm will be
+ # guaranteed to end up with maxcv > 0.
+ cons = ({'type': 'ineq', 'fun': lambda x: 4 - x},
+ {'type': 'ineq', 'fun': lambda x: x - 5})
+ sol = minimize(lambda x: x, [0], method='cobyla', constraints=cons,
+ options={'catol': 0.6})
+ assert sol.maxcv > 0.1
+ assert sol.success
+ sol = minimize(lambda x: x, [0], method='cobyla', constraints=cons,
+ options={'catol': 0.4})
+ assert sol.maxcv > 0.1
+ assert not sol.success
+
+ def test_f_target(self):
+ f_target = 250
+ sol = minimize(lambda x: x**2, [500], method='cobyla',
+ options={'f_target': f_target})
+ assert sol.status == 1
+ assert sol.success
+ assert sol.fun <= f_target
+
+ def test_minimize_linear_constraints(self):
+ constraints = LinearConstraint([1.0, 1.0], 1.0, 1.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyla',
+ constraints=constraints,
+ options=self.opts,
+ )
+ solution = [(4 - np.sqrt(7)) / 3, (np.sqrt(7) - 1) / 3]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+
+
+def test_vector_constraints():
+ # test that fmin_cobyla and minimize can take a combination
+ # of constraints, some returning a number and others an array
+ def fun(x):
+ return (x[0] - 1)**2 + (x[1] - 2.5)**2
+
+ def fmin(x):
+ return fun(x) - 1
+
+ def cons1(x):
+ a = np.array([[1, -2, 2], [-1, -2, 6], [-1, 2, 2]])
+ return np.array([a[i, 0] * x[0] + a[i, 1] * x[1] +
+ a[i, 2] for i in range(len(a))])
+
+ def cons2(x):
+ return x # identity, acts as bounds x > 0
+
+ x0 = np.array([2, 0])
+ cons_list = [fun, cons1, cons2]
+
+ xsol = [1.4, 1.7]
+ fsol = 0.8
+
+ # testing fmin_cobyla
+ sol = fmin_cobyla(fun, x0, cons_list, rhoend=1e-5)
+ assert_allclose(sol, xsol, atol=1e-4)
+
+ sol = fmin_cobyla(fun, x0, fmin, rhoend=1e-5)
+ assert_allclose(fun(sol), 1, atol=1e-4)
+
+ # testing minimize
+ constraints = [{'type': 'ineq', 'fun': cons} for cons in cons_list]
+ sol = minimize(fun, x0, constraints=constraints, tol=1e-5)
+ assert_allclose(sol.x, xsol, atol=1e-4)
+ assert sol.success, sol.message
+ assert_allclose(sol.fun, fsol, atol=1e-4)
+
+ constraints = {'type': 'ineq', 'fun': fmin}
+ sol = minimize(fun, x0, constraints=constraints, tol=1e-5)
+ assert_allclose(sol.fun, 1, atol=1e-4)
+
+
+class TestBounds:
+ # Test cobyla support for bounds (only when used via `minimize`)
+ # Invalid bounds is tested in
+ # test_optimize.TestOptimizeSimple.test_minimize_invalid_bounds
+
+ def test_basic(self):
+ def f(x):
+ return np.sum(x**2)
+
+ lb = [-1, None, 1, None, -0.5]
+ ub = [-0.5, -0.5, None, None, -0.5]
+ bounds = [(a, b) for a, b in zip(lb, ub)]
+ # these are converted to Bounds internally
+
+ res = minimize(f, x0=[1, 2, 3, 4, 5], method='cobyla', bounds=bounds)
+ ref = [-0.5, -0.5, 1, 0, -0.5]
+ assert res.success
+ assert_allclose(res.x, ref, atol=1e-3)
+
+ def test_unbounded(self):
+ def f(x):
+ return np.sum(x**2)
+
+ bounds = Bounds([-np.inf, -np.inf], [np.inf, np.inf])
+ res = minimize(f, x0=[1, 2], method='cobyla', bounds=bounds)
+ assert res.success
+ assert_allclose(res.x, 0, atol=1e-3)
+
+ bounds = Bounds([1, -np.inf], [np.inf, np.inf])
+ res = minimize(f, x0=[1, 2], method='cobyla', bounds=bounds)
+ assert res.success
+ assert_allclose(res.x, [1, 0], atol=1e-3)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyqa.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf16af71625c4d476353407f9708c981915b098a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyqa.py
@@ -0,0 +1,252 @@
+import numpy as np
+import pytest
+import threading
+from numpy.testing import assert_allclose, assert_equal
+
+from scipy.optimize import (
+ Bounds,
+ LinearConstraint,
+ NonlinearConstraint,
+ OptimizeResult,
+ minimize,
+)
+
+
+class TestCOBYQA:
+
+ def setup_method(self):
+ self.x0 = [4.95, 0.66]
+ self.options = {'maxfev': 100}
+
+ @staticmethod
+ def fun(x, c=1.0):
+ return x[0]**2 + c * abs(x[1])**3
+
+ @staticmethod
+ def con(x):
+ return x[0]**2 + x[1]**2 - 25.0
+
+ def test_minimize_simple(self):
+ class Callback:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.n_calls = 0
+
+ def __call__(self, x):
+ assert isinstance(x, np.ndarray)
+ with self.lock:
+ self.n_calls += 1
+
+ class CallbackNewSyntax:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.n_calls = 0
+
+ def __call__(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ with self.lock:
+ self.n_calls += 1
+
+ x0 = [4.95, 0.66]
+ callback = Callback()
+ callback_new_syntax = CallbackNewSyntax()
+
+ # Minimize with method='cobyqa'.
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ self.fun,
+ x0,
+ method='cobyqa',
+ constraints=constraints,
+ callback=callback,
+ options=self.options,
+ )
+ sol_new = minimize(
+ self.fun,
+ x0,
+ method='cobyqa',
+ constraints=constraints,
+ callback=callback_new_syntax,
+ options=self.options,
+ )
+ solution = [np.sqrt(25.0 - 4.0 / 9.0), 2.0 / 3.0]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+ assert sol.nfev == callback.n_calls, \
+ "Callback is not called exactly once for every function eval."
+ assert_equal(sol.x, sol_new.x)
+ assert sol_new.success, sol_new.message
+ assert sol.fun == sol_new.fun
+ assert sol.maxcv == sol_new.maxcv
+ assert sol.nfev == sol_new.nfev
+ assert sol.nit == sol_new.nit
+ assert sol_new.nfev == callback_new_syntax.n_calls, \
+ "Callback is not called exactly once for every function eval."
+
+ def test_minimize_bounds(self):
+ def fun_check_bounds(x):
+ assert np.all(bounds.lb <= x) and np.all(x <= bounds.ub)
+ return self.fun(x)
+
+ # Case where the bounds are not active at the solution.
+ bounds = Bounds([4.5, 0.6], [5.0, 0.7])
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ fun_check_bounds,
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ solution = [np.sqrt(25.0 - 4.0 / 9.0), 2.0 / 3.0]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert np.all(bounds.lb <= sol.x) and np.all(sol.x <= bounds.ub), sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+
+ # Case where the bounds are active at the solution.
+ bounds = Bounds([5.0, 0.6], [5.5, 0.65])
+ sol = minimize(
+ fun_check_bounds,
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ assert not sol.success, sol.message
+ assert sol.maxcv > 0.35, sol
+ assert np.all(bounds.lb <= sol.x) and np.all(sol.x <= bounds.ub), sol
+ assert sol.nfev <= 100, sol
+
+ def test_minimize_linear_constraints(self):
+ constraints = LinearConstraint([1.0, 1.0], 1.0, 1.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=self.options,
+ )
+ solution = [(4 - np.sqrt(7)) / 3, (np.sqrt(7) - 1) / 3]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+
+ def test_minimize_args(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ args=(2.0,),
+ method='cobyqa',
+ constraints=constraints,
+ options=self.options,
+ )
+ solution = [np.sqrt(25.0 - 4.0 / 36.0), 2.0 / 6.0]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution, 2.0) + 1e-3, sol
+
+ def test_minimize_array(self):
+ def fun_array(x, dim):
+ f = np.array(self.fun(x))
+ return np.reshape(f, (1,) * dim)
+
+ # The argument fun can return an array with a single element.
+ bounds = Bounds([4.5, 0.6], [5.0, 0.7])
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ for dim in [0, 1, 2]:
+ sol_array = minimize(
+ fun_array,
+ self.x0,
+ args=(dim,),
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ assert_equal(sol.x, sol_array.x)
+ assert sol_array.success, sol_array.message
+ assert sol.fun == sol_array.fun
+ assert sol.maxcv == sol_array.maxcv
+ assert sol.nfev == sol_array.nfev
+ assert sol.nit == sol_array.nit
+
+ # The argument fun cannot return an array with more than one element.
+ with pytest.raises(TypeError):
+ minimize(
+ lambda x: np.array([self.fun(x), self.fun(x)]),
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+
+ def test_minimize_maxfev(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ options = {'maxfev': 2}
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=options,
+ )
+ assert not sol.success, sol.message
+ assert sol.nfev <= 2, sol
+
+ def test_minimize_maxiter(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ options = {'maxiter': 2}
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=options,
+ )
+ assert not sol.success, sol.message
+ assert sol.nit <= 2, sol
+
+ def test_minimize_f_target(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol_ref = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=self.options,
+ )
+ options = dict(self.options)
+ options['f_target'] = sol_ref.fun
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=options,
+ )
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= sol_ref.nfev, sol
+ assert sol.fun <= sol_ref.fun, sol
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_constraint_conversion.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_constraint_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..80453fe497968db39031695462b9ee3301da7e2e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_constraint_conversion.py
@@ -0,0 +1,284 @@
+"""
+Unit test for constraint conversion
+"""
+import warnings
+
+import numpy as np
+from numpy.testing import (assert_array_almost_equal,
+ assert_allclose)
+import pytest
+from scipy.optimize import (NonlinearConstraint, LinearConstraint,
+ OptimizeWarning, minimize, BFGS)
+from .test_minimize_constrained import (Maratos, HyperbolicIneq, Rosenbrock,
+ IneqRosenbrock, EqIneqRosenbrock,
+ BoundedRosenbrock, Elec)
+
+
+class TestOldToNew:
+ x0 = (2, 0)
+ bnds = ((0, None), (0, None))
+ method = "trust-constr"
+
+ def test_constraint_dictionary_1(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2
+ cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
+ {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ res = minimize(fun, self.x0, method=self.method,
+ bounds=self.bnds, constraints=cons)
+ assert_allclose(res.x, [1.4, 1.7], rtol=1e-4)
+ assert_allclose(res.fun, 0.8, rtol=1e-4)
+
+ def test_constraint_dictionary_2(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2
+ cons = {'type': 'eq',
+ 'fun': lambda x, p1, p2: p1*x[0] - p2*x[1],
+ 'args': (1, 1.1),
+ 'jac': lambda x, p1, p2: np.array([[p1, -p2]])}
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ res = minimize(fun, self.x0, method=self.method,
+ bounds=self.bnds, constraints=cons)
+ assert_allclose(res.x, [1.7918552, 1.62895927])
+ assert_allclose(res.fun, 1.3857466063348418)
+
+ def test_constraint_dictionary_3(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2
+ cons = [{'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ NonlinearConstraint(lambda x: x[0] - x[1], 0, 0)]
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ res = minimize(fun, self.x0, method=self.method,
+ bounds=self.bnds, constraints=cons)
+ assert_allclose(res.x, [1.75, 1.75], rtol=1e-4)
+ assert_allclose(res.fun, 1.125, rtol=1e-4)
+
+
+class TestNewToOld:
+ @pytest.mark.fail_slow(2)
+ def test_multiple_constraint_objects(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ x0 = [2, 0, 1]
+ coni = [] # only inequality constraints (can use cobyla)
+ methods = ["slsqp", "cobyla", "cobyqa", "trust-constr"]
+
+ # mixed old and new
+ coni.append([{'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)])
+
+ coni.append([LinearConstraint([1, -2, 0], -2, np.inf),
+ NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)])
+
+ coni.append([NonlinearConstraint(lambda x: x[0] - 2 * x[1] + 2, 0, np.inf),
+ NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)])
+
+ for con in coni:
+ funs = {}
+ for method in methods:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(fun, x0, method=method, constraints=con)
+ funs[method] = result.fun
+ assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-4)
+ assert_allclose(funs['cobyla'], funs['trust-constr'], rtol=1e-4)
+ assert_allclose(funs['cobyqa'], funs['trust-constr'],
+ rtol=1e-4)
+
+ @pytest.mark.fail_slow(20)
+ def test_individual_constraint_objects(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ x0 = [2, 0, 1]
+
+ cone = [] # with equality constraints (can't use cobyla)
+ coni = [] # only inequality constraints (can use cobyla)
+ methods = ["slsqp", "cobyla", "cobyqa", "trust-constr"]
+
+ # nonstandard data types for constraint equality bounds
+ cone.append(NonlinearConstraint(lambda x: x[0] - x[1], 1, 1))
+ cone.append(NonlinearConstraint(lambda x: x[0] - x[1], [1.21], [1.21]))
+ cone.append(NonlinearConstraint(lambda x: x[0] - x[1],
+ 1.21, np.array([1.21])))
+
+ # multiple equalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ 1.21, 1.21)) # two same equalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, 1.4], [1.21, 1.4])) # two different equalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, 1.21], 1.21)) # equality specified two ways
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, -np.inf], [1.21, np.inf])) # equality + unbounded
+
+ # nonstandard data types for constraint inequality bounds
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1], 1.21, np.inf))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1], [1.21], np.inf))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1],
+ 1.21, np.array([np.inf])))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1], -np.inf, -3))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1],
+ np.array(-np.inf), -3))
+
+ # multiple inequalities/equalities
+ coni.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ 1.21, np.inf)) # two same inequalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, -np.inf], [1.21, 1.4])) # mixed equality/inequality
+ coni.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.1, .8], [1.2, 1.4])) # bounded above and below
+ coni.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [-1.2, -1.4], [-1.1, -.8])) # - bounded above and below
+
+ # quick check of LinearConstraint class (very little new code to test)
+ cone.append(LinearConstraint([1, -1, 0], 1.21, 1.21))
+ cone.append(LinearConstraint([[1, -1, 0], [0, 1, -1]], 1.21, 1.21))
+ cone.append(LinearConstraint([[1, -1, 0], [0, 1, -1]],
+ [1.21, -np.inf], [1.21, 1.4]))
+
+ for con in coni:
+ funs = {}
+ for method in methods:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(fun, x0, method=method, constraints=con)
+ funs[method] = result.fun
+ assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-3)
+ assert_allclose(funs['cobyla'], funs['trust-constr'], rtol=1e-3)
+ assert_allclose(funs['cobyqa'], funs['trust-constr'],
+ rtol=1e-3)
+
+ for con in cone:
+ funs = {}
+ for method in [method for method in methods if method != 'cobyla']:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(fun, x0, method=method, constraints=con)
+ funs[method] = result.fun
+ assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-3)
+ assert_allclose(funs['cobyqa'], funs['trust-constr'],
+ rtol=1e-3)
+
+
+class TestNewToOldSLSQP:
+ method = 'slsqp'
+ elec = Elec(n_electrons=2)
+ elec.x_opt = np.array([-0.58438468, 0.58438466, 0.73597047,
+ -0.73597044, 0.34180668, -0.34180667])
+ brock = BoundedRosenbrock()
+ brock.x_opt = [0, 0]
+ list_of_problems = [Maratos(),
+ HyperbolicIneq(),
+ Rosenbrock(),
+ IneqRosenbrock(),
+ EqIneqRosenbrock(),
+ elec,
+ brock
+ ]
+
+ def test_list_of_problems(self):
+
+ for prob in self.list_of_problems:
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(prob.fun, prob.x0,
+ method=self.method,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=3)
+
+ def test_warn_mixed_constraints(self):
+ # warns about inefficiency of mixed equality/inequality constraints
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ cons = NonlinearConstraint(lambda x: [x[0]**2 - x[1], x[1] - x[2]],
+ [1.1, .8], [1.1, 1.4])
+ bnds = ((0, None), (0, None), (0, None))
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ with pytest.warns(OptimizeWarning):
+ minimize(fun, (2, 0, 1),
+ method=self.method, bounds=bnds, constraints=cons)
+
+ def test_warn_ignored_options(self):
+ # warns about constraint options being ignored
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ x0 = (2, 0, 1)
+
+ if self.method == "slsqp":
+ bnds = ((0, None), (0, None), (0, None))
+ else:
+ bnds = None
+
+ cons = NonlinearConstraint(lambda x: x[0], 2, np.inf)
+ res = minimize(fun, x0, method=self.method,
+ bounds=bnds, constraints=cons)
+ # no warnings without constraint options
+ assert_allclose(res.fun, 1)
+
+ cons = LinearConstraint([1, 0, 0], 2, np.inf)
+ res = minimize(fun, x0, method=self.method,
+ bounds=bnds, constraints=cons)
+ # no warnings without constraint options
+ assert_allclose(res.fun, 1)
+
+ cons = []
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ keep_feasible=True))
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ hess=BFGS()))
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ finite_diff_jac_sparsity=42))
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ finite_diff_rel_step=42))
+ cons.append(LinearConstraint([1, 0, 0], 2, np.inf,
+ keep_feasible=True))
+ for con in cons:
+ with pytest.warns(OptimizeWarning):
+ minimize(fun, x0,
+ method=self.method, bounds=bnds, constraints=cons)
+
+
+class TestNewToOldCobyla:
+ method = 'cobyla'
+
+ list_of_problems = [
+ Elec(n_electrons=2),
+ Elec(n_electrons=4),
+ ]
+
+ @pytest.mark.slow
+ def test_list_of_problems(self):
+
+ for prob in self.list_of_problems:
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ truth = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ bounds=prob.bounds,
+ constraints=prob.constr)
+ result = minimize(prob.fun, prob.x0,
+ method=self.method,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ assert_allclose(result.fun, truth.fun, rtol=1e-3)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_constraints.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ab6965c9a28bc844f416bcbda37107124ccdfe2
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_constraints.py
@@ -0,0 +1,261 @@
+import pytest
+import numpy as np
+from numpy.testing import TestCase, assert_array_equal
+import scipy.sparse as sps
+from scipy.optimize._constraints import (
+ Bounds, LinearConstraint, NonlinearConstraint, PreparedConstraint,
+ new_bounds_to_old, old_bound_to_new, strict_bounds)
+
+
+class TestStrictBounds(TestCase):
+ def test_scalarvalue_unique_enforce_feasibility(self):
+ m = 3
+ lb = 2
+ ub = 4
+ enforce_feasibility = False
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [-np.inf, -np.inf, -np.inf])
+ assert_array_equal(strict_ub, [np.inf, np.inf, np.inf])
+
+ enforce_feasibility = True
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [2, 2, 2])
+ assert_array_equal(strict_ub, [4, 4, 4])
+
+ def test_vectorvalue_unique_enforce_feasibility(self):
+ m = 3
+ lb = [1, 2, 3]
+ ub = [4, 5, 6]
+ enforce_feasibility = False
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [-np.inf, -np.inf, -np.inf])
+ assert_array_equal(strict_ub, [np.inf, np.inf, np.inf])
+
+ enforce_feasibility = True
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [1, 2, 3])
+ assert_array_equal(strict_ub, [4, 5, 6])
+
+ def test_scalarvalue_vector_enforce_feasibility(self):
+ m = 3
+ lb = 2
+ ub = 4
+ enforce_feasibility = [False, True, False]
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [-np.inf, 2, -np.inf])
+ assert_array_equal(strict_ub, [np.inf, 4, np.inf])
+
+ def test_vectorvalue_vector_enforce_feasibility(self):
+ m = 3
+ lb = [1, 2, 3]
+ ub = [4, 6, np.inf]
+ enforce_feasibility = [True, False, True]
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [1, -np.inf, 3])
+ assert_array_equal(strict_ub, [4, np.inf, np.inf])
+
+
+def test_prepare_constraint_infeasible_x0():
+ lb = np.array([0, 20, 30])
+ ub = np.array([0.5, np.inf, 70])
+ x0 = np.array([1, 2, 3])
+ enforce_feasibility = np.array([False, True, True], dtype=bool)
+ bounds = Bounds(lb, ub, enforce_feasibility)
+ pytest.raises(ValueError, PreparedConstraint, bounds, x0)
+
+ pc = PreparedConstraint(Bounds(lb, ub), [1, 2, 3])
+ assert (pc.violation([1, 2, 3]) > 0).any()
+ assert (pc.violation([0.25, 21, 31]) == 0).all()
+
+ x0 = np.array([1, 2, 3, 4])
+ A = np.array([[1, 2, 3, 4], [5, 0, 0, 6], [7, 0, 8, 0]])
+ enforce_feasibility = np.array([True, True, True], dtype=bool)
+ linear = LinearConstraint(A, -np.inf, 0, enforce_feasibility)
+ pytest.raises(ValueError, PreparedConstraint, linear, x0)
+
+ pc = PreparedConstraint(LinearConstraint(A, -np.inf, 0),
+ [1, 2, 3, 4])
+ assert (pc.violation([1, 2, 3, 4]) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ def fun(x):
+ return A.dot(x)
+
+ def jac(x):
+ return A
+
+ def hess(x, v):
+ return sps.csr_array((4, 4))
+
+ nonlinear = NonlinearConstraint(fun, -np.inf, 0, jac, hess,
+ enforce_feasibility)
+ pytest.raises(ValueError, PreparedConstraint, nonlinear, x0)
+
+ pc = PreparedConstraint(nonlinear, [-10, 2, -10, 4])
+ assert (pc.violation([1, 2, 3, 4]) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+
+def test_violation():
+ def cons_f(x):
+ return np.array([x[0] ** 2 + x[1], x[0] ** 2 - x[1]])
+
+ nlc = NonlinearConstraint(cons_f, [-1, -0.8500], [2, 2])
+ pc = PreparedConstraint(nlc, [0.5, 1])
+
+ assert_array_equal(pc.violation([0.5, 1]), [0., 0.])
+
+ np.testing.assert_almost_equal(pc.violation([0.5, 1.2]), [0., 0.1])
+
+ np.testing.assert_almost_equal(pc.violation([1.2, 1.2]), [0.64, 0])
+
+ np.testing.assert_almost_equal(pc.violation([0.1, -1.2]), [0.19, 0])
+
+ np.testing.assert_almost_equal(pc.violation([0.1, 2]), [0.01, 1.14])
+
+
+def test_new_bounds_to_old():
+ lb = np.array([-np.inf, 2, 3])
+ ub = np.array([3, np.inf, 10])
+
+ bounds = [(None, 3), (2, None), (3, 10)]
+ assert_array_equal(new_bounds_to_old(lb, ub, 3), bounds)
+
+ bounds_single_lb = [(-1, 3), (-1, None), (-1, 10)]
+ assert_array_equal(new_bounds_to_old(-1, ub, 3), bounds_single_lb)
+
+ bounds_no_lb = [(None, 3), (None, None), (None, 10)]
+ assert_array_equal(new_bounds_to_old(-np.inf, ub, 3), bounds_no_lb)
+
+ bounds_single_ub = [(None, 20), (2, 20), (3, 20)]
+ assert_array_equal(new_bounds_to_old(lb, 20, 3), bounds_single_ub)
+
+ bounds_no_ub = [(None, None), (2, None), (3, None)]
+ assert_array_equal(new_bounds_to_old(lb, np.inf, 3), bounds_no_ub)
+
+ bounds_single_both = [(1, 2), (1, 2), (1, 2)]
+ assert_array_equal(new_bounds_to_old(1, 2, 3), bounds_single_both)
+
+ bounds_no_both = [(None, None), (None, None), (None, None)]
+ assert_array_equal(new_bounds_to_old(-np.inf, np.inf, 3), bounds_no_both)
+
+
+def test_old_bounds_to_new():
+ bounds = ([1, 2], (None, 3), (-1, None))
+ lb_true = np.array([1, -np.inf, -1])
+ ub_true = np.array([2, 3, np.inf])
+
+ lb, ub = old_bound_to_new(bounds)
+ assert_array_equal(lb, lb_true)
+ assert_array_equal(ub, ub_true)
+
+ bounds = [(-np.inf, np.inf), (np.array([1]), np.array([1]))]
+ lb, ub = old_bound_to_new(bounds)
+
+ assert_array_equal(lb, [-np.inf, 1])
+ assert_array_equal(ub, [np.inf, 1])
+
+
+class TestBounds:
+ def test_repr(self):
+ # so that eval works
+ from numpy import array, inf # noqa: F401
+ for args in (
+ (-1.0, 5.0),
+ (-1.0, np.inf, True),
+ (np.array([1.0, -np.inf]), np.array([2.0, np.inf])),
+ (np.array([1.0, -np.inf]), np.array([2.0, np.inf]),
+ np.array([True, False])),
+ ):
+ bounds = Bounds(*args)
+ bounds2 = eval(repr(Bounds(*args)))
+ assert_array_equal(bounds.lb, bounds2.lb)
+ assert_array_equal(bounds.ub, bounds2.ub)
+ assert_array_equal(bounds.keep_feasible, bounds2.keep_feasible)
+
+ def test_array(self):
+ # gh13501
+ b = Bounds(lb=[0.0, 0.0], ub=[1.0, 1.0])
+ assert isinstance(b.lb, np.ndarray)
+ assert isinstance(b.ub, np.ndarray)
+
+ def test_defaults(self):
+ b1 = Bounds()
+ b2 = Bounds(np.asarray(-np.inf), np.asarray(np.inf))
+ assert b1.lb == b2.lb
+ assert b1.ub == b2.ub
+
+ def test_input_validation(self):
+ message = "Lower and upper bounds must be dense arrays."
+ with pytest.raises(ValueError, match=message):
+ Bounds(sps.coo_array([1, 2]), [1, 2])
+ with pytest.raises(ValueError, match=message):
+ Bounds([1, 2], sps.coo_array([1, 2]))
+
+ message = "`keep_feasible` must be a dense array."
+ with pytest.raises(ValueError, match=message):
+ Bounds([1, 2], [1, 2], keep_feasible=sps.coo_array([True, True]))
+
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
+ with pytest.raises(ValueError, match=message):
+ Bounds([1, 2], [1, 2, 3])
+
+ # gh-25086: empty `lb`/`ub` describes a zero-variable problem, and
+ # rejecting early prevents issues in downstream optimizers.
+ message = "`lb` and `ub` must be non-empty"
+ with pytest.raises(ValueError, match=message):
+ Bounds([], [])
+
+ def test_residual(self):
+ bounds = Bounds(-2, 4)
+ x0 = [-1, 2]
+ np.testing.assert_allclose(bounds.residual(x0), ([1, 4], [5, 2]))
+
+
+class TestLinearConstraint:
+ def test_defaults(self):
+ A = np.eye(4)
+ lc = LinearConstraint(A)
+ lc2 = LinearConstraint(A, -np.inf, np.inf)
+ assert_array_equal(lc.lb, lc2.lb)
+ assert_array_equal(lc.ub, lc2.ub)
+
+ def test_input_validation(self):
+ A = np.eye(4)
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable"
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A, [1, 2], [1, 2, 3])
+
+ message = "Constraint limits must be dense arrays"
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A, sps.coo_array([1, 2]), [2, 3])
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A, [1, 2], sps.coo_array([2, 3]))
+
+ message = "`keep_feasible` must be a dense array"
+ with pytest.raises(ValueError, match=message):
+ keep_feasible = sps.coo_array([True, True])
+ LinearConstraint(A, [1, 2], [2, 3], keep_feasible=keep_feasible)
+
+ A = np.empty((4, 3, 5))
+ message = "`A` must have exactly two dimensions."
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A)
+
+ def test_residual(self):
+ A = np.eye(2)
+ lc = LinearConstraint(A, -2, 4)
+ x0 = [-1, 2]
+ np.testing.assert_allclose(lc.residual(x0), ([1, 4], [5, 2]))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_abi.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_abi.py
new file mode 100644
index 0000000000000000000000000000000000000000..37d5e0a29084850a2bbab70e4e4d952e854df3a9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_abi.py
@@ -0,0 +1,87 @@
+# ---------------------------------------------------------------------------
+# AUTO-GENERATED - do not edit by hand.
+# Re-generate with: python tools/generate_cython_abi_tests.py optimize
+#
+# Generated against SciPy 1.17.1 on 2026-03-29
+# Python 3.12.13
+# ---------------------------------------------------------------------------
+
+"""
+Regression test for the cython_optimize binary interface.
+
+The __pyx_capi__ dict of each module contains PyCapsule objects whose
+*name* string encodes the C-level function signature that Cython checks
+at import time when another module does ``cimport``. Any change to
+those strings is a binary incompatibility that breaks every downstream
+package (e.g., scikit-learn, statsmodels) compiled against the previous release,
+without any compile-time warning.
+
+The expected signatures are stored in cython_abi_signatures.json.
+The test fails if:
+ * an existing name disappears, or
+ * an existing name's signature string changes.
+Adding new names is explicitly allowed (it is not a break).
+"""
+
+import ctypes
+import importlib
+import importlib.resources
+import json
+
+import pytest
+import scipy
+
+CYTHON_BLAS_ILP64 = (
+ scipy.show_config(mode='dicts')['Build Dependencies']['blas']['cython blas ilp64']
+)
+
+
+# ---------------------------------------------------------------------------
+# Helper
+# ---------------------------------------------------------------------------
+
+_get_capsule_name = ctypes.pythonapi.PyCapsule_GetName
+_get_capsule_name.restype = ctypes.c_char_p
+_get_capsule_name.argtypes = [ctypes.py_object]
+
+
+def _extract_capi(module):
+ """Return {name: signature} for every entry in module.__pyx_capi__."""
+ result = {}
+ for name, capsule in module.__pyx_capi__.items():
+ raw = _get_capsule_name(capsule)
+ if raw is not None:
+ result[name] = raw.decode('utf-8')
+ return result
+
+
+_sig_file = importlib.resources.files('scipy.optimize.tests').joinpath(
+ 'cython_abi_signatures.json'
+)
+with importlib.resources.as_file(_sig_file) as _f:
+ _EXPECTED = json.loads(_f.read_text())
+
+
+def test_cython_optimize_abi_stability():
+ """No existing cython_optimize signature may change or disappear."""
+ expected = _EXPECTED['scipy.optimize.cython_optimize._zeros']
+ mod = importlib.import_module('scipy.optimize.cython_optimize._zeros')
+ actual = _extract_capi(mod)
+ errors = []
+ for name, expected_sig in expected.items():
+ if name not in actual:
+ errors.append(
+ f"REMOVED {name!r} (was {expected_sig!r})"
+ )
+ elif actual[name] != expected_sig:
+ errors.append(
+ f"CHANGED {name!r}\n"
+ f" expected: {expected_sig!r}\n"
+ f" actual: {actual[name]!r}"
+ )
+ if errors:
+ joined = '\n'.join(errors)
+ pytest.fail(
+ f"scipy.optimize.cython_optimize._zeros.__pyx_capi__ has {len(errors)} "
+ f"ABI breakage(s):\n{joined}"
+ )
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_optimize.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f859c1143eb6b63c439fe278bfdd4fdaa15410f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_optimize.py
@@ -0,0 +1,92 @@
+"""
+Test Cython optimize zeros API functions: ``bisect``, ``ridder``, ``brenth``,
+and ``brentq`` in `scipy.optimize.cython_optimize`, by finding the roots of a
+3rd order polynomial given a sequence of constant terms, ``a0``, and fixed 1st,
+2nd, and 3rd order terms in ``args``.
+
+.. math::
+
+ f(x, a0, args) = ((args[2]*x + args[1])*x + args[0])*x + a0
+
+The 3rd order polynomial function is written in Cython and called in a Python
+wrapper named after the zero function. See the private ``_zeros`` Cython module
+in `scipy.optimize.cython_optimze` for more information.
+"""
+
+import numpy.testing as npt
+from scipy.optimize.cython_optimize import _zeros
+
+# CONSTANTS
+# Solve x**3 - A0 = 0 for A0 = [2.0, 2.1, ..., 2.9].
+# The ARGS have 3 elements just to show how this could be done for any cubic
+# polynomial.
+A0 = tuple(-2.0 - x/10.0 for x in range(10)) # constant term
+ARGS = (0.0, 0.0, 1.0) # 1st, 2nd, and 3rd order terms
+XLO, XHI = 0.0, 2.0 # first and second bounds of zeros functions
+# absolute and relative tolerances and max iterations for zeros functions
+XTOL, RTOL, MITR = 0.001, 0.001, 10
+EXPECTED = [(-a0) ** (1.0/3.0) for a0 in A0]
+# = [1.2599210498948732,
+# 1.2805791649874942,
+# 1.300591446851387,
+# 1.3200061217959123,
+# 1.338865900164339,
+# 1.3572088082974532,
+# 1.375068867074141,
+# 1.3924766500838337,
+# 1.4094597464129783,
+# 1.4260431471424087]
+
+
+# test bisect
+def test_bisect():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('bisect', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test ridder
+def test_ridder():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('ridder', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test brenth
+def test_brenth():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('brenth', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test brentq
+def test_brentq():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('brentq', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test brentq with full output
+def test_brentq_full_output():
+ output = _zeros.full_output_example(
+ (A0[0],) + ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ npt.assert_allclose(EXPECTED[0], output['root'], rtol=RTOL, atol=XTOL)
+ npt.assert_equal(6, output['iterations'])
+ npt.assert_equal(7, output['funcalls'])
+ npt.assert_equal(0, output['error_num'])
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_differentiable_functions.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a5eb8c398911e8b1547d3992916cd4983c1eb6d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_differentiable_functions.py
@@ -0,0 +1,1024 @@
+import pytest
+import numpy as np
+from numpy.testing import (TestCase, assert_array_almost_equal,
+ assert_array_equal, assert_, assert_allclose,
+ assert_equal)
+from scipy._lib._gcutils import assert_deallocated
+from scipy._lib._util import MapWrapper
+from scipy.sparse import csr_array
+from scipy.sparse.linalg import LinearOperator
+from scipy.optimize._differentiable_functions import (ScalarFunction,
+ VectorFunction,
+ LinearVectorFunction,
+ IdentityVectorFunction)
+from scipy.optimize import rosen, rosen_der, rosen_hess
+from scipy.optimize._hessian_update_strategy import BFGS
+
+
+class ExScalarFunction:
+
+ def __init__(self):
+ self.nfev = 0
+ self.ngev = 0
+ self.nhev = 0
+
+ def fun(self, x):
+ self.nfev += 1
+ return 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+
+ def grad(self, x):
+ self.ngev += 1
+ return np.array([4*x[0]-1, 4*x[1]])
+
+ def hess(self, x):
+ self.nhev += 1
+ return 4*np.eye(2)
+
+
+class TestScalarFunction(TestCase):
+
+ def test_finite_difference_grad(self):
+ ex = ExScalarFunction()
+ nfev = 0
+ ngev = 0
+
+ x0 = [1.0, 0.0]
+ analit = ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev, nfev)
+ approx = ScalarFunction(ex.fun, x0, (), '2-point',
+ ex.hess, None, (-np.inf, np.inf))
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.g, approx.g)
+
+ x = [10, 0.3]
+ f_analit = analit.fun(x)
+ g_analit = analit.grad(x)
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ f_approx = approx.fun(x)
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ x = [2.0, 1.0]
+ g_analit = analit.grad(x)
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ x = [2.5, 0.3]
+ f_analit = analit.fun(x)
+ g_analit = analit.grad(x)
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ f_approx = approx.fun(x)
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ x = [2, 0.3]
+ f_analit = analit.fun(x)
+ g_analit = analit.grad(x)
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ f_approx = approx.fun(x)
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ @pytest.mark.fail_slow(5.0)
+ def test_workers(self):
+ x0 = np.array([2.0, 0.3])
+ ex = ExScalarFunction()
+ ex2 = ExScalarFunction()
+ with MapWrapper(2) as mapper:
+ approx = ScalarFunction(ex.fun, x0, (), '2-point',
+ ex.hess, None, (-np.inf, np.inf),
+ workers=mapper)
+ approx_series = ScalarFunction(ex2.fun, x0, (), '2-point',
+ ex2.hess, None, (-np.inf, np.inf),
+ )
+ assert_allclose(approx.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.hess(x0), ex.hess(x0))
+ assert_allclose(approx.hess(x0), ex.hess(x0))
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.ngev, approx_series.ngev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ ex = ExScalarFunction()
+ ex2 = ExScalarFunction()
+ approx = ScalarFunction(ex.fun, x0, (), '3-point',
+ ex.hess, None, (-np.inf, np.inf),
+ workers=mapper)
+ approx_series = ScalarFunction(ex2.fun, x0, (), '3-point',
+ ex2.hess, None, (-np.inf, np.inf),
+ )
+ assert_allclose(approx.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.hess(x0), ex.hess(x0))
+ assert_allclose(approx.hess(x0), ex.hess(x0))
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.ngev, approx_series.ngev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ ex = ExScalarFunction()
+ ex2 = ExScalarFunction()
+ x1 = np.array([3.0, 4.0])
+
+ approx = ScalarFunction(ex.fun, x0, (), ex.grad,
+ '3-point', None, (-np.inf, np.inf),
+ workers=mapper)
+ approx_series = ScalarFunction(ex2.fun, x0, (), ex2.grad,
+ '3-point', None, (-np.inf, np.inf),
+ )
+ assert_allclose(approx.grad(x1), ex.grad(x1))
+ assert_allclose(approx_series.grad(x1), ex.grad(x1))
+ approx_series.hess(x1)
+ approx.hess(x1)
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.ngev, approx_series.ngev)
+ assert_equal(approx_series.ngev, ex2.ngev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ def test_fun_and_grad(self):
+ ex = ExScalarFunction()
+
+ def fg_allclose(x, y):
+ assert_allclose(x[0], y[0])
+ assert_allclose(x[1], y[1])
+
+ # with analytic gradient
+ x0 = [2.0, 0.3]
+ analit = ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))
+
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(analit.fun_and_grad(x0), fg)
+ assert analit.ngev == 1
+
+ x0[1] = 1.
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(analit.fun_and_grad(x0), fg)
+
+ # with finite difference gradient
+ x0 = [2.0, 0.3]
+ sf = ScalarFunction(ex.fun, x0, (), '3-point',
+ ex.hess, None, (-np.inf, np.inf))
+ assert sf.ngev == 1
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(sf.fun_and_grad(x0), fg)
+ assert sf.ngev == 1
+
+ x0[1] = 1.
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(sf.fun_and_grad(x0), fg)
+
+ def test_finite_difference_hess_linear_operator(self):
+ ex = ExScalarFunction()
+ nfev = 0
+ ngev = 0
+ nhev = 0
+
+ x0 = [1.0, 0.0]
+ analit = ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))
+ nfev += 1
+ ngev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev, nhev)
+ approx = ScalarFunction(ex.fun, x0, (), ex.grad,
+ '2-point', None, (-np.inf, np.inf))
+ assert_(isinstance(approx.H, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.g, approx.g)
+ assert_array_almost_equal(analit.H.dot(v), approx.H.dot(v))
+ nfev += 1
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.0, 1.0]
+ H_analit = analit.hess(x)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.1, 1.2]
+ H_analit = analit.hess(x)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.5, 0.3]
+ _ = analit.grad(x)
+ H_analit = analit.hess(x)
+ ngev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.grad(x)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [5.2, 2.3]
+ _ = analit.grad(x)
+ H_analit = analit.hess(x)
+ ngev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.grad(x)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ def test_x_storage_overlap(self):
+ # Scalar_Function should not store references to arrays, it should
+ # store copies - this checks that updating an array in-place causes
+ # Scalar_Function.x to be updated.
+
+ def f(x):
+ return np.sum(np.asarray(x) ** 2)
+
+ x = np.array([1., 2., 3.])
+ sf = ScalarFunction(f, x, (), '3-point', lambda x: x, None, (-np.inf, np.inf))
+
+ assert x is not sf.x
+ assert_equal(sf.fun(x), 14.0)
+ assert x is not sf.x
+
+ x[0] = 0.
+ f1 = sf.fun(x)
+ assert_equal(f1, 13.0)
+
+ x[0] = 1
+ f2 = sf.fun(x)
+ assert_equal(f2, 14.0)
+ assert x is not sf.x
+
+ # now test with a HessianUpdate strategy specified
+ hess = BFGS()
+ x = np.array([1., 2., 3.])
+ sf = ScalarFunction(f, x, (), '3-point', hess, None, (-np.inf, np.inf))
+
+ assert x is not sf.x
+ assert_equal(sf.fun(x), 14.0)
+ assert x is not sf.x
+
+ x[0] = 0.
+ f1 = sf.fun(x)
+ assert_equal(f1, 13.0)
+
+ x[0] = 1
+ f2 = sf.fun(x)
+ assert_equal(f2, 14.0)
+ assert x is not sf.x
+
+ # gh13740 x is changed in user function
+ def ff(x):
+ x *= x # overwrite x
+ return np.sum(x)
+
+ x = np.array([1., 2., 3.])
+ sf = ScalarFunction(
+ ff, x, (), '3-point', lambda x: x, None, (-np.inf, np.inf)
+ )
+ assert x is not sf.x
+ assert_equal(sf.fun(x), 14.0)
+ assert_equal(sf.x, np.array([1., 2., 3.]))
+ assert x is not sf.x
+
+ def test_lowest_x(self):
+ # ScalarFunction should remember the lowest func(x) visited.
+ x0 = np.array([2, 3, 4])
+ sf = ScalarFunction(rosen, x0, (), rosen_der, rosen_hess,
+ None, None)
+ sf.fun([1, 1, 1])
+ sf.fun(x0)
+ sf.fun([1.01, 1, 1.0])
+ sf.grad([1.01, 1, 1.0])
+ assert_equal(sf._lowest_f, 0.0)
+ assert_equal(sf._lowest_x, [1.0, 1.0, 1.0])
+
+ sf = ScalarFunction(rosen, x0, (), '2-point', rosen_hess,
+ None, (-np.inf, np.inf))
+ sf.fun([1, 1, 1])
+ sf.fun(x0)
+ sf.fun([1.01, 1, 1.0])
+ sf.grad([1.01, 1, 1.0])
+ assert_equal(sf._lowest_f, 0.0)
+ assert_equal(sf._lowest_x, [1.0, 1.0, 1.0])
+
+ def test_float_size(self):
+ x0 = np.array([2, 3, 4]).astype(np.float32)
+
+ # check that ScalarFunction/approx_derivative always send the correct
+ # float width
+ def rosen_(x):
+ assert x.dtype == np.float32
+ return rosen(x)
+
+ sf = ScalarFunction(rosen_, x0, (), '2-point', rosen_hess,
+ None, (-np.inf, np.inf))
+ res = sf.fun(x0)
+ assert res.dtype == np.float32
+
+ # checks that ScalarFunction.fun returns a value with the same float
+ # precision as the unwrapped function would call.
+ def fun(x):
+ return x**4 - x
+
+ x0 = np.array([1.2], dtype=np.float32)
+ sf = ScalarFunction(fun, x0, (), '2-point', lambda x: None,
+ None, (-np.inf, np.inf))
+ fx = sf.fun(x0)
+ assert fun(x0).dtype == np.float32
+ assert fx.dtype == np.float32
+ # check that the round trip cast works as intended
+ assert_equal(fx, fun(x0))
+
+
+class ExVectorialFunction:
+
+ def __init__(self):
+ self.nfev = 0
+ self.njev = 0
+ self.nhev = 0
+
+ def fun(self, x):
+ self.nfev += 1
+ return np.array([2*(x[0]**2 + x[1]**2 - 1) - x[0],
+ 4*(x[0]**3 + x[1]**2 - 4) - 3*x[0]], dtype=x.dtype)
+
+ def jac(self, x):
+ self.njev += 1
+ return np.array([[4*x[0]-1, 4*x[1]],
+ [12*x[0]**2-3, 8*x[1]]], dtype=x.dtype)
+
+ def hess(self, x, v):
+ self.nhev += 1
+ return v[0]*4*np.eye(2) + v[1]*np.array([[24*x[0], 0],
+ [0, 8]])
+
+
+class TestVectorialFunction(TestCase):
+
+ def test_finite_difference_jac(self):
+ ex = ExVectorialFunction()
+ nfev = 0
+ njev = 0
+
+ x0 = [1.0, 0.0]
+ analit = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev, njev)
+ # create with defaults for the keyword arguments, to
+ # ensure that the defaults work
+ approx = VectorFunction(ex.fun, x0, '2-point', ex.hess)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.J, approx.J)
+
+ x = [10, 0.3]
+ f_analit = analit.fun(x)
+ J_analit = analit.jac(x)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ f_approx = approx.fun(x)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(J_analit, J_approx, decimal=4)
+
+ x = [2.0, 1.0]
+ J_analit = analit.jac(x)
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(J_analit, J_approx)
+
+ x = [2.5, 0.3]
+ f_analit = analit.fun(x)
+ J_analit = analit.jac(x)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ f_approx = approx.fun(x)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(J_analit, J_approx)
+
+ x = [2, 0.3]
+ f_analit = analit.fun(x)
+ J_analit = analit.jac(x)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ f_approx = approx.fun(x)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(J_analit, J_approx)
+
+ def test_updating_on_initial_setup(self):
+ # Check that memoisation works with the freshly created VectorFunction
+ # On initialization vf.f_updated attribute wasn't being set correctly.
+ x0 = np.array([2.5, 3.0])
+ ex = ExVectorialFunction()
+ vf = VectorFunction(ex.fun, x0, ex.jac, ex.hess)
+ assert vf.f_updated
+ assert vf.nfev == 1
+ assert vf.njev == 1
+ assert ex.nfev == 1
+ assert ex.njev == 1
+ vf.fun(x0)
+ vf.jac(x0)
+ assert vf.nfev == 1
+ assert vf.njev == 1
+ assert ex.nfev == 1
+ assert ex.njev == 1
+
+ @pytest.mark.fail_slow(5.0)
+ def test_workers(self):
+ x0 = np.array([2.5, 3.0])
+ ex = ExVectorialFunction()
+ ex2 = ExVectorialFunction()
+ v = np.array([1.0, 2.0])
+
+ with MapWrapper(2) as mapper:
+ approx = VectorFunction(ex.fun, x0, '2-point',
+ ex.hess, None, None, (-np.inf, np.inf),
+ False, workers=mapper)
+ approx_series = VectorFunction(ex2.fun, x0, '2-point',
+ ex2.hess, None, None, (-np.inf, np.inf),
+ False)
+
+ assert_allclose(approx.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.hess(x0, v), ex.hess(x0, v))
+ assert_allclose(approx.hess(x0, v), ex.hess(x0, v))
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.njev, approx_series.njev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ ex.nfev = ex.njev = ex.nhev = 0
+ ex2.nfev = ex2.njev = ex2.nhev = 0
+ approx = VectorFunction(ex.fun, x0, '3-point',
+ ex.hess, None, None, (-np.inf, np.inf),
+ False, workers=mapper)
+ approx_series = VectorFunction(ex2.fun, x0, '3-point',
+ ex2.hess, None, None, (-np.inf, np.inf),
+ False)
+ assert_allclose(approx.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.hess(x0, v), ex.hess(x0, v))
+ assert_allclose(approx.hess(x0, v), ex.hess(x0, v))
+
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.njev, approx_series.njev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ # The following tests are somewhat redundant because the LinearOperator
+ # produced by VectorFunction.hess does not use any parallelisation.
+ # The tests are left for completeness, in case that situation changes.
+ ex.nfev = ex.njev = ex.nhev = 0
+ ex2.nfev = ex2.njev = ex2.nhev = 0
+ approx = VectorFunction(ex.fun, x0, ex.jac,
+ '2-point', None, None, (-np.inf, np.inf),
+ False, workers=mapper)
+ approx_series = VectorFunction(ex2.fun, x0, ex2.jac,
+ '2-point', None, None, (-np.inf, np.inf),
+ False)
+ assert_allclose(approx.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.jac(x0), ex.jac(x0))
+
+ H_analit = ex2.hess(x0, v)
+ H_approx_series = approx_series.hess(x0, v)
+ H_approx = approx.hess(x0, v)
+ x = [5, 2.0]
+ assert_allclose(H_approx.dot(x), H_analit.dot(x))
+ assert_allclose(H_approx_series.dot(x), H_analit.dot(x))
+
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.njev, approx_series.njev)
+ assert_equal(approx.nhev, approx_series.nhev)
+
+ def test_finite_difference_hess_linear_operator(self):
+ ex = ExVectorialFunction()
+ nfev = 0
+ njev = 0
+ nhev = 0
+
+ x0 = [1.0, 0.0]
+ v0 = [1.0, 2.0]
+ analit = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ nfev += 1
+ njev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev, nhev)
+ approx = VectorFunction(ex.fun, x0, ex.jac, '2-point', None, None,
+ (-np.inf, np.inf), None)
+ assert_(isinstance(approx.H, LinearOperator))
+ for p in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.J, approx.J)
+ assert_array_almost_equal(analit.H.dot(p), approx.H.dot(p))
+ nfev += 1
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.0, 1.0]
+ H_analit = analit.hess(x, v0)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x, v0)
+ assert_(isinstance(H_approx, LinearOperator))
+ for p in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(p), H_approx.dot(p),
+ decimal=5)
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.1, 1.2]
+ v = [1.0, 1.0]
+ H_analit = analit.hess(x, v)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x, v)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.5, 0.3]
+ _ = analit.jac(x)
+ H_analit = analit.hess(x, v0)
+ njev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.jac(x)
+ H_approx = approx.hess(x, v0)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v), decimal=4)
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [5.2, 2.3]
+ v = [2.3, 5.2]
+ _ = analit.jac(x)
+ H_analit = analit.hess(x, v)
+ njev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.jac(x)
+ H_approx = approx.hess(x, v)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v), decimal=4)
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ # Test VectorFunction.hess_wrapped with J0=None
+ x = np.array([1.5, 0.5])
+ v = np.array([1.0, 2.0])
+ njev_before = approx.hess_wrapped.njev
+ H = approx.hess_wrapped(x, v, J0=None)
+ assert isinstance(H, LinearOperator)
+ # The njev counter should be incremented by exactly 1
+ assert approx.hess_wrapped.njev == njev_before + 1
+
+ def test_fgh_overlap(self):
+ # VectorFunction.fun/jac should return copies to internal attributes
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+
+ vf = VectorFunction(ex.fun, x0, '3-point', ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ f = vf.fun(np.array([1.1, 0.1]))
+ J = vf.jac([1.1, 0.1])
+ assert vf.f is not f
+ assert vf.J is not J
+ assert_equal(f, vf.f)
+ assert_equal(J, vf.J)
+
+ vf = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ f = vf.fun(np.array([1.1, 0.1]))
+ J = vf.jac([1.1, 0.1])
+ assert vf.f is not f
+ assert vf.J is not J
+ assert_equal(f, vf.f)
+ assert_equal(J, vf.J)
+
+ def test_x_storage_overlap(self):
+ # VectorFunction should not store references to arrays, it should
+ # store copies - this checks that updating an array in-place causes
+ # Scalar_Function.x to be updated.
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+
+ vf = VectorFunction(ex.fun, x0, '3-point', ex.hess, None, None,
+ (-np.inf, np.inf), None)
+
+ assert x0 is not vf.x
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 2.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 1.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ # now test with a HessianUpdate strategy specified
+ hess = BFGS()
+ x0 = np.array([1.0, 0.0])
+ vf = VectorFunction(ex.fun, x0, '3-point', hess, None, None,
+ (-np.inf, np.inf), None)
+
+ with pytest.warns(UserWarning):
+ # filter UserWarning because ExVectorialFunction is linear and
+ # a quasi-Newton approximation is used for the Hessian.
+ assert x0 is not vf.x
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 2.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 1.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ def test_float_size(self):
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0]).astype(np.float32)
+
+ vf = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+
+ res = vf.fun(x0)
+ assert res.dtype == np.float32
+
+ res = vf.jac(x0)
+ assert res.dtype == np.float32
+
+ def test_sparse_analytic_jac(self):
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+ def sparse_adapter(func):
+ def inner(x):
+ f_x = func(x)
+ return csr_array(f_x)
+ return inner
+
+ # jac(x) returns dense jacobian
+ vf1 = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), sparse_jacobian=None)
+ # jac(x) returns sparse jacobian, but sparse_jacobian=False requests dense
+ vf2 = VectorFunction(ex.fun, x0, sparse_adapter(ex.jac), ex.hess, None, None,
+ (-np.inf, np.inf), sparse_jacobian=False)
+
+ res1 = vf1.jac(x0 + 1)
+ res2 = vf2.jac(x0 + 1)
+ assert_equal(res1, res2)
+
+ def test_sparse_numerical_jac(self):
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+ N = len(x0)
+
+ # normal dense numerical difference
+ vf1 = VectorFunction(ex.fun, x0, '2-point', ex.hess, None, None,
+ (-np.inf, np.inf), sparse_jacobian=None)
+ # use sparse numerical difference, but ask it to be converted to dense
+ finite_diff_jac_sparsity = csr_array(np.ones((N, N)))
+ vf2 = VectorFunction(ex.fun, x0, '2-point', ex.hess, None,
+ finite_diff_jac_sparsity, (-np.inf, np.inf),
+ sparse_jacobian=False)
+
+ res1 = vf1.jac(x0 + 1)
+ res2 = vf2.jac(x0 + 1)
+ assert_equal(res1, res2)
+
+
+def test_LinearVectorFunction():
+ A_dense = np.array([
+ [-1, 2, 0],
+ [0, 4, 2]
+ ])
+ x0 = np.zeros(3)
+ A_sparse = csr_array(A_dense)
+ x = np.array([1, -1, 0])
+ v = np.array([-1, 1])
+ Ax = np.array([-3, -4])
+
+ f1 = LinearVectorFunction(A_dense, x0, None)
+ assert_(not f1.sparse_jacobian)
+
+ f2 = LinearVectorFunction(A_dense, x0, True)
+ assert_(f2.sparse_jacobian)
+
+ f3 = LinearVectorFunction(A_dense, x0, False)
+ assert_(not f3.sparse_jacobian)
+
+ f4 = LinearVectorFunction(A_sparse, x0, None)
+ assert_(f4.sparse_jacobian)
+
+ f5 = LinearVectorFunction(A_sparse, x0, True)
+ assert_(f5.sparse_jacobian)
+
+ f6 = LinearVectorFunction(A_sparse, x0, False)
+ assert_(not f6.sparse_jacobian)
+
+ assert_array_equal(f1.fun(x), Ax)
+ assert_array_equal(f2.fun(x), Ax)
+ assert_array_equal(f1.jac(x), A_dense)
+ assert_array_equal(f2.jac(x).toarray(), A_sparse.toarray())
+ assert_array_equal(f1.hess(x, v).toarray(), np.zeros((3, 3)))
+
+
+def test_LinearVectorFunction_memoization():
+ A = np.array([[-1, 2, 0], [0, 4, 2]])
+ x0 = np.array([1, 2, -1])
+ fun = LinearVectorFunction(A, x0, False)
+
+ assert_array_equal(x0, fun.x)
+ assert_array_equal(A.dot(x0), fun.f)
+
+ x1 = np.array([-1, 3, 10])
+ assert_array_equal(A, fun.jac(x1))
+ assert_array_equal(x1, fun.x)
+ assert_array_equal(A.dot(x0), fun.f)
+ assert_array_equal(A.dot(x1), fun.fun(x1))
+ assert_array_equal(A.dot(x1), fun.f)
+
+
+def test_IdentityVectorFunction():
+ x0 = np.zeros(3)
+
+ f1 = IdentityVectorFunction(x0, None)
+ f2 = IdentityVectorFunction(x0, False)
+ f3 = IdentityVectorFunction(x0, True)
+
+ assert_(f1.sparse_jacobian)
+ assert_(not f2.sparse_jacobian)
+ assert_(f3.sparse_jacobian)
+
+ x = np.array([-1, 2, 1])
+ v = np.array([-2, 3, 0])
+
+ assert_array_equal(f1.fun(x), x)
+ assert_array_equal(f2.fun(x), x)
+
+ assert_array_equal(f1.jac(x).toarray(), np.eye(3))
+ assert_array_equal(f2.jac(x), np.eye(3))
+
+ assert_array_equal(f1.hess(x, v).toarray(), np.zeros((3, 3)))
+
+
+def test_ScalarFunctionNoReferenceCycle():
+ """Regression test for gh-20768."""
+ ex = ExScalarFunction()
+ x0 = np.zeros(3)
+ with assert_deallocated(lambda: ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))):
+ pass
+
+
+def test_VectorFunctionNoReferenceCycle():
+ """Regression test for gh-20768."""
+ ex = ExVectorialFunction()
+ x0 = [1.0, 0.0]
+ with assert_deallocated(lambda: VectorFunction(ex.fun, x0, ex.jac,
+ ex.hess, None, None, (-np.inf, np.inf), None)):
+ pass
+
+
+def test_LinearVectorFunctionNoReferenceCycle():
+ """Regression test for gh-20768."""
+ A_dense = np.array([
+ [-1, 2, 0],
+ [0, 4, 2]
+ ])
+ x0 = np.zeros(3)
+ A_sparse = csr_array(A_dense)
+ with assert_deallocated(lambda: LinearVectorFunction(A_sparse, x0, None)):
+ pass
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_direct.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_direct.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2a6631e6b2007e9bed9eb68481877a7a2afff98
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_direct.py
@@ -0,0 +1,332 @@
+"""
+Unit test for DIRECT optimization algorithm.
+"""
+from numpy.testing import (assert_allclose,
+ assert_array_less)
+import pytest
+import numpy as np
+from scipy.optimize import direct, Bounds
+import threading
+
+
+class TestDIRECT:
+
+ def setup_method(self):
+ self.fun_calls = threading.local()
+ self.bounds_sphere = 4*[(-2, 3)]
+ self.optimum_sphere_pos = np.zeros((4, ))
+ self.optimum_sphere = 0.0
+ self.bounds_stylinski_tang = Bounds([-4., -4.], [4., 4.])
+ self.maxiter = 1000
+
+ # test functions
+ def sphere(self, x):
+ if not hasattr(self.fun_calls, 'c'):
+ self.fun_calls.c = 0
+ self.fun_calls.c += 1
+ return np.square(x).sum()
+
+ def inv(self, x):
+ if np.sum(x) == 0:
+ raise ZeroDivisionError()
+ return 1/np.sum(x)
+
+ def nan_fun(self, x):
+ return np.nan
+
+ def inf_fun(self, x):
+ return np.inf
+
+ def styblinski_tang(self, pos):
+ x, y = pos
+ return 0.5 * (x**4 - 16 * x**2 + 5 * x + y**4 - 16 * y**2 + 5 * y)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_direct(self, locally_biased):
+ res = direct(self.sphere, self.bounds_sphere,
+ locally_biased=locally_biased)
+
+ # test accuracy
+ assert_allclose(res.x, self.optimum_sphere_pos,
+ rtol=1e-3, atol=1e-3)
+ assert_allclose(res.fun, self.optimum_sphere, atol=1e-5, rtol=1e-5)
+
+ # test that result lies within bounds
+ _bounds = np.asarray(self.bounds_sphere)
+ assert_array_less(_bounds[:, 0], res.x)
+ assert_array_less(res.x, _bounds[:, 1])
+
+ # test number of function evaluations. Original DIRECT overshoots by
+ # up to 500 evaluations in last iteration
+ assert res.nfev <= 1000 * (len(self.bounds_sphere) + 1)
+ # test that number of function evaluations is correct
+ assert res.nfev == self.fun_calls.c
+
+ # test that number of iterations is below supplied maximum
+ assert res.nit <= self.maxiter
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_direct_callback(self, locally_biased):
+ # test that callback does not change the result
+ res = direct(self.sphere, self.bounds_sphere,
+ locally_biased=locally_biased)
+
+ def callback(x):
+ x = 2*x
+ dummy = np.square(x)
+ print("DIRECT minimization algorithm callback test")
+ return dummy
+
+ res_callback = direct(self.sphere, self.bounds_sphere,
+ locally_biased=locally_biased,
+ callback=callback)
+
+ assert_allclose(res.x, res_callback.x)
+
+ assert res.nit == res_callback.nit
+ assert res.nfev == res_callback.nfev
+ assert res.status == res_callback.status
+ assert res.success == res_callback.success
+ assert res.fun == res_callback.fun
+ assert_allclose(res.x, res_callback.x)
+ assert res.message == res_callback.message
+
+ # test accuracy
+ assert_allclose(res_callback.x, self.optimum_sphere_pos,
+ rtol=1e-3, atol=1e-3)
+ assert_allclose(res_callback.fun, self.optimum_sphere,
+ atol=1e-5, rtol=1e-5)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_exception(self, locally_biased):
+ bounds = 4*[(-10, 10)]
+ with pytest.raises(ZeroDivisionError):
+ direct(self.inv, bounds=bounds,
+ locally_biased=locally_biased)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_nan(self, locally_biased):
+ bounds = 4*[(-10, 10)]
+ direct(self.nan_fun, bounds=bounds,
+ locally_biased=locally_biased)
+
+ @pytest.mark.parametrize("len_tol", [1e-3, 1e-4])
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_len_tol(self, len_tol, locally_biased):
+ bounds = 4*[(-10., 10.)]
+ res = direct(self.sphere, bounds=bounds, len_tol=len_tol,
+ vol_tol=1e-30, locally_biased=locally_biased)
+ assert res.status == 5
+ assert res.success
+ assert_allclose(res.x, np.zeros((4, )))
+ message = ("The side length measure of the hyperrectangle containing "
+ "the lowest function value found is below "
+ f"len_tol={len_tol}")
+ assert res.message == message
+
+ @pytest.mark.parametrize("vol_tol", [1e-6, 1e-8])
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_vol_tol(self, vol_tol, locally_biased):
+ bounds = 4*[(-10., 10.)]
+ res = direct(self.sphere, bounds=bounds, vol_tol=vol_tol,
+ len_tol=0., locally_biased=locally_biased)
+ assert res.status == 4
+ assert res.success
+ assert_allclose(res.x, np.zeros((4, )))
+ message = ("The volume of the hyperrectangle containing the lowest "
+ f"function value found is below vol_tol={vol_tol}")
+ assert res.message == message
+
+ @pytest.mark.parametrize("f_min_rtol", [1e-3, 1e-5, 1e-7])
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_f_min(self, f_min_rtol, locally_biased):
+ # test that desired function value is reached within
+ # relative tolerance of f_min_rtol
+ f_min = 1.
+ bounds = 4*[(-2., 10.)]
+ res = direct(self.sphere, bounds=bounds, f_min=f_min,
+ f_min_rtol=f_min_rtol,
+ locally_biased=locally_biased)
+ assert res.status == 3
+ assert res.success
+ assert res.fun < f_min * (1. + f_min_rtol)
+ message = ("The best function value found is within a relative "
+ f"error={f_min_rtol} of the (known) global optimum f_min")
+ assert res.message == message
+
+ def circle_with_args(self, x, a, b):
+ return np.square(x[0] - a) + np.square(x[1] - b).sum()
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_f_circle_with_args(self, locally_biased):
+ bounds = 2*[(-2.0, 2.0)]
+
+ res = direct(self.circle_with_args, bounds, args=(1, 1), maxfun=1250,
+ locally_biased=locally_biased)
+ assert_allclose(res.x, np.array([1., 1.]), rtol=1e-5)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_failure_maxfun(self, locally_biased):
+ # test that if optimization runs for the maximal number of
+ # evaluations, success = False is returned
+
+ maxfun = 100
+ result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxfun=maxfun, locally_biased=locally_biased)
+ assert result.success is False
+ assert result.status == 1
+ assert result.nfev >= maxfun
+ message = ("Number of function evaluations done is "
+ f"larger than maxfun={maxfun}")
+ assert result.message == message
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_failure_maxiter(self, locally_biased):
+ # test that if optimization runs for the maximal number of
+ # iterations, success = False is returned
+
+ maxiter = 10
+ result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxiter=maxiter, locally_biased=locally_biased)
+ assert result.success is False
+ assert result.status == 2
+ assert result.nit >= maxiter
+ message = f"Number of iterations is larger than maxiter={maxiter}"
+ assert result.message == message
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_bounds_variants(self, locally_biased):
+ # test that new and old bounds yield same result
+
+ lb = [-6., 1., -5.]
+ ub = [-1., 3., 5.]
+ x_opt = np.array([-1., 1., 0.])
+ bounds_old = list(zip(lb, ub))
+ bounds_new = Bounds(lb, ub)
+
+ res_old_bounds = direct(self.sphere, bounds_old,
+ locally_biased=locally_biased)
+ res_new_bounds = direct(self.sphere, bounds_new,
+ locally_biased=locally_biased)
+
+ assert res_new_bounds.nfev == res_old_bounds.nfev
+ assert res_new_bounds.message == res_old_bounds.message
+ assert res_new_bounds.success == res_old_bounds.success
+ assert res_new_bounds.nit == res_old_bounds.nit
+ assert_allclose(res_new_bounds.x, res_old_bounds.x)
+ assert_allclose(res_new_bounds.x, x_opt, rtol=1e-2)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ @pytest.mark.parametrize("eps", [1e-5, 1e-4, 1e-3])
+ def test_epsilon(self, eps, locally_biased):
+ result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ eps=eps, vol_tol=1e-6,
+ locally_biased=locally_biased)
+ assert result.status == 4
+ assert result.success
+
+ @pytest.mark.xslow
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_no_segmentation_fault(self, locally_biased):
+ # test that an excessive number of function evaluations
+ # does not result in segmentation fault
+ bounds = [(-5., 20.)] * 100
+ result = direct(self.sphere, bounds, maxfun=10000000,
+ maxiter=1000000, locally_biased=locally_biased)
+ assert result is not None
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_inf_fun(self, locally_biased):
+ # test that an objective value of infinity does not crash DIRECT
+ bounds = [(-5., 5.)] * 2
+ result = direct(self.inf_fun, bounds,
+ locally_biased=locally_biased)
+ assert result is not None
+
+ @pytest.mark.parametrize("len_tol", [-1, 2])
+ def test_len_tol_validation(self, len_tol):
+ error_msg = "len_tol must be between 0 and 1."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ len_tol=len_tol)
+
+ @pytest.mark.parametrize("vol_tol", [-1, 2])
+ def test_vol_tol_validation(self, vol_tol):
+ error_msg = "vol_tol must be between 0 and 1."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ vol_tol=vol_tol)
+
+ @pytest.mark.parametrize("f_min_rtol", [-1, 2])
+ def test_fmin_rtol_validation(self, f_min_rtol):
+ error_msg = "f_min_rtol must be between 0 and 1."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ f_min_rtol=f_min_rtol, f_min=0.)
+
+ @pytest.mark.parametrize("maxfun", [1.5, "string", (1, 2)])
+ def test_maxfun_wrong_type(self, maxfun):
+ error_msg = "maxfun must be of type int."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxfun=maxfun)
+
+ @pytest.mark.parametrize("maxiter", [1.5, "string", (1, 2)])
+ def test_maxiter_wrong_type(self, maxiter):
+ error_msg = "maxiter must be of type int."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxiter=maxiter)
+
+ def test_negative_maxiter(self):
+ error_msg = "maxiter must be > 0."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxiter=-1)
+
+ def test_negative_maxfun(self):
+ error_msg = "maxfun must be > 0."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxfun=-1)
+
+ @pytest.mark.parametrize("bounds", ["bounds", 2., 0])
+ def test_invalid_bounds_type(self, bounds):
+ error_msg = ("bounds must be a sequence or "
+ "instance of Bounds class")
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, bounds)
+
+ @pytest.mark.parametrize("bounds",
+ [Bounds([-1., -1], [-2, 1]),
+ Bounds([-np.nan, -1], [-2, np.nan]),
+ ]
+ )
+ def test_incorrect_bounds(self, bounds):
+ error_msg = 'Bounds are not consistent min < max'
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, bounds)
+
+ def test_inf_bounds(self):
+ error_msg = 'Bounds must not be inf.'
+ bounds = Bounds([-np.inf, -1], [-2, np.inf])
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, bounds)
+
+ def test_empty_bounds(self):
+ # gh-25086: empty Bounds() is invalid. This is checked at
+ # Bounds() init time, but the C kernel has an additional
+ # defense-in-depth check, which we exercise here.
+ bounds = Bounds([-1.0], [1.0])
+ bounds.lb = []
+ bounds.ub = []
+ error_msg = "DIRECT requires at least one dimension, got 0"
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, bounds)
+
+ @pytest.mark.parametrize("locally_biased", ["bias", [0, 0], 2.])
+ def test_locally_biased_validation(self, locally_biased):
+ error_msg = 'locally_biased must be True or False.'
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ locally_biased=locally_biased)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_extending.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..279cac794e5f453fee52f19026f96eb530259485
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_extending.py
@@ -0,0 +1,28 @@
+import os
+import platform
+import sysconfig
+
+import pytest
+
+from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython
+
+
+@pytest.mark.fail_slow(40)
+# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
+@pytest.mark.skipif(IS_EDITABLE,
+ reason='Editable install cannot find .pxd headers.')
+@pytest.mark.skipif((platform.system() == 'Windows' and
+ sysconfig.get_config_var('Py_GIL_DISABLED')),
+ reason='gh-22039')
+@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
+ reason="Can't start subprocess")
+@pytest.mark.skipif(cython is None, reason="requires cython")
+def test_cython(tmp_path):
+ srcdir = os.path.dirname(os.path.dirname(__file__))
+ extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
+ # actually test the cython c-extensions
+ # From docstring for scipy.optimize.cython_optimize module
+ x = extensions.brentq_example()
+ assert x == 0.6999942848231314
+ x = extensions_cpp.brentq_example()
+ assert x == 0.6999942848231314
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2434e92434ff2ecc74ce2e8b8119632207fd0853
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py
@@ -0,0 +1,300 @@
+import re
+from copy import deepcopy
+
+import numpy as np
+import pytest
+from numpy.linalg import norm
+from numpy.testing import (TestCase, assert_array_almost_equal,
+ assert_array_equal, assert_array_less)
+from scipy.optimize import (BFGS, SR1)
+
+
+class Rosenbrock:
+ """Rosenbrock function.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
+ """
+
+ def __init__(self, n=2, random_state=0):
+ rng = np.random.RandomState(random_state)
+ self.x0 = rng.uniform(-1, 1, n)
+ self.x_opt = np.ones(n)
+
+ def fun(self, x):
+ x = np.asarray(x)
+ r = np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
+ axis=0)
+ return r
+
+ def grad(self, x):
+ x = np.asarray(x)
+ xm = x[1:-1]
+ xm_m1 = x[:-2]
+ xm_p1 = x[2:]
+ der = np.zeros_like(x)
+ der[1:-1] = (200 * (xm - xm_m1**2) -
+ 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
+ der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
+ der[-1] = 200 * (x[-1] - x[-2]**2)
+ return der
+
+ def hess(self, x):
+ x = np.atleast_1d(x)
+ H = np.diag(-400 * x[:-1], 1) - np.diag(400 * x[:-1], -1)
+ diagonal = np.zeros(len(x), dtype=x.dtype)
+ diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2
+ diagonal[-1] = 200
+ diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:]
+ H = H + np.diag(diagonal)
+ return H
+
+
+class TestHessianUpdateStrategy(TestCase):
+
+
+ def test_hessian_initialization(self):
+
+ ndims = 5
+ symmetric_matrix = np.array([[43, 24, 33, 34, 49],
+ [24, 36, 44, 15, 44],
+ [33, 44, 37, 1, 30],
+ [34, 15, 1, 5, 46],
+ [49, 44, 30, 46, 22]])
+ init_scales = (
+ ('auto', np.eye(ndims)),
+ (2, np.eye(ndims) * 2),
+ (np.arange(1, ndims + 1) * np.eye(ndims),
+ np.arange(1, ndims + 1) * np.eye(ndims)),
+ (symmetric_matrix, symmetric_matrix),)
+ for approx_type in ['hess', 'inv_hess']:
+ for init_scale, true_matrix in init_scales:
+ # large min_{denominator,curvatur} makes them skip an update,
+ # so we can have our initial matrix
+ quasi_newton = (BFGS(init_scale=init_scale,
+ min_curvature=1e50,
+ exception_strategy='skip_update'),
+ SR1(init_scale=init_scale,
+ min_denominator=1e50))
+
+ for qn in quasi_newton:
+ qn.initialize(ndims, approx_type)
+ B = qn.get_matrix()
+
+ assert_array_equal(B, np.eye(ndims))
+ # don't test the auto init scale
+ if isinstance(init_scale, str) and init_scale == 'auto':
+ continue
+
+ qn.update(np.ones(ndims) * 1e-5, np.arange(ndims) + 0.2)
+ B = qn.get_matrix()
+ assert_array_equal(B, true_matrix)
+
+ # For this list of points, it is known
+ # that no exception occur during the
+ # Hessian update. Hence no update is
+ # skiped or damped.
+
+
+ def test_initialize_catch_illegal(self):
+ ndims = 3
+ # no complex allowed
+ inits_msg_errtype = ((complex(3.14),
+ r"float\(\) argument must be a string or a "
+ r"(real )?number, not 'complex'",
+ TypeError),
+
+ (np.array([3.2, 2.3, 1.2]).astype(np.complex128),
+ "init_scale contains complex elements, "
+ "must be real.",
+ TypeError),
+
+ (np.array([[43, 24, 33],
+ [24, 36, 44, ],
+ [33, 44, 37, ]]).astype(np.complex128),
+ "init_scale contains complex elements, "
+ "must be real.",
+ TypeError),
+
+ # not square
+ (np.array([[43, 55, 66]]),
+ re.escape(
+ "If init_scale is an array, it must have the "
+ "dimensions of the hess/inv_hess: (3, 3)."
+ " Got (1, 3)."),
+ ValueError),
+
+ # not symmetric
+ (np.array([[43, 24, 33],
+ [24.1, 36, 44, ],
+ [33, 44, 37, ]]),
+ re.escape("If init_scale is an array, it must be"
+ " symmetric (passing scipy.linalg.issymmetric)"
+ " to be an approximation of a hess/inv_hess."),
+ ValueError),
+ )
+ for approx_type in ['hess', 'inv_hess']:
+ for init_scale, message, errortype in inits_msg_errtype:
+ # large min_{denominator,curvatur} makes it skip an update,
+ # so we can retrieve our initial matrix
+ quasi_newton = (BFGS(init_scale=init_scale),
+ SR1(init_scale=init_scale))
+
+ for qn in quasi_newton:
+ qn.initialize(ndims, approx_type)
+ with pytest.raises(errortype, match=message):
+ qn.update(np.ones(ndims), np.arange(ndims))
+
+ def test_rosenbrock_with_no_exception(self):
+ # Define auxiliary problem
+ prob = Rosenbrock(n=5)
+ # Define iteration points
+ x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
+ [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
+ [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
+ [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
+ [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
+ [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
+ [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184],
+ [0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563],
+ [0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537],
+ [0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809],
+ [0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541],
+ [0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401],
+ [0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230],
+ [0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960],
+ [0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702],
+ [0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661],
+ [0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276],
+ [0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185],
+ [0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338],
+ [0.9190793, 0.8486480, 0.7163332, 0.5083780, 0.26107691],
+ [0.9371223, 0.8762177, 0.7653702, 0.5773109, 0.32181041],
+ [0.9554613, 0.9119893, 0.8282687, 0.6776178, 0.43162744],
+ [0.9545744, 0.9099264, 0.8270244, 0.6822220, 0.45237623],
+ [0.9688112, 0.9351710, 0.8730961, 0.7546601, 0.56622448],
+ [0.9743227, 0.9491953, 0.9005150, 0.8086497, 0.64505437],
+ [0.9807345, 0.9638853, 0.9283012, 0.8631675, 0.73812581],
+ [0.9886746, 0.9777760, 0.9558950, 0.9123417, 0.82726553],
+ [0.9899096, 0.9803828, 0.9615592, 0.9255600, 0.85822149],
+ [0.9969510, 0.9935441, 0.9864657, 0.9726775, 0.94358663],
+ [0.9979533, 0.9960274, 0.9921724, 0.9837415, 0.96626288],
+ [0.9995981, 0.9989171, 0.9974178, 0.9949954, 0.99023356],
+ [1.0002640, 1.0005088, 1.0010594, 1.0021161, 1.00386912],
+ [0.9998903, 0.9998459, 0.9997795, 0.9995484, 0.99916305],
+ [1.0000008, 0.9999905, 0.9999481, 0.9998903, 0.99978047],
+ [1.0000004, 0.9999983, 1.0000001, 1.0000031, 1.00000297],
+ [0.9999995, 1.0000003, 1.0000005, 1.0000001, 1.00000032],
+ [0.9999999, 0.9999997, 0.9999994, 0.9999989, 0.99999786],
+ [0.9999999, 0.9999999, 0.9999999, 0.9999999, 0.99999991]]
+ # Get iteration points
+ grad_list = [prob.grad(x) for x in x_list]
+ delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
+ for i in range(len(x_list)-1)]
+ delta_grad = [grad_list[i+1]-grad_list[i]
+ for i in range(len(grad_list)-1)]
+ # Check curvature condition
+ for s, y in zip(delta_x, delta_grad):
+ if np.dot(s, y) <= 0:
+ raise ArithmeticError()
+ # Define QuasiNewton update
+ for quasi_newton in (BFGS(init_scale=1, min_curvature=1e-4),
+ SR1(init_scale=1)):
+ hess = deepcopy(quasi_newton)
+ inv_hess = deepcopy(quasi_newton)
+ hess.initialize(len(x_list[0]), 'hess')
+ inv_hess.initialize(len(x_list[0]), 'inv_hess')
+ # Compare the hessian and its inverse
+ for s, y in zip(delta_x, delta_grad):
+ hess.update(s, y)
+ inv_hess.update(s, y)
+ B = hess.get_matrix()
+ H = inv_hess.get_matrix()
+ assert_array_almost_equal(np.linalg.inv(B), H, decimal=10)
+ B_true = prob.hess(x_list[len(delta_x)])
+ assert_array_less(norm(B - B_true)/norm(B_true), 0.1)
+
+ def test_SR1_skip_update(self):
+ # Define auxiliary problem
+ prob = Rosenbrock(n=5)
+ # Define iteration points
+ x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
+ [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
+ [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
+ [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
+ [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
+ [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
+ [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184],
+ [0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563],
+ [0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537],
+ [0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809],
+ [0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541],
+ [0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401],
+ [0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230],
+ [0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960],
+ [0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702],
+ [0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661],
+ [0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276],
+ [0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185],
+ [0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338]]
+ # Get iteration points
+ grad_list = [prob.grad(x) for x in x_list]
+ delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
+ for i in range(len(x_list)-1)]
+ delta_grad = [grad_list[i+1]-grad_list[i]
+ for i in range(len(grad_list)-1)]
+ hess = SR1(init_scale=1, min_denominator=1e-2)
+ hess.initialize(len(x_list[0]), 'hess')
+ # Compare the Hessian and its inverse
+ for i in range(len(delta_x)-1):
+ s = delta_x[i]
+ y = delta_grad[i]
+ hess.update(s, y)
+ # Test skip update
+ B = np.copy(hess.get_matrix())
+ s = delta_x[17]
+ y = delta_grad[17]
+ hess.update(s, y)
+ B_updated = np.copy(hess.get_matrix())
+ assert_array_equal(B, B_updated)
+
+ def test_BFGS_skip_update(self):
+ # Define auxiliary problem
+ prob = Rosenbrock(n=5)
+ # Define iteration points
+ x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
+ [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
+ [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
+ [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
+ [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
+ [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
+ [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184]]
+ # Get iteration points
+ grad_list = [prob.grad(x) for x in x_list]
+ delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
+ for i in range(len(x_list)-1)]
+ delta_grad = [grad_list[i+1]-grad_list[i]
+ for i in range(len(grad_list)-1)]
+ hess = BFGS(init_scale=1, min_curvature=10)
+ hess.initialize(len(x_list[0]), 'hess')
+ # Compare the Hessian and its inverse
+ for i in range(len(delta_x)-1):
+ s = delta_x[i]
+ y = delta_grad[i]
+ hess.update(s, y)
+ # Test skip update
+ B = np.copy(hess.get_matrix())
+ s = delta_x[5]
+ y = delta_grad[5]
+ hess.update(s, y)
+ B_updated = np.copy(hess.get_matrix())
+ assert_array_equal(B, B_updated)
+
+
+@pytest.mark.parametrize('strategy', [BFGS, SR1])
+@pytest.mark.parametrize('approx_type', ['hess', 'inv_hess'])
+def test_matmul_equals_dot(strategy, approx_type):
+ H = strategy(init_scale=1)
+ H.initialize(2, approx_type)
+ v = np.array([1, 2])
+ assert_array_equal(H @ v, H.dot(v))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_isotonic_regression.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_isotonic_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49c56db5b4470c1e4e0f787df52c80eb055c120
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_isotonic_regression.py
@@ -0,0 +1,167 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+
+from scipy.optimize._pava_pybind import pava
+from scipy.optimize import isotonic_regression
+
+
+class TestIsotonicRegression:
+ @pytest.mark.parametrize(
+ ("y", "w", "msg"),
+ [
+ ([[0, 1]], None,
+ "array has incorrect number of dimensions: 2; expected 1"),
+ ([0, 1], [[1, 2]],
+ "Input arrays y and w must have one dimension of equal length"),
+ ([0, 1], [1],
+ "Input arrays y and w must have one dimension of equal length"),
+ (1, [1, 2],
+ "Input arrays y and w must have one dimension of equal length"),
+ ([1, 2], 1,
+ "Input arrays y and w must have one dimension of equal length"),
+ ([0, 1], [0, 1],
+ "Weights w must be strictly positive"),
+ ]
+ )
+ def test_raise_error(self, y, w, msg):
+ with pytest.raises(ValueError, match=msg):
+ isotonic_regression(y=y, weights=w)
+
+ def test_simple_pava(self):
+ # Test case of Busing 2020
+ # https://doi.org/10.18637/jss.v102.c01
+ y = np.array([8, 4, 8, 2, 2, 0, 8], dtype=np.float64)
+ w = np.ones_like(y)
+ r = np.full(shape=y.shape[0] + 1, fill_value=-1, dtype=np.intp)
+ pava(y, w, r)
+ assert_allclose(y, [4, 4, 4, 4, 4, 4, 8])
+ # Only first 2 elements of w are changed.
+ assert_allclose(w, [6, 1, 1, 1, 1, 1, 1])
+ # Only first 3 elements of r are changed.
+ assert_allclose(r, [0, 6, 7, -1, -1, -1, -1, -1])
+
+ @pytest.mark.parametrize("y_dtype", [np.float64, np.float32, np.int64, np.int32])
+ @pytest.mark.parametrize("w_dtype", [np.float64, np.float32, np.int64, np.int32])
+ @pytest.mark.parametrize("w", [None, "ones"])
+ def test_simple_isotonic_regression(self, w, w_dtype, y_dtype):
+ # Test case of Busing 2020
+ # https://doi.org/10.18637/jss.v102.c01
+ y = np.array([8, 4, 8, 2, 2, 0, 8], dtype=y_dtype)
+ if w is not None:
+ w = np.ones_like(y, dtype=w_dtype)
+ res = isotonic_regression(y, weights=w)
+ assert res.x.dtype == np.float64
+ assert res.weights.dtype == np.float64
+ assert_allclose(res.x, [4, 4, 4, 4, 4, 4, 8])
+ assert_allclose(res.weights, [6, 1])
+ assert_allclose(res.blocks, [0, 6, 7])
+ # Assert that y was not overwritten
+ assert_equal(y, np.array([8, 4, 8, 2, 2, 0, 8], dtype=np.float64))
+
+ @pytest.mark.parametrize("increasing", [True, False])
+ def test_linspace(self, increasing):
+ n = 10
+ y = np.linspace(0, 1, n) if increasing else np.linspace(1, 0, n)
+ res = isotonic_regression(y, increasing=increasing)
+ assert_allclose(res.x, y)
+ assert_allclose(res.blocks, np.arange(n + 1))
+
+ def test_weights(self):
+ w = np.array([1, 2, 5, 0.5, 0.5, 0.5, 1, 3])
+ y = np.array([3, 2, 1, 10, 9, 8, 20, 10])
+ res = isotonic_regression(y, weights=w)
+ assert_allclose(res.x, [12/8, 12/8, 12/8, 9, 9, 9, 50/4, 50/4])
+ assert_allclose(res.weights, [8, 1.5, 4])
+ assert_allclose(res.blocks, [0, 3, 6, 8])
+
+ # weights are like repeated observations, we repeat the 3rd element 5
+ # times.
+ w2 = np.array([1, 2, 1, 1, 1, 1, 1, 0.5, 0.5, 0.5, 1, 3])
+ y2 = np.array([3, 2, 1, 1, 1, 1, 1, 10, 9, 8, 20, 10])
+ res2 = isotonic_regression(y2, weights=w2)
+ assert_allclose(np.diff(res2.x[0:7]), 0)
+ assert_allclose(res2.x[4:], res.x)
+ assert_allclose(res2.weights, res.weights)
+ assert_allclose(res2.blocks[1:] - 4, res.blocks[1:])
+
+ def test_against_R_monotone(self):
+ y = [0, 6, 8, 3, 5, 2, 1, 7, 9, 4]
+ res = isotonic_regression(y)
+ # R code
+ # library(monotone)
+ # options(digits=8)
+ # monotone(c(0, 6, 8, 3, 5, 2, 1, 7, 9, 4))
+ x_R = [
+ 0, 4.1666667, 4.1666667, 4.1666667, 4.1666667, 4.1666667,
+ 4.1666667, 6.6666667, 6.6666667, 6.6666667,
+ ]
+ assert_allclose(res.x, x_R)
+ assert_equal(res.blocks, [0, 1, 7, 10])
+
+ n = 100
+ y = np.linspace(0, 1, num=n, endpoint=False)
+ y = 5 * y + np.sin(10 * y)
+ res = isotonic_regression(y)
+ # R code
+ # library(monotone)
+ # n <- 100
+ # y <- 5 * ((1:n)-1)/n + sin(10 * ((1:n)-1)/n)
+ # options(digits=8)
+ # monotone(y)
+ x_R = [
+ 0.00000000, 0.14983342, 0.29866933, 0.44552021, 0.58941834, 0.72942554,
+ 0.86464247, 0.99421769, 1.11735609, 1.23332691, 1.34147098, 1.44120736,
+ 1.53203909, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.62418532, 1.71654534, 1.81773256,
+ 1.92723551, 2.04445967, 2.16873336, 2.29931446, 2.43539782, 2.57612334,
+ 2.72058450, 2.86783750, 3.01691060, 3.16681390, 3.31654920, 3.46511999,
+ 3.61154136, 3.75484992, 3.89411335, 4.02843976, 4.15698660, 4.27896904,
+ 4.39366786, 4.50043662, 4.59870810, 4.68799998, 4.76791967, 4.83816823,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ ]
+ assert_allclose(res.x, x_R)
+
+ # Test increasing
+ assert np.all(np.diff(res.x) >= 0)
+
+ # Test balance property: sum(y) == sum(x)
+ assert_allclose(np.sum(res.x), np.sum(y))
+
+ # Reverse order
+ res_inv = isotonic_regression(-y, increasing=False)
+ assert_allclose(-res_inv.x, res.x)
+ assert_equal(res_inv.blocks, res.blocks)
+
+ def test_readonly(self):
+ x = np.arange(3, dtype=float)
+ w = np.ones(3, dtype=float)
+
+ x.flags.writeable = False
+ w.flags.writeable = False
+
+ res = isotonic_regression(x, weights=w)
+ assert np.all(np.isfinite(res.x))
+ assert np.all(np.isfinite(res.weights))
+ assert np.all(np.isfinite(res.blocks))
+
+ def test_non_contiguous_arrays(self):
+ x = np.arange(10, dtype=float)[::3]
+ w = np.ones(10, dtype=float)[::3]
+ assert not x.flags.c_contiguous
+ assert not x.flags.f_contiguous
+ assert not w.flags.c_contiguous
+ assert not w.flags.f_contiguous
+
+ res = isotonic_regression(x, weights=w)
+ assert np.all(np.isfinite(res.x))
+ assert np.all(np.isfinite(res.weights))
+ assert np.all(np.isfinite(res.blocks))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py
new file mode 100644
index 0000000000000000000000000000000000000000..8740b94e99929b23ad1aa55bc26829b472691d24
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py
@@ -0,0 +1,65 @@
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.linalg
+from scipy.optimize import minimize
+
+
+def test_1():
+ def f(x):
+ return x**4, 4*x**3
+
+ for gtol in [1e-8, 1e-12, 1e-20]:
+ for maxcor in range(20, 35):
+ result = minimize(fun=f, jac=True, method='L-BFGS-B', x0=20,
+ options={'gtol': gtol, 'maxcor': maxcor})
+
+ H1 = result.hess_inv(np.array([1])).reshape(1,1)
+ H2 = result.hess_inv.todense()
+
+ assert_allclose(H1, H2)
+
+
+def test_2():
+ H0 = [[3, 0], [1, 2]]
+
+ def f(x):
+ return np.dot(x, np.dot(scipy.linalg.inv(H0), x))
+
+ result1 = minimize(fun=f, method='L-BFGS-B', x0=[10, 20])
+ result2 = minimize(fun=f, method='BFGS', x0=[10, 20])
+
+ H1 = result1.hess_inv.todense()
+
+ H2 = np.vstack((
+ result1.hess_inv(np.array([1, 0])),
+ result1.hess_inv(np.array([0, 1]))))
+
+ assert_allclose(
+ result1.hess_inv(np.array([1, 0]).reshape(2,1)).reshape(-1),
+ result1.hess_inv(np.array([1, 0])))
+ assert_allclose(H1, H2)
+ assert_allclose(H1, result2.hess_inv, rtol=1e-2, atol=0.03)
+
+
+def test_3():
+
+ def todense_old_impl(self):
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+ I_arr = np.eye(*self.shape, dtype=self.dtype)
+ Hk = I_arr
+
+ for i in range(n_corrs):
+ A1 = I_arr - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i]
+ A2 = I_arr - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i]
+
+ Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] *
+ s[i][np.newaxis, :])
+ return Hk
+
+ H0 = [[3, 0], [1, 2]]
+
+ def f(x):
+ return np.dot(x, np.dot(scipy.linalg.inv(H0), x))
+
+ result1 = minimize(fun=f, method='L-BFGS-B', x0=[10, 20])
+ assert_allclose(result1.hess_inv.todense(), todense_old_impl(result1.hess_inv))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddbc293928c8aeeed9086c03358cfccde685705a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py
@@ -0,0 +1,125 @@
+import numpy as np
+from scipy.linalg.lapack import HAS_ILP64
+from scipy.optimize import _lbfgsb, minimize
+
+
+def objfun(x):
+ """simplified objective func to test lbfgsb bound violation"""
+ x0 = [0.8750000000000278,
+ 0.7500000000000153,
+ 0.9499999999999722,
+ 0.8214285714285992,
+ 0.6363636363636085]
+ x1 = [1.0, 0.0, 1.0, 0.0, 0.0]
+ x2 = [1.0,
+ 0.0,
+ 0.9889733043149325,
+ 0.0,
+ 0.026353554421041155]
+ x3 = [1.0,
+ 0.0,
+ 0.9889917442915558,
+ 0.0,
+ 0.020341986743231205]
+
+ f0 = 5163.647901211178
+ f1 = 5149.8181642072905
+ f2 = 5149.379332309634
+ f3 = 5149.374490771297
+
+ g0 = np.array([-0.5934820547965749,
+ 1.6251549718258351,
+ -71.99168459202559,
+ 5.346636965797545,
+ 37.10732723092604])
+ g1 = np.array([-0.43295349282641515,
+ 1.008607936794592,
+ 18.223666726602975,
+ 31.927010036981997,
+ -19.667512518739386])
+ g2 = np.array([-0.4699874455100256,
+ 0.9466285353668347,
+ -0.016874360242016825,
+ 48.44999161133457,
+ 5.819631620590712])
+ g3 = np.array([-0.46970678696829116,
+ 0.9612719312174818,
+ 0.006129809488833699,
+ 48.43557729419473,
+ 6.005481418498221])
+
+ if np.allclose(x, x0):
+ f = f0
+ g = g0
+ elif np.allclose(x, x1):
+ f = f1
+ g = g1
+ elif np.allclose(x, x2):
+ f = f2
+ g = g2
+ elif np.allclose(x, x3):
+ f = f3
+ g = g3
+ else:
+ raise ValueError(
+ 'Simplified objective function not defined '
+ 'at requested point')
+ return (np.copy(f), np.copy(g))
+
+
+def test_setulb_floatround():
+ """test if setulb() violates bounds
+
+ checks for violation due to floating point rounding error
+ """
+
+ n = 5
+ m = 10
+ factr = 1e7
+ pgtol = 1e-5
+ maxls = 20
+ int_dtype = np.int64 if HAS_ILP64 else np.int32
+
+ nbd = np.full(shape=(n,), fill_value=2, dtype=int_dtype)
+ low_bnd = np.zeros(n, dtype=np.float64)
+ upper_bnd = np.ones(n, dtype=np.float64)
+
+ x0 = np.array(
+ [0.8750000000000278,
+ 0.7500000000000153,
+ 0.9499999999999722,
+ 0.8214285714285992,
+ 0.6363636363636085])
+ x = np.copy(x0)
+
+ f = np.array(0.0, dtype=np.float64)
+ g = np.zeros(n, dtype=np.float64)
+
+ wa = np.zeros(2*m*n + 5*n + 11*m*m + 8*m, dtype=np.float64)
+ iwa = np.zeros(3*n, dtype=int_dtype)
+ task = np.zeros(2, dtype=int_dtype)
+ ln_task = np.zeros(2, dtype=int_dtype)
+ lsave = np.zeros(4, dtype=int_dtype)
+ isave = np.zeros(44, dtype=int_dtype)
+ dsave = np.zeros(29, dtype=np.float64)
+
+ for n_iter in range(7): # 7 steps required to reproduce error
+ f, g = objfun(x)
+
+ _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa,
+ iwa, task, lsave, isave, dsave, maxls, ln_task)
+
+ assert (x <= upper_bnd).all() and (x >= low_bnd).all(), (
+ "_lbfgsb.setulb() stepped to a point outside of the bounds")
+
+
+def test_gh_issue18730():
+ # issue 18730 reported that l-bfgs-b did not work with objectives
+ # returning single precision gradient arrays
+ def fun_single_precision(x):
+ x = x.astype(np.float32)
+ return np.sum(x**2), (2*x)
+
+ res = minimize(fun_single_precision, x0=np.array([1., 1.]), jac=True,
+ method="l-bfgs-b")
+ np.testing.assert_allclose(res.fun, 0., atol=1e-15)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_least_squares.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..07587acc4f972e009bb2e72d5b95531140ccd3eb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_least_squares.py
@@ -0,0 +1,999 @@
+import warnings
+
+from itertools import product
+from multiprocessing import Pool
+
+import numpy as np
+from numpy.linalg import norm
+from numpy.testing import (assert_, assert_allclose,
+ assert_equal)
+import pytest
+from pytest import raises as assert_raises
+from scipy.sparse import issparse, lil_array
+from scipy.sparse.linalg import aslinearoperator
+
+from scipy.optimize import least_squares, Bounds, minimize
+from scipy.optimize._lsq.least_squares import IMPLEMENTED_LOSSES
+from scipy.optimize._lsq.common import EPS, make_strictly_feasible, CL_scaling_vector
+
+from scipy.optimize import OptimizeResult
+
+def fun_trivial(x, a=0):
+ return (x - a)**2 + 5.0
+
+
+def jac_trivial(x, a=0.0):
+ return 2 * (x - a)
+
+
+def fun_2d_trivial(x):
+ return np.array([x[0], x[1]])
+
+
+def jac_2d_trivial(x):
+ return np.identity(2)
+
+
+def fun_rosenbrock(x):
+ return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])
+
+
+class Fun_Rosenbrock:
+ def __init__(self):
+ self.nfev = 0
+
+ def __call__(self, x, a=0):
+ self.nfev += 1
+ return fun_rosenbrock(x)
+
+
+def jac_rosenbrock(x):
+ return np.array([
+ [-20 * x[0], 10],
+ [-1, 0]
+ ])
+
+
+def jac_rosenbrock_bad_dim(x):
+ return np.array([
+ [-20 * x[0], 10],
+ [-1, 0],
+ [0.0, 0.0]
+ ])
+
+
+def fun_rosenbrock_cropped(x):
+ return fun_rosenbrock(x)[0]
+
+
+def jac_rosenbrock_cropped(x):
+ return jac_rosenbrock(x)[0]
+
+
+# When x is 1-D array, return is 2-D array.
+def fun_wrong_dimensions(x):
+ return np.array([x, x**2, x**3])
+
+
+def jac_wrong_dimensions(x, a=0.0):
+ return np.atleast_3d(jac_trivial(x, a=a))
+
+
+def fun_bvp(x):
+ n = int(np.sqrt(x.shape[0]))
+ u = np.zeros((n + 2, n + 2))
+ x = x.reshape((n, n))
+ u[1:-1, 1:-1] = x
+ y = u[:-2, 1:-1] + u[2:, 1:-1] + u[1:-1, :-2] + u[1:-1, 2:] - 4 * x + x**3
+ return y.ravel()
+
+
+class BroydenTridiagonal:
+ def __init__(self, n=100, mode='sparse'):
+ rng = np.random.default_rng(123440)
+
+ self.n = n
+
+ self.x0 = -np.ones(n)
+ self.lb = np.linspace(-2, -1.5, n)
+ self.ub = np.linspace(-0.8, 0.0, n)
+
+ self.lb += 0.1 * rng.standard_normal(n)
+ self.ub += 0.1 * rng.standard_normal(n)
+
+ self.x0 += 0.1 * rng.standard_normal(n)
+ self.x0 = make_strictly_feasible(self.x0, self.lb, self.ub)
+
+ if mode == 'sparse':
+ self.sparsity = lil_array((n, n), dtype=int)
+ i = np.arange(n)
+ self.sparsity[i, i] = 1
+ i = np.arange(1, n)
+ self.sparsity[i, i - 1] = 1
+ i = np.arange(n - 1)
+ self.sparsity[i, i + 1] = 1
+
+ self.jac = self._jac
+ elif mode == 'operator':
+ self.jac = lambda x: aslinearoperator(self._jac(x))
+ elif mode == 'dense':
+ self.sparsity = None
+ self.jac = lambda x: self._jac(x).toarray()
+ else:
+ assert_(False)
+
+ def fun(self, x):
+ f = (3 - x) * x + 1
+ f[1:] -= x[:-1]
+ f[:-1] -= 2 * x[1:]
+ return f
+
+ def _jac(self, x):
+ J = lil_array((self.n, self.n))
+ i = np.arange(self.n)
+ J[i, i] = 3 - 2 * x
+ i = np.arange(1, self.n)
+ J[i, i - 1] = -1
+ i = np.arange(self.n - 1)
+ J[i, i + 1] = -2
+ return J
+
+
+class ExponentialFittingProblem:
+ """Provide data and function for exponential fitting in the form
+ y = a + exp(b * x) + noise."""
+
+ def __init__(self, a, b, noise, n_outliers=1, x_range=(-1, 1),
+ n_points=11, rng=None):
+ rng = np.random.default_rng(rng)
+ self.m = n_points
+ self.n = 2
+
+ self.p0 = np.zeros(2)
+ self.x = np.linspace(x_range[0], x_range[1], n_points)
+
+ self.y = a + np.exp(b * self.x)
+ self.y += noise * rng.standard_normal(self.m)
+
+ outliers = rng.integers(0, self.m, n_outliers)
+ self.y[outliers] += 50 * noise * rng.random(n_outliers)
+
+ self.p_opt = np.array([a, b])
+
+ def fun(self, p):
+ return p[0] + np.exp(p[1] * self.x) - self.y
+
+ def jac(self, p):
+ J = np.empty((self.m, self.n))
+ J[:, 0] = 1
+ J[:, 1] = self.x * np.exp(p[1] * self.x)
+ return J
+
+
+def cubic_soft_l1(z):
+ rho = np.empty((3, z.size))
+
+ t = 1 + z
+ rho[0] = 3 * (t**(1/3) - 1)
+ rho[1] = t ** (-2/3)
+ rho[2] = -2/3 * t**(-5/3)
+
+ return rho
+
+
+LOSSES = list(IMPLEMENTED_LOSSES.keys()) + [cubic_soft_l1]
+
+
+class BaseMixin:
+ msg = "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'"
+ def test_basic(self):
+ # Test that the basic calling sequence works.
+ res = least_squares(fun_trivial, 2., method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+ assert_allclose(res.fun, fun_trivial(res.x))
+
+ def test_args_kwargs(self):
+ # Test that args and kwargs are passed correctly to the functions.
+ a = 3.0
+ for jac in ['2-point', '3-point', 'cs', jac_trivial]:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", self.msg, UserWarning)
+ res = least_squares(fun_trivial, 2.0, jac, args=(a,),
+ method=self.method)
+ res1 = least_squares(fun_trivial, 2.0, jac, kwargs={'a': a},
+ method=self.method)
+
+ assert_allclose(res.x, a, rtol=1e-4)
+ assert_allclose(res1.x, a, rtol=1e-4)
+
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ args=(3, 4,), method=self.method)
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ kwargs={'kaboom': 3}, method=self.method)
+
+ def test_jac_options(self):
+ for jac in ['2-point', '3-point', 'cs', jac_trivial]:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", self.msg, UserWarning)
+ res = least_squares(fun_trivial, 2.0, jac, method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0, jac='oops',
+ method=self.method)
+
+ def test_nfev_options(self):
+ for max_nfev in [None, 20]:
+ res = least_squares(fun_trivial, 2.0, max_nfev=max_nfev,
+ method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+
+ def test_x_scale_options(self):
+ for x_scale in [1.0, np.array([0.5]), 'jac']:
+ res = least_squares(fun_trivial, 2.0, x_scale=x_scale)
+ assert_allclose(res.x, 0)
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, x_scale='auto', method=self.method)
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, x_scale=-1.0, method=self.method)
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, x_scale=1.0+2.0j, method=self.method)
+
+ def test_diff_step(self):
+ res1 = least_squares(fun_trivial, 2.0, diff_step=1e-1,
+ method=self.method)
+ res3 = least_squares(fun_trivial, 2.0,
+ diff_step=None, method=self.method)
+ assert_allclose(res1.x, 0, atol=1e-4)
+ assert_allclose(res3.x, 0, atol=1e-4)
+
+
+ def test_incorrect_options_usage(self):
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ method=self.method, options={'no_such_option': 100})
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ method=self.method, options={'max_nfev': 100})
+
+ def test_full_result(self):
+ # MINPACK doesn't work very well with factor=100 on this problem,
+ # thus using low 'atol'.
+ res = least_squares(fun_trivial, 2.0, method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+ assert_allclose(res.cost, 12.5)
+ assert_allclose(res.fun, 5)
+ assert_allclose(res.jac, 0, atol=1e-4)
+ assert_allclose(res.grad, 0, atol=1e-2)
+ assert_allclose(res.optimality, 0, atol=1e-2)
+ assert_equal(res.active_mask, 0)
+ if self.method == 'lm':
+ assert_(res.njev is None)
+ else:
+ assert_(res.nfev < 10)
+ assert_(res.njev < 10)
+ assert_(res.status > 0)
+ assert_(res.success)
+
+ def test_full_result_single_fev(self):
+ # MINPACK checks the number of nfev after the iteration,
+ # so it's hard to tell what he is going to compute.
+ if self.method == 'lm':
+ return
+
+ res = least_squares(fun_trivial, 2.0, method=self.method,
+ max_nfev=1)
+ assert_equal(res.x, np.array([2]))
+ assert_equal(res.cost, 40.5)
+ assert_equal(res.fun, np.array([9]))
+ assert_equal(res.jac, np.array([[4]]))
+ assert_equal(res.grad, np.array([36]))
+ assert_equal(res.optimality, 36)
+ assert_equal(res.active_mask, np.array([0]))
+ assert_equal(res.nfev, 1)
+ assert_equal(res.njev, 1)
+ assert_equal(res.status, 0)
+ assert_equal(res.success, 0)
+
+ def test_nfev(self):
+ # checks that the true number of nfev are being consumed
+ for i in range(1, 3):
+ rng = np.random.default_rng(128908)
+ x0 = rng.uniform(size=2) * 10
+ ftrivial = Fun_Rosenbrock()
+ res = least_squares(
+ ftrivial, x0, jac=jac_rosenbrock, method=self.method, max_nfev=i
+ )
+ assert res.nfev == ftrivial.nfev
+
+ def test_rosenbrock(self):
+ x0 = [-2, 1]
+ x_opt = [1, 1]
+ for jac, x_scale, tr_solver in product(
+ ['2-point', '3-point', 'cs', jac_rosenbrock],
+ [1.0, np.array([1.0, 0.2]), 'jac'],
+ ['exact', 'lsmr']):
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", self.msg, UserWarning)
+ res = least_squares(fun_rosenbrock, x0, jac, x_scale=x_scale,
+ tr_solver=tr_solver, method=self.method)
+ assert_allclose(res.x, x_opt)
+
+ def test_rosenbrock_cropped(self):
+ x0 = [-2, 1]
+ if self.method == 'lm':
+ assert_raises(ValueError, least_squares, fun_rosenbrock_cropped,
+ x0, method='lm')
+ else:
+ for jac, x_scale, tr_solver in product(
+ ['2-point', '3-point', 'cs', jac_rosenbrock_cropped],
+ [1.0, np.array([1.0, 0.2]), 'jac'],
+ ['exact', 'lsmr']):
+ res = least_squares(
+ fun_rosenbrock_cropped, x0, jac, x_scale=x_scale,
+ tr_solver=tr_solver, method=self.method)
+ assert_allclose(res.cost, 0, atol=1e-14)
+
+ def test_fun_wrong_dimensions(self):
+ assert_raises(ValueError, least_squares, fun_wrong_dimensions,
+ 2.0, method=self.method)
+
+ def test_jac_wrong_dimensions(self):
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, jac_wrong_dimensions, method=self.method)
+
+ def test_fun_and_jac_inconsistent_dimensions(self):
+ x0 = [1, 2]
+ assert_raises(ValueError, least_squares, fun_rosenbrock, x0,
+ jac_rosenbrock_bad_dim, method=self.method)
+
+ def test_x0_multidimensional(self):
+ x0 = np.ones(4).reshape(2, 2)
+ assert_raises(ValueError, least_squares, fun_trivial, x0,
+ method=self.method)
+
+ def test_x0_complex_scalar(self):
+ x0 = 2.0 + 0.0*1j
+ assert_raises(ValueError, least_squares, fun_trivial, x0,
+ method=self.method)
+
+ def test_x0_complex_array(self):
+ x0 = [1.0, 2.0 + 0.0*1j]
+ assert_raises(ValueError, least_squares, fun_trivial, x0,
+ method=self.method)
+
+ def test_bvp(self):
+ # This test was introduced with fix #5556. It turned out that
+ # dogbox solver had a bug with trust-region radius update, which
+ # could block its progress and create an infinite loop. And this
+ # discrete boundary value problem is the one which triggers it.
+ n = 10
+ x0 = np.ones(n**2)
+ if self.method == 'lm':
+ max_nfev = 5000 # To account for Jacobian estimation.
+ else:
+ max_nfev = 100
+ res = least_squares(fun_bvp, x0, ftol=1e-2, method=self.method,
+ max_nfev=max_nfev)
+
+ assert_(res.nfev < max_nfev)
+ assert_(res.cost < 0.5)
+
+ def test_error_raised_when_all_tolerances_below_eps(self):
+ # Test that all 0 tolerances are not allowed.
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ method=self.method, ftol=None, xtol=None, gtol=None)
+
+ def test_convergence_with_only_one_tolerance_enabled(self):
+ if self.method == 'lm':
+ return # should not do test
+ x0 = [-2, 1]
+ x_opt = [1, 1]
+ for ftol, xtol, gtol in [(1e-8, None, None),
+ (None, 1e-8, None),
+ (None, None, 1e-8)]:
+ res = least_squares(fun_rosenbrock, x0, jac=jac_rosenbrock,
+ ftol=ftol, gtol=gtol, xtol=xtol,
+ method=self.method)
+ assert_allclose(res.x, x_opt)
+
+ # This test is thread safe, but it is too slow and opens
+ # too many file descriptors to run it in parallel.
+ @pytest.mark.parallel_threads_limit(1)
+ @pytest.mark.fail_slow(5.0)
+ def test_workers(self):
+ serial = least_squares(fun_trivial, 2.0, method=self.method)
+
+ reses = []
+ for workers in [None, 2]:
+ res = least_squares(
+ fun_trivial, 2.0, method=self.method, workers=workers
+ )
+ reses.append(res)
+ with Pool(2) as workers:
+ res = least_squares(
+ fun_trivial, 2.0, method=self.method, workers=workers.map
+ )
+ reses.append(res)
+ for res in reses:
+ assert res.success
+ assert_equal(res.x, serial.x)
+ assert_equal(res.nfev, serial.nfev)
+ assert_equal(res.njev, serial.njev)
+
+
+class BoundsMixin:
+ def test_inconsistent(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ bounds=(10.0, 0.0), method=self.method)
+
+ def test_infeasible(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ bounds=(3., 4), method=self.method)
+
+ def test_wrong_number(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.,
+ bounds=(1., 2, 3), method=self.method)
+
+ def test_inconsistent_shape(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ bounds=(1.0, [2.0, 3.0]), method=self.method)
+ # 1-D array won't be broadcast
+ assert_raises(ValueError, least_squares, fun_rosenbrock, [1.0, 2.0],
+ bounds=([0.0], [3.0, 4.0]), method=self.method)
+
+ def test_in_bounds(self):
+ for jac in ['2-point', '3-point', 'cs', jac_trivial]:
+ res = least_squares(fun_trivial, 2.0, jac=jac,
+ bounds=(-1.0, 3.0), method=self.method)
+ assert_allclose(res.x, 0.0, atol=1e-4)
+ assert_equal(res.active_mask, [0])
+ assert_(-1 <= res.x <= 3)
+ res = least_squares(fun_trivial, 2.0, jac=jac,
+ bounds=(0.5, 3.0), method=self.method)
+ assert_allclose(res.x, 0.5, atol=1e-4)
+ assert_equal(res.active_mask, [-1])
+ assert_(0.5 <= res.x <= 3)
+
+ def test_bounds_shape(self):
+ def get_bounds_direct(lb, ub):
+ return lb, ub
+
+ def get_bounds_instances(lb, ub):
+ return Bounds(lb, ub)
+
+ for jac in ['2-point', '3-point', 'cs', jac_2d_trivial]:
+ for bounds_func in [get_bounds_direct, get_bounds_instances]:
+ x0 = [1.0, 1.0]
+ res = least_squares(fun_2d_trivial, x0, jac=jac)
+ assert_allclose(res.x, [0.0, 0.0])
+ res = least_squares(fun_2d_trivial, x0, jac=jac,
+ bounds=bounds_func(0.5, [2.0, 2.0]),
+ method=self.method)
+ assert_allclose(res.x, [0.5, 0.5])
+ res = least_squares(fun_2d_trivial, x0, jac=jac,
+ bounds=bounds_func([0.3, 0.2], 3.0),
+ method=self.method)
+ assert_allclose(res.x, [0.3, 0.2])
+ res = least_squares(
+ fun_2d_trivial, x0, jac=jac,
+ bounds=bounds_func([-1, 0.5], [1.0, 3.0]),
+ method=self.method)
+ assert_allclose(res.x, [0.0, 0.5], atol=1e-5)
+
+ def test_bounds_instances(self):
+ res = least_squares(fun_trivial, 0.5, bounds=Bounds())
+ assert_allclose(res.x, 0.0, atol=1e-4)
+
+ res = least_squares(fun_trivial, 3.0, bounds=Bounds(lb=1.0))
+ assert_allclose(res.x, 1.0, atol=1e-4)
+
+ res = least_squares(fun_trivial, 0.5, bounds=Bounds(lb=-1.0, ub=1.0))
+ assert_allclose(res.x, 0.0, atol=1e-4)
+
+ res = least_squares(fun_trivial, -3.0, bounds=Bounds(ub=-1.0))
+ assert_allclose(res.x, -1.0, atol=1e-4)
+
+ res = least_squares(fun_2d_trivial, [0.5, 0.5],
+ bounds=Bounds(lb=[-1.0, -1.0], ub=1.0))
+ assert_allclose(res.x, [0.0, 0.0], atol=1e-5)
+
+ res = least_squares(fun_2d_trivial, [0.5, 0.5],
+ bounds=Bounds(lb=[0.1, 0.1]))
+ assert_allclose(res.x, [0.1, 0.1], atol=1e-5)
+
+ @pytest.mark.fail_slow(10)
+ def test_rosenbrock_bounds(self):
+ x0_1 = np.array([-2.0, 1.0])
+ x0_2 = np.array([2.0, 2.0])
+ x0_3 = np.array([-2.0, 2.0])
+ x0_4 = np.array([0.0, 2.0])
+ x0_5 = np.array([-1.2, 1.0])
+ problems = [
+ (x0_1, ([-np.inf, -1.5], np.inf)),
+ (x0_2, ([-np.inf, 1.5], np.inf)),
+ (x0_3, ([-np.inf, 1.5], np.inf)),
+ (x0_4, ([-np.inf, 1.5], [1.0, np.inf])),
+ (x0_2, ([1.0, 1.5], [3.0, 3.0])),
+ (x0_5, ([-50.0, 0.0], [0.5, 100]))
+ ]
+ for x0, bounds in problems:
+ for jac, x_scale, tr_solver in product(
+ ['2-point', '3-point', 'cs', jac_rosenbrock],
+ [1.0, [1.0, 0.5], 'jac'],
+ ['exact', 'lsmr']):
+ res = least_squares(fun_rosenbrock, x0, jac, bounds,
+ x_scale=x_scale, tr_solver=tr_solver,
+ method=self.method)
+ assert_allclose(res.optimality, 0.0, atol=1e-5)
+
+
+class SparseMixin:
+ def test_exact_tr_solver(self):
+ p = BroydenTridiagonal()
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ tr_solver='exact', method=self.method)
+ assert_raises(ValueError, least_squares, p.fun, p.x0,
+ tr_solver='exact', jac_sparsity=p.sparsity,
+ method=self.method)
+
+ def test_equivalence(self):
+ sparse = BroydenTridiagonal(mode='sparse')
+ dense = BroydenTridiagonal(mode='dense')
+ res_sparse = least_squares(
+ sparse.fun, sparse.x0, jac=sparse.jac,
+ method=self.method)
+ res_dense = least_squares(
+ dense.fun, dense.x0, jac=sparse.jac,
+ method=self.method)
+ assert_equal(res_sparse.nfev, res_dense.nfev)
+ assert_allclose(res_sparse.x, res_dense.x, atol=1e-20)
+ assert_allclose(res_sparse.cost, 0, atol=1e-20)
+ assert_allclose(res_dense.cost, 0, atol=1e-20)
+
+ def test_tr_options(self):
+ p = BroydenTridiagonal()
+ res = least_squares(p.fun, p.x0, p.jac, method=self.method,
+ tr_options={'btol': 1e-10})
+ assert_allclose(res.cost, 0, atol=1e-20)
+
+ def test_wrong_parameters(self):
+ p = BroydenTridiagonal()
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ tr_solver='best', method=self.method)
+ assert_raises(TypeError, least_squares, p.fun, p.x0, p.jac,
+ tr_solver='lsmr', tr_options={'tol': 1e-10})
+
+ def test_solver_selection(self):
+ sparse = BroydenTridiagonal(mode='sparse')
+ dense = BroydenTridiagonal(mode='dense')
+ res_sparse = least_squares(sparse.fun, sparse.x0, jac=sparse.jac,
+ method=self.method)
+ res_dense = least_squares(dense.fun, dense.x0, jac=dense.jac,
+ method=self.method)
+ assert_allclose(res_sparse.cost, 0, atol=1e-20)
+ assert_allclose(res_dense.cost, 0, atol=1e-20)
+ assert_(issparse(res_sparse.jac))
+ assert_(isinstance(res_dense.jac, np.ndarray))
+
+ def test_numerical_jac(self):
+ p = BroydenTridiagonal()
+ for jac in ['2-point', '3-point', 'cs']:
+ res_dense = least_squares(p.fun, p.x0, jac, method=self.method)
+ res_sparse = least_squares(
+ p.fun, p.x0, jac,method=self.method,
+ jac_sparsity=p.sparsity)
+ assert_equal(res_dense.nfev, res_sparse.nfev)
+ assert_allclose(res_dense.x, res_sparse.x, atol=1e-20)
+ assert_allclose(res_dense.cost, 0, atol=1e-20)
+ assert_allclose(res_sparse.cost, 0, atol=1e-20)
+
+ @pytest.mark.fail_slow(10)
+ def test_with_bounds(self):
+ p = BroydenTridiagonal()
+ for jac, jac_sparsity in product(
+ [p.jac, '2-point', '3-point', 'cs'], [None, p.sparsity]):
+ res_1 = least_squares(
+ p.fun, p.x0, jac, bounds=(p.lb, np.inf),
+ method=self.method,jac_sparsity=jac_sparsity)
+ res_2 = least_squares(
+ p.fun, p.x0, jac, bounds=(-np.inf, p.ub),
+ method=self.method, jac_sparsity=jac_sparsity)
+ res_3 = least_squares(
+ p.fun, p.x0, jac, bounds=(p.lb, p.ub),
+ method=self.method, jac_sparsity=jac_sparsity)
+ assert_allclose(res_1.optimality, 0, atol=1e-10)
+ assert_allclose(res_2.optimality, 0, atol=1e-10)
+ assert_allclose(res_3.optimality, 0, atol=1e-10)
+
+ def test_wrong_jac_sparsity(self):
+ p = BroydenTridiagonal()
+ sparsity = p.sparsity[:-1]
+ assert_raises(ValueError, least_squares, p.fun, p.x0,
+ jac_sparsity=sparsity, method=self.method)
+
+ def test_linear_operator(self):
+ p = BroydenTridiagonal(mode='operator')
+ res = least_squares(p.fun, p.x0, p.jac, method=self.method)
+ assert_allclose(res.cost, 0.0, atol=1e-20)
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method=self.method, tr_solver='exact')
+
+ def test_x_scale_jac_scale(self):
+ p = BroydenTridiagonal()
+ res = least_squares(p.fun, p.x0, p.jac, method=self.method,
+ x_scale='jac')
+ assert_allclose(res.cost, 0.0, atol=1e-20)
+
+ p = BroydenTridiagonal(mode='operator')
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method=self.method, x_scale='jac')
+
+
+class LossFunctionMixin:
+ def test_options(self):
+ for loss in LOSSES:
+ res = least_squares(fun_trivial, 2.0, loss=loss,
+ method=self.method)
+ assert_allclose(res.x, 0, atol=1e-15)
+
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ loss='hinge', method=self.method)
+
+ def test_fun(self):
+ # Test that res.fun is actual residuals, and not modified by loss
+ # function stuff.
+ for loss in LOSSES:
+ res = least_squares(fun_trivial, 2.0, loss=loss,
+ method=self.method)
+ assert_equal(res.fun, fun_trivial(res.x))
+
+ def test_grad(self):
+ # Test that res.grad is true gradient of loss function at the
+ # solution. Use max_nfev = 1, to avoid reaching minimum.
+ x = np.array([2.0]) # res.x will be this.
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='linear',
+ max_nfev=1, method=self.method)
+ assert_equal(res.grad, 2 * x * (x**2 + 5))
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='huber',
+ max_nfev=1, method=self.method)
+ assert_equal(res.grad, 2 * x)
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='soft_l1',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad,
+ 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2)**0.5)
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad, 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2))
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='arctan',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad, 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**4))
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss=cubic_soft_l1,
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad,
+ 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2)**(2/3))
+
+ def test_jac(self):
+ # Test that res.jac.T.dot(res.jac) gives Gauss-Newton approximation
+ # of Hessian. This approximation is computed by doubly differentiating
+ # the cost function and dropping the part containing second derivative
+ # of f. For a scalar function it is computed as
+ # H = (rho' + 2 * rho'' * f**2) * f'**2, if the expression inside the
+ # brackets is less than EPS it is replaced by EPS. Here, we check
+ # against the root of H.
+
+ x = 2.0 # res.x will be this.
+ f = x**2 + 5 # res.fun will be this.
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='linear',
+ max_nfev=1, method=self.method)
+ assert_equal(res.jac, 2 * x)
+
+ # For `huber` loss the Jacobian correction is identically zero
+ # in outlier region, in such cases it is modified to be equal EPS**0.5.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='huber',
+ max_nfev=1, method=self.method)
+ assert_equal(res.jac, 2 * x * EPS**0.5)
+
+ # Now, let's apply `loss_scale` to turn the residual into an inlier.
+ # The loss function becomes linear.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='huber',
+ f_scale=10, max_nfev=1)
+ assert_equal(res.jac, 2 * x)
+
+ # 'soft_l1' always gives a positive scaling.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='soft_l1',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.jac, 2 * x * (1 + f**2)**-0.75)
+
+ # For 'cauchy' the correction term turns out to be negative, and it
+ # replaced by EPS**0.5.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.jac, 2 * x * EPS**0.5)
+
+ # Now use scaling to turn the residual to inlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy',
+ f_scale=10, max_nfev=1, method=self.method)
+ fs = f / 10
+ assert_allclose(res.jac, 2 * x * (1 - fs**2)**0.5 / (1 + fs**2))
+
+ # 'arctan' gives an outlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='arctan',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.jac, 2 * x * EPS**0.5)
+
+ # Turn to inlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='arctan',
+ f_scale=20.0, max_nfev=1, method=self.method)
+ fs = f / 20
+ assert_allclose(res.jac, 2 * x * (1 - 3 * fs**4)**0.5 / (1 + fs**4))
+
+ # cubic_soft_l1 will give an outlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss=cubic_soft_l1,
+ max_nfev=1)
+ assert_allclose(res.jac, 2 * x * EPS**0.5)
+
+ # Turn to inlier.
+ res = least_squares(fun_trivial, x, jac_trivial,
+ loss=cubic_soft_l1, f_scale=6, max_nfev=1)
+ fs = f / 6
+ assert_allclose(res.jac,
+ 2 * x * (1 - fs**2 / 3)**0.5 * (1 + fs**2)**(-5/6))
+
+ def test_robustness(self):
+ for noise in [0.1, 1.0]:
+ p = ExponentialFittingProblem(1, 0.1, noise, rng=12220903)
+
+ for jac in ['2-point', '3-point', 'cs', p.jac]:
+ res_lsq = least_squares(p.fun, p.p0, jac=jac,
+ method=self.method)
+ assert_allclose(res_lsq.optimality, 0, atol=1e-2)
+ for loss in LOSSES:
+ if loss == 'linear':
+ continue
+ res_robust = least_squares(
+ p.fun, p.p0, jac=jac, loss=loss, f_scale=noise,
+ method=self.method)
+ assert_allclose(res_robust.optimality, 0, atol=1e-2)
+ assert_(norm(res_robust.x - p.p_opt) <
+ norm(res_lsq.x - p.p_opt))
+
+
+class TestDogbox(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin):
+ method = 'dogbox'
+
+
+class TestTRF(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin):
+ method = 'trf'
+
+ def test_lsmr_regularization(self):
+ p = BroydenTridiagonal()
+ for regularize in [True, False]:
+ res = least_squares(p.fun, p.x0, p.jac, method='trf',
+ tr_options={'regularize': regularize})
+ assert_allclose(res.cost, 0, atol=1e-20)
+
+
+class TestLM(BaseMixin):
+ method = 'lm'
+
+ def test_bounds_not_supported(self):
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, bounds=(-3.0, 3.0), method='lm')
+
+ def test_m_less_n_not_supported(self):
+ x0 = [-2, 1]
+ assert_raises(ValueError, least_squares, fun_rosenbrock_cropped, x0,
+ method='lm')
+
+ def test_sparse_not_supported(self):
+ p = BroydenTridiagonal()
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method='lm')
+
+ def test_jac_sparsity_not_supported(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ jac_sparsity=[1], method='lm')
+
+ def test_LinearOperator_not_supported(self):
+ p = BroydenTridiagonal(mode="operator")
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method='lm')
+
+ def test_loss(self):
+ res = least_squares(fun_trivial, 2.0, loss='linear', method='lm')
+ assert_allclose(res.x, 0.0, atol=1e-4)
+
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ method='lm', loss='huber')
+
+ def test_callback_with_lm_method(self):
+ def callback(x):
+ assert(False) # Dummy callback function
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Callback function specified, but not supported with `lm` method.",
+ UserWarning,
+ )
+ least_squares(fun_trivial, x0=[0], method='lm', callback=callback)
+
+
+def test_basic():
+ # test that 'method' arg is really optional
+ res = least_squares(fun_trivial, 2.0)
+ assert_allclose(res.x, 0, atol=1e-10)
+
+
+def test_callback():
+ # test that callback function works as expected
+
+ results = []
+
+ def my_callback_optimresult(intermediate_result: OptimizeResult):
+ results.append(intermediate_result)
+
+ def my_callback_x(x):
+ r = OptimizeResult()
+ r.nit = 1
+ r.x = x
+ results.append(r)
+ return False
+
+ def my_callback_optimresult_stop_exception(
+ intermediate_result: OptimizeResult):
+ results.append(intermediate_result)
+ raise StopIteration
+
+ def my_callback_x_stop_exception(x):
+ r = OptimizeResult()
+ r.nit = 1
+ r.x = x
+ results.append(r)
+ raise StopIteration
+
+ # Try for different function signatures and stop methods
+ callbacks_nostop = [my_callback_optimresult, my_callback_x]
+ callbacks_stop = [my_callback_optimresult_stop_exception,
+ my_callback_x_stop_exception]
+
+ # Try for all the implemented methods: trf, trf_bounds and dogbox
+ calls = [
+ lambda callback: least_squares(fun_trivial, 5.0, method='trf',
+ callback=callback),
+ lambda callback: least_squares(fun_trivial, 5.0, method='trf',
+ bounds=(-8.0, 8.0), callback=callback),
+ lambda callback: least_squares(fun_trivial, 5.0, method='dogbox',
+ callback=callback)
+ ]
+
+ for mycallback, call in product(callbacks_nostop, calls):
+ results.clear()
+ # Call the different implemented methods
+ res = call(mycallback)
+ # Check that callback was called
+ assert len(results) > 0
+ # Check that results data makes sense
+ assert results[-1].nit > 0
+ # Check that it didn't stop because of the callback
+ assert res.status != -2
+ # final callback x should be same as final result
+ assert_allclose(results[-1].x, res.x)
+
+ for mycallback, call in product(callbacks_stop, calls):
+ results.clear()
+ # Call the different implemented methods
+ res = call(mycallback)
+ # Check that callback was called
+ assert len(results) > 0
+ # Check that only one iteration was run
+ assert results[-1].nit == 1
+ # Check that it stopped because of the callback
+ assert res.status == -2
+
+
+def test_small_tolerances_for_lm():
+ for ftol, xtol, gtol in [(None, 1e-13, 1e-13),
+ (1e-13, None, 1e-13),
+ (1e-13, 1e-13, None)]:
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0, xtol=xtol,
+ ftol=ftol, gtol=gtol, method='lm')
+
+
+def test_fp32_gh12991():
+ # checks that smaller FP sizes can be used in least_squares
+ # this is the minimum working example reported for gh12991
+ rng = np.random.default_rng(1978)
+
+ x = np.linspace(0, 1, 100, dtype=np.float32)
+ y = rng.random(size=100, dtype=np.float32)
+
+ # changed in gh21872. These functions should've been working in fp32 to force
+ # approx_derivative to work in fp32. One of the initial steps in least_squares
+ # is to force x0 (p) to be a float, meaning that the output of func and err would
+ # be in float64, unless forced to be in float32
+ def func(p, x):
+ return (p[0] + p[1] * x).astype(np.float32)
+
+ def err(p, x, y):
+ return (func(p, x) - y).astype(np.float32)
+
+ def mse(p, x, y):
+ return np.sum(err(p, x, y)**2)
+
+ res = least_squares(err, [-1.0, -1.0], args=(x, y))
+ # previously the initial jacobian calculated for this would be all 0
+ # and the minimize would terminate immediately, with nfev=1, would
+ # report a successful minimization (it shouldn't have done), but be
+ # unchanged from the initial solution.
+ # It was terminating early because the underlying approx_derivative
+ # used a step size for FP64 when the working space was FP32.
+ assert res.nfev > 2
+ # compare output to solver that doesn't use derivatives
+ res2 = minimize(
+ mse,
+ [-1.0, 1.0],
+ method='cobyqa',
+ args=(x, y),
+ options={'final_tr_radius': 1e-6}
+ )
+ assert_allclose(res.x, res2.x, atol=9e-5)
+
+
+def test_gh_18793_and_19351():
+ answer = 1e-12
+ initial_guess = 1.1e-12
+
+ def chi2(x):
+ return (x-answer)**2
+
+ gtol = 1e-15
+ res = least_squares(chi2, x0=initial_guess, gtol=1e-15, bounds=(0, np.inf))
+ # Original motivation: gh-18793
+ # if we choose an initial condition that is close to the solution
+ # we shouldn't return an answer that is further away from the solution
+
+ # Update: gh-19351
+ # However this requirement does not go well with 'trf' algorithm logic.
+ # Some regressions were reported after the presumed fix.
+ # The returned solution is good as long as it satisfies the convergence
+ # conditions.
+ # Specifically in this case the scaled gradient will be sufficiently low.
+
+ scaling, _ = CL_scaling_vector(res.x, res.grad,
+ np.atleast_1d(0), np.atleast_1d(np.inf))
+ assert res.status == 1 # Converged by gradient
+ assert np.linalg.norm(res.grad * scaling, ord=np.inf) < gtol
+
+
+def test_gh_19103():
+ # Checks that least_squares trf method selects a strictly feasible point,
+ # and thus succeeds instead of failing,
+ # when the initial guess is reported exactly at a boundary point.
+ # This is a reduced example from gh191303
+
+ ydata = np.array([0.] * 66 + [
+ 1., 0., 0., 0., 0., 0., 1., 1., 0., 0., 1.,
+ 1., 1., 1., 0., 0., 0., 1., 0., 0., 2., 1.,
+ 0., 3., 1., 6., 5., 0., 0., 2., 8., 4., 4.,
+ 6., 9., 7., 2., 7., 8., 2., 13., 9., 8., 11.,
+ 10., 13., 14., 19., 11., 15., 18., 26., 19., 32., 29.,
+ 28., 36., 32., 35., 36., 43., 52., 32., 58., 56., 52.,
+ 67., 53., 72., 88., 77., 95., 94., 84., 86., 101., 107.,
+ 108., 118., 96., 115., 138., 137.,
+ ])
+ xdata = np.arange(0, ydata.size) * 0.1
+
+ def exponential_wrapped(params):
+ A, B, x0 = params
+ return A * np.exp(B * (xdata - x0)) - ydata
+
+ x0 = [0.01, 1., 5.]
+ bounds = ((0.01, 0, 0), (np.inf, 10, 20.9))
+ res = least_squares(exponential_wrapped, x0, method='trf', bounds=bounds)
+ assert res.success
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linear_assignment.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linear_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..523ed78f5115b02349c35eb94e601fd31f03936d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linear_assignment.py
@@ -0,0 +1,116 @@
+# Author: Brian M. Clapper, G. Varoquaux, Lars Buitinck
+# License: BSD
+
+from numpy.testing import assert_array_equal
+import pytest
+
+import numpy as np
+
+from scipy.optimize import linear_sum_assignment
+from scipy.sparse import random_array
+from scipy.sparse._sputils import matrix
+from scipy.sparse.csgraph import min_weight_full_bipartite_matching
+from scipy.sparse.csgraph.tests.test_matching import (
+ linear_sum_assignment_assertions, linear_sum_assignment_test_cases
+)
+
+
+def test_linear_sum_assignment_input_shape():
+ with pytest.raises(ValueError, match="expected a matrix"):
+ linear_sum_assignment([1, 2, 3])
+
+
+def test_linear_sum_assignment_input_object():
+ C = [[1, 2, 3], [4, 5, 6]]
+ assert_array_equal(linear_sum_assignment(C),
+ linear_sum_assignment(np.asarray(C)))
+ assert_array_equal(linear_sum_assignment(C),
+ linear_sum_assignment(matrix(C)))
+
+
+def test_linear_sum_assignment_input_bool():
+ I = np.identity(3)
+ assert_array_equal(linear_sum_assignment(I.astype(np.bool_)),
+ linear_sum_assignment(I))
+
+
+def test_linear_sum_assignment_input_string():
+ I = np.identity(3)
+ with pytest.raises(TypeError, match="Cannot cast array data"):
+ linear_sum_assignment(I.astype(str))
+
+
+def test_linear_sum_assignment_input_nan():
+ I = np.diag([np.nan, 1, 1])
+ with pytest.raises(ValueError, match="contains invalid numeric entries"):
+ linear_sum_assignment(I)
+
+
+def test_linear_sum_assignment_input_neginf():
+ I = np.diag([1, -np.inf, 1])
+ with pytest.raises(ValueError, match="contains invalid numeric entries"):
+ linear_sum_assignment(I)
+
+
+def test_linear_sum_assignment_input_inf():
+ I = np.identity(3)
+ I[:, 0] = np.inf
+ with pytest.raises(ValueError, match="cost matrix is infeasible"):
+ linear_sum_assignment(I)
+
+
+def test_constant_cost_matrix():
+ # Fixes #11602
+ n = 8
+ C = np.ones((n, n))
+ row_ind, col_ind = linear_sum_assignment(C)
+ assert_array_equal(row_ind, np.arange(n))
+ assert_array_equal(col_ind, np.arange(n))
+
+
+@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)])
+def test_linear_sum_assignment_trivial_cost(num_rows, num_cols):
+ C = np.empty(shape=(num_cols, num_rows))
+ row_ind, col_ind = linear_sum_assignment(C)
+ assert len(row_ind) == 0
+ assert len(col_ind) == 0
+
+
+@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases)
+def test_linear_sum_assignment_small_inputs(sign, test_case):
+ linear_sum_assignment_assertions(
+ linear_sum_assignment, np.array, sign, test_case)
+
+
+# Tests that combine scipy.optimize.linear_sum_assignment and
+# scipy.sparse.csgraph.min_weight_full_bipartite_matching
+def test_two_methods_give_same_result_on_many_sparse_inputs():
+ # As opposed to the test above, here we do not spell out the expected
+ # output; only assert that the two methods give the same result.
+ # Concretely, the below tests 100 cases of size 100x100, out of which
+ # 36 are infeasible.
+ rng = np.random.default_rng(12342309)
+ for _ in range(100):
+ lsa_raises = False
+ mwfbm_raises = False
+ sparse = random_array((100, 100), density=0.06,
+ data_sampler=lambda size: rng.integers(1, 100, size))
+ # In csgraph, zeros correspond to missing edges, so we explicitly
+ # replace those with infinities
+ dense = np.full(sparse.shape, np.inf)
+ dense[sparse.row, sparse.col] = sparse.data
+ sparse = sparse.tocsr()
+ try:
+ row_ind, col_ind = linear_sum_assignment(dense)
+ lsa_cost = dense[row_ind, col_ind].sum()
+ except ValueError:
+ lsa_raises = True
+ try:
+ row_ind, col_ind = min_weight_full_bipartite_matching(sparse)
+ mwfbm_cost = sparse[row_ind, col_ind].sum()
+ except ValueError:
+ mwfbm_raises = True
+ # Ensure that if one method raises, so does the other one.
+ assert lsa_raises == mwfbm_raises
+ if not lsa_raises:
+ assert lsa_cost == mwfbm_cost
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linesearch.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a76b9248b2dd3e257196877261d1ab7bedd2532
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linesearch.py
@@ -0,0 +1,334 @@
+"""
+Tests for line search routines
+"""
+import warnings
+
+from numpy.testing import (assert_equal, assert_array_almost_equal,
+ assert_array_almost_equal_nulp)
+import scipy.optimize._linesearch as ls
+from scipy.optimize._linesearch import LineSearchWarning
+import numpy as np
+import pytest
+import threading
+
+
+def assert_wolfe(s, phi, derphi, c1=1e-4, c2=0.9, err_msg=""):
+ """
+ Check that strong Wolfe conditions apply
+ """
+ phi1 = phi(s)
+ phi0 = phi(0)
+ derphi0 = derphi(0)
+ derphi1 = derphi(s)
+ msg = (f"s = {s}; phi(0) = {phi0}; phi(s) = {phi1}; phi'(0) = {derphi0};"
+ f" phi'(s) = {derphi1}; {err_msg}")
+
+ assert phi1 <= phi0 + c1*s*derphi0, "Wolfe 1 failed: " + msg
+ assert abs(derphi1) <= abs(c2*derphi0), "Wolfe 2 failed: " + msg
+
+
+def assert_armijo(s, phi, c1=1e-4, err_msg=""):
+ """
+ Check that Armijo condition applies
+ """
+ phi1 = phi(s)
+ phi0 = phi(0)
+ msg = f"s = {s}; phi(0) = {phi0}; phi(s) = {phi1}; {err_msg}"
+ assert phi1 <= (1 - c1*s)*phi0, msg
+
+
+def assert_line_wolfe(x, p, s, f, fprime, **kw):
+ assert_wolfe(s, phi=lambda sp: f(x + p*sp),
+ derphi=lambda sp: np.dot(fprime(x + p*sp), p), **kw)
+
+
+def assert_line_armijo(x, p, s, f, **kw):
+ assert_armijo(s, phi=lambda sp: f(x + p*sp), **kw)
+
+
+def assert_fp_equal(x, y, err_msg="", nulp=50):
+ """Assert two arrays are equal, up to some floating-point rounding error"""
+ try:
+ assert_array_almost_equal_nulp(x, y, nulp)
+ except AssertionError as e:
+ raise AssertionError(f"{e}\n{err_msg}") from e
+
+
+class TestLineSearch:
+ # -- scalar functions; must have dphi(0.) < 0
+ def _scalar_func_1(self, s): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ p = -s - s**3 + s**4
+ dp = -1 - 3*s**2 + 4*s**3
+ return p, dp
+
+ def _scalar_func_2(self, s): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ p = np.exp(-4*s) + s**2
+ dp = -4*np.exp(-4*s) + 2*s
+ return p, dp
+
+ def _scalar_func_3(self, s): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ p = -np.sin(10*s)
+ dp = -10*np.cos(10*s)
+ return p, dp
+
+ # -- n-d functions
+
+ def _line_func_1(self, x): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ f = np.dot(x, x)
+ df = 2*x
+ return f, df
+
+ def _line_func_2(self, x): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ f = np.dot(x, np.dot(self.A, x)) + 1
+ df = np.dot(self.A + self.A.T, x)
+ return f, df
+
+ # --
+
+ def setup_method(self):
+ self.scalar_funcs = []
+ self.line_funcs = []
+ self.N = 20
+ self.fcount = threading.local()
+
+ def bind_index(func, idx):
+ # Remember Python's closure semantics!
+ return lambda *a, **kw: func(*a, **kw)[idx]
+
+ for name in sorted(dir(self)):
+ if name.startswith('_scalar_func_'):
+ value = getattr(self, name)
+ self.scalar_funcs.append(
+ (name, bind_index(value, 0), bind_index(value, 1)))
+ elif name.startswith('_line_func_'):
+ value = getattr(self, name)
+ self.line_funcs.append(
+ (name, bind_index(value, 0), bind_index(value, 1)))
+
+ # the choice of seed affects whether the tests pass
+ rng = np.random.default_rng(1231892908)
+ self.A = rng.standard_normal((self.N, self.N))
+
+ def scalar_iter(self):
+ rng = np.random.default_rng(2231892908)
+ for name, phi, derphi in self.scalar_funcs:
+ for old_phi0 in rng.standard_normal(3):
+ yield name, phi, derphi, old_phi0
+
+ def line_iter(self):
+ rng = np.random.default_rng(2231892908)
+ for name, f, fprime in self.line_funcs:
+ k = 0
+ while k < 9:
+ x = rng.standard_normal(self.N)
+ p = rng.standard_normal(self.N)
+ if np.dot(p, fprime(x)) >= 0:
+ # always pick a descent direction
+ continue
+ k += 1
+ old_fv = float(rng.standard_normal())
+ yield name, f, fprime, x, p, old_fv
+
+ # -- Generic scalar searches
+
+ def test_scalar_search_wolfe1(self):
+ c = 0
+ for name, phi, derphi, old_phi0 in self.scalar_iter():
+ c += 1
+ s, phi1, phi0 = ls.scalar_search_wolfe1(phi, derphi, phi(0),
+ old_phi0, derphi(0))
+ assert_fp_equal(phi0, phi(0), name)
+ assert_fp_equal(phi1, phi(s), name)
+ assert_wolfe(s, phi, derphi, err_msg=name)
+
+ assert c > 3 # check that the iterator really works...
+
+ def test_scalar_search_wolfe2(self):
+ for name, phi, derphi, old_phi0 in self.scalar_iter():
+ s, phi1, phi0, derphi1 = ls.scalar_search_wolfe2(
+ phi, derphi, phi(0), old_phi0, derphi(0))
+ assert_fp_equal(phi0, phi(0), name)
+ assert_fp_equal(phi1, phi(s), name)
+ if derphi1 is not None:
+ assert_fp_equal(derphi1, derphi(s), name)
+ assert_wolfe(s, phi, derphi, err_msg=f"{name} {old_phi0:g}")
+
+ def test_scalar_search_wolfe2_with_low_amax(self):
+ def phi(alpha):
+ return (alpha - 5) ** 2
+
+ def derphi(alpha):
+ return 2 * (alpha - 5)
+
+ alpha_star, _, _, derphi_star = ls.scalar_search_wolfe2(phi, derphi, amax=0.001)
+ assert alpha_star is None # Not converged
+ assert derphi_star is None # Not converged
+
+ def test_scalar_search_wolfe2_regression(self):
+ # Regression test for gh-12157
+ # This phi has its minimum at alpha=4/3 ~ 1.333.
+ def phi(alpha):
+ if alpha < 1:
+ return - 3*np.pi/2 * (alpha - 1)
+ else:
+ return np.cos(3*np.pi/2 * alpha - np.pi)
+
+ def derphi(alpha):
+ if alpha < 1:
+ return - 3*np.pi/2
+ else:
+ return - 3*np.pi/2 * np.sin(3*np.pi/2 * alpha - np.pi)
+
+ s, _, _, _ = ls.scalar_search_wolfe2(phi, derphi)
+ # Without the fix in gh-13073, the scalar_search_wolfe2
+ # returned s=2.0 instead.
+ assert s < 1.5
+
+ def test_scalar_search_armijo(self):
+ for name, phi, derphi, old_phi0 in self.scalar_iter():
+ s, phi1 = ls.scalar_search_armijo(phi, phi(0), derphi(0))
+ assert_fp_equal(phi1, phi(s), name)
+ assert_armijo(s, phi, err_msg=f"{name} {old_phi0:g}")
+
+ # -- Generic line searches
+
+ def test_line_search_wolfe1(self):
+ c = 0
+ smax = 100
+ for name, f, fprime, x, p, old_f in self.line_iter():
+ f0 = f(x)
+ g0 = fprime(x)
+ self.fcount.c = 0
+ s, fc, gc, fv, ofv, gv = ls.line_search_wolfe1(f, fprime, x, p,
+ g0, f0, old_f,
+ amax=smax)
+ assert_equal(self.fcount.c, fc+gc)
+ assert_fp_equal(ofv, f(x))
+ if s is None:
+ continue
+ assert_fp_equal(fv, f(x + s*p))
+ assert_array_almost_equal(gv, fprime(x + s*p), decimal=14)
+ if s < smax:
+ c += 1
+ assert_line_wolfe(x, p, s, f, fprime, err_msg=name)
+
+ assert c > 3 # check that the iterator really works...
+
+ def test_line_search_wolfe2(self):
+ c = 0
+ smax = 512
+ for name, f, fprime, x, p, old_f in self.line_iter():
+ f0 = f(x)
+ g0 = fprime(x)
+ self.fcount.c = 0
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "The line search algorithm could not find a solution",
+ LineSearchWarning)
+ warnings.filterwarnings(
+ "ignore",
+ "The line search algorithm did not converge",
+ LineSearchWarning)
+ s, fc, gc, fv, ofv, gv = ls.line_search_wolfe2(f, fprime, x, p,
+ g0, f0, old_f,
+ amax=smax)
+ assert_equal(self.fcount.c, fc+gc)
+ assert_fp_equal(ofv, f(x))
+ assert_fp_equal(fv, f(x + s*p))
+ if gv is not None:
+ assert_array_almost_equal(gv, fprime(x + s*p), decimal=14)
+ if s < smax:
+ c += 1
+ assert_line_wolfe(x, p, s, f, fprime, err_msg=name)
+ assert c > 3 # check that the iterator really works...
+
+ def test_line_search_wolfe2_bounds(self):
+ # See gh-7475
+
+ # For this f and p, starting at a point on axis 0, the strong Wolfe
+ # condition 2 is met if and only if the step length s satisfies
+ # |x + s| <= c2 * |x|
+ def f(x):
+ return np.dot(x, x)
+ def fp(x):
+ return 2 * x
+ p = np.array([1, 0])
+
+ # Smallest s satisfying strong Wolfe conditions for these arguments is 30
+ x = -60 * p
+ c2 = 0.5
+
+ s, _, _, _, _, _ = ls.line_search_wolfe2(f, fp, x, p, amax=30, c2=c2)
+ assert_line_wolfe(x, p, s, f, fp)
+
+ with pytest.warns(LineSearchWarning):
+ s, _, _, _, _, _ = ls.line_search_wolfe2(f, fp, x, p,
+ amax=29, c2=c2)
+ assert s is None
+
+ # s=30 will only be tried on the 6th iteration, so this won't converge
+ with pytest.warns(LineSearchWarning):
+ ls.line_search_wolfe2(f, fp, x, p, c2=c2, maxiter=5)
+
+ def test_line_search_armijo(self):
+ c = 0
+ for name, f, fprime, x, p, old_f in self.line_iter():
+ f0 = f(x)
+ g0 = fprime(x)
+ self.fcount.c = 0
+ s, fc, fv = ls.line_search_armijo(f, x, p, g0, f0)
+ c += 1
+ assert_equal(self.fcount.c, fc)
+ assert_fp_equal(fv, f(x + s*p))
+ assert_line_armijo(x, p, s, f, err_msg=name)
+ assert c >= 9
+
+ # -- More specific tests
+
+ def test_armijo_terminate_1(self):
+ # Armijo should evaluate the function only once if the trial step
+ # is already suitable
+ count = [0]
+
+ def phi(s):
+ count[0] += 1
+ return -s + 0.01*s**2
+ s, phi1 = ls.scalar_search_armijo(phi, phi(0), -1, alpha0=1)
+ assert_equal(s, 1)
+ assert_equal(count[0], 2)
+ assert_armijo(s, phi)
+
+ def test_wolfe_terminate(self):
+ # wolfe1 and wolfe2 should also evaluate the function only a few
+ # times if the trial step is already suitable
+
+ def phi(s):
+ count[0] += 1
+ return -s + 0.05*s**2
+
+ def derphi(s):
+ count[0] += 1
+ return -1 + 0.05*2*s
+
+ for func in [ls.scalar_search_wolfe1, ls.scalar_search_wolfe2]:
+ count = [0]
+ r = func(phi, derphi, phi(0), None, derphi(0))
+ assert r[0] is not None, (r, func)
+ assert count[0] <= 2 + 2, (count, func)
+ assert_wolfe(r[0], phi, derphi, err_msg=str(func))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linprog.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linprog.py
new file mode 100644
index 0000000000000000000000000000000000000000..a36694c60f0c0d3db42deebdaac7ccc9e4e966ca
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_linprog.py
@@ -0,0 +1,2614 @@
+"""
+Unit test for Linear Programming
+"""
+import sys
+import platform
+import warnings
+
+import numpy as np
+from numpy.exceptions import VisibleDeprecationWarning
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+ assert_array_less)
+from pytest import raises as assert_raises
+from scipy.optimize import linprog, OptimizeWarning
+from scipy.optimize._numdiff import approx_derivative
+from scipy.sparse.linalg import MatrixRankWarning
+from scipy.linalg import LinAlgWarning
+import scipy.sparse
+import pytest
+
+has_umfpack = True
+try:
+ from scikits.umfpack import UmfpackWarning
+except ImportError:
+ has_umfpack = False
+
+has_cholmod = True
+try:
+ import sksparse # noqa: F401
+ from sksparse.cholmod import cholesky as cholmod # noqa: F401
+except ImportError:
+ has_cholmod = False
+
+
+def _assert_iteration_limit_reached(res, maxiter):
+ assert_(not res.success, "Incorrectly reported success")
+ assert_(res.success < maxiter, "Incorrectly reported number of iterations")
+ assert_equal(res.status, 1, "Failed to report iteration limit reached")
+
+
+def _assert_infeasible(res):
+ # res: linprog result object
+ assert_(not res.success, "incorrectly reported success")
+ assert_equal(res.status, 2, "failed to report infeasible status")
+
+
+def _assert_unbounded(res):
+ # res: linprog result object
+ assert_(not res.success, "incorrectly reported success")
+ assert_equal(res.status, 3, "failed to report unbounded status")
+
+
+def _assert_unable_to_find_basic_feasible_sol(res):
+ # res: linprog result object
+
+ # The status may be either 2 or 4 depending on why the feasible solution
+ # could not be found. If the underlying problem is expected to not have a
+ # feasible solution, _assert_infeasible should be used.
+ assert_(not res.success, "incorrectly reported success")
+ assert_(res.status in (2, 4), "failed to report optimization failure")
+
+
+def _assert_success(res, desired_fun=None, desired_x=None,
+ rtol=1e-8, atol=1e-8):
+ # res: linprog result object
+ # desired_fun: desired objective function value or None
+ # desired_x: desired solution or None
+ if not res.success:
+ msg = f"linprog status {res.status}, message: {res.message}"
+ raise AssertionError(msg)
+
+ assert_equal(res.status, 0)
+ if desired_fun is not None:
+ assert_allclose(res.fun, desired_fun,
+ err_msg="converged to an unexpected objective value",
+ rtol=rtol, atol=atol)
+ if desired_x is not None:
+ assert_allclose(res.x, desired_x,
+ err_msg="converged to an unexpected solution",
+ rtol=rtol, atol=atol)
+
+
+def magic_square(n, rng=None):
+ """
+ Generates a linear program for which integer solutions represent an
+ n x n magic square; binary decision variables represent the presence
+ (or absence) of an integer 1 to n^2 in each position of the square.
+ """
+
+ rng = np.random.default_rng(92350948245690509234) if rng is None else rng
+ M = n * (n**2 + 1) / 2
+
+ numbers = np.arange(n**4) // n**2 + 1
+
+ numbers = numbers.reshape(n**2, n, n)
+
+ zeros = np.zeros((n**2, n, n))
+
+ A_list = []
+ b_list = []
+
+ # Rule 1: use every number exactly once
+ for i in range(n**2):
+ A_row = zeros.copy()
+ A_row[i, :, :] = 1
+ A_list.append(A_row.flatten())
+ b_list.append(1)
+
+ # Rule 2: Only one number per square
+ for i in range(n):
+ for j in range(n):
+ A_row = zeros.copy()
+ A_row[:, i, j] = 1
+ A_list.append(A_row.flatten())
+ b_list.append(1)
+
+ # Rule 3: sum of rows is M
+ for i in range(n):
+ A_row = zeros.copy()
+ A_row[:, i, :] = numbers[:, i, :]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+
+ # Rule 4: sum of columns is M
+ for i in range(n):
+ A_row = zeros.copy()
+ A_row[:, :, i] = numbers[:, :, i]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+
+ # Rule 5: sum of diagonals is M
+ A_row = zeros.copy()
+ A_row[:, range(n), range(n)] = numbers[:, range(n), range(n)]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+ A_row = zeros.copy()
+ A_row[:, range(n), range(-1, -n - 1, -1)] = \
+ numbers[:, range(n), range(-1, -n - 1, -1)]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+
+ A = np.array(np.vstack(A_list), dtype=float)
+ b = np.array(b_list, dtype=float)
+ c = rng.random(A.shape[1])
+
+ return A, b, c, numbers, M
+
+
+def lpgen_2d(m, n):
+ """ -> A b c LP test: m*n vars, m+n constraints
+ row sums == n/m, col sums == 1
+ https://gist.github.com/denis-bz/8647461
+ """
+ rng = np.random.default_rng(35892345982340246935)
+ c = - rng.exponential(size=(m, n))
+ Arow = np.zeros((m, m * n))
+ brow = np.zeros(m)
+ for j in range(m):
+ j1 = j + 1
+ Arow[j, j * n:j1 * n] = 1
+ brow[j] = n / m
+
+ Acol = np.zeros((n, m * n))
+ bcol = np.zeros(n)
+ for j in range(n):
+ j1 = j + 1
+ Acol[j, j::n] = 1
+ bcol[j] = 1
+
+ A = np.vstack((Arow, Acol))
+ b = np.hstack((brow, bcol))
+
+ return A, b, c.ravel()
+
+
+def very_random_gen(seed=0):
+ rng = np.random.default_rng(389234982354865)
+ m_eq, m_ub, n = 10, 20, 50
+ c = rng.random(n)-0.5
+ A_ub = rng.random((m_ub, n))-0.5
+ b_ub = rng.random(m_ub)-0.5
+ A_eq = rng.random((m_eq, n))-0.5
+ b_eq = rng.random(m_eq)-0.5
+ lb = -rng.random(n)
+ ub = rng.random(n)
+ lb[lb < -rng.random()] = -np.inf
+ ub[ub > rng.random()] = np.inf
+ bounds = np.vstack((lb, ub)).T
+ return c, A_ub, b_ub, A_eq, b_eq, bounds
+
+
+def nontrivial_problem():
+ c = [-1, 8, 4, -6]
+ A_ub = [[-7, -7, 6, 9],
+ [1, -1, -3, 0],
+ [10, -10, -7, 7],
+ [6, -1, 3, 4]]
+ b_ub = [-3, 6, -6, 6]
+ A_eq = [[-10, 1, 1, -8]]
+ b_eq = [-4]
+ x_star = [101 / 1391, 1462 / 1391, 0, 752 / 1391]
+ f_star = 7083 / 1391
+ return c, A_ub, b_ub, A_eq, b_eq, x_star, f_star
+
+
+def l1_regression_prob(seed=0, m=8, d=9, n=100):
+ '''
+ Training data is {(x0, y0), (x1, y2), ..., (xn-1, yn-1)}
+ x in R^d
+ y in R
+ n: number of training samples
+ d: dimension of x, i.e. x in R^d
+ phi: feature map R^d -> R^m
+ m: dimension of feature space
+ '''
+ rng = np.random.default_rng(72847583923592458453)
+ phi = rng.normal(0, 1, size=(m, d)) # random feature mapping
+ w_true = rng.standard_normal(m)
+ x = rng.normal(0, 1, size=(d, n)) # features
+ y = w_true @ (phi @ x) + rng.normal(0, 1e-5, size=n) # measurements
+
+ # construct the problem
+ c = np.ones(m+n)
+ c[:m] = 0
+ A_ub = scipy.sparse.lil_array((2*n, n+m))
+ idx = 0
+ for ii in range(n):
+ A_ub[idx, :m] = phi @ x[:, ii]
+ A_ub[idx, m+ii] = -1
+ A_ub[idx+1, :m] = -1*phi @ x[:, ii]
+ A_ub[idx+1, m+ii] = -1
+ idx += 2
+ A_ub = A_ub.tocsc()
+ b_ub = np.zeros(2*n)
+ b_ub[0::2] = y
+ b_ub[1::2] = -y
+ bnds = [(None, None)]*m + [(0, None)]*n
+ return c, A_ub, b_ub, bnds
+
+
+def generic_callback_test(self):
+ # Check that callback is as advertised
+ last_cb = {}
+
+ def cb(res):
+ message = res.pop('message')
+ complete = res.pop('complete')
+
+ assert_(res.pop('phase') in (1, 2))
+ assert_(res.pop('status') in range(4))
+ assert_(isinstance(res.pop('nit'), int))
+ assert_(isinstance(complete, bool))
+ assert_(isinstance(message, str))
+
+ last_cb['x'] = res['x']
+ last_cb['fun'] = res['fun']
+ last_cb['slack'] = res['slack']
+ last_cb['con'] = res['con']
+
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, callback=cb, method=self.method)
+
+ _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])
+ assert_allclose(last_cb['fun'], res['fun'])
+ assert_allclose(last_cb['x'], res['x'])
+ assert_allclose(last_cb['con'], res['con'])
+ assert_allclose(last_cb['slack'], res['slack'])
+
+
+def test_unknown_solvers_and_options():
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+
+ assert_raises(ValueError, linprog,
+ c, A_ub=A_ub, b_ub=b_ub, method='ekki-ekki-ekki')
+ assert_raises(ValueError, linprog,
+ c, A_ub=A_ub, b_ub=b_ub, method='highs-ekki')
+ message = "Unrecognized options detected: {'rr_method': 'ekki-ekki-ekki'}"
+ with pytest.warns(OptimizeWarning, match=message):
+ linprog(c, A_ub=A_ub, b_ub=b_ub,
+ options={"rr_method": 'ekki-ekki-ekki'})
+
+
+def test_choose_solver():
+ # 'highs' chooses 'dual'
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+
+ res = linprog(c, A_ub, b_ub, method='highs')
+ _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])
+
+
+def test_deprecation():
+ with pytest.warns(DeprecationWarning):
+ linprog(1, method='interior-point')
+ with pytest.warns(DeprecationWarning):
+ linprog(1, method='revised simplex')
+ with pytest.warns(DeprecationWarning):
+ linprog(1, method='simplex')
+
+
+def test_highs_status_message():
+ res = linprog(1, method='highs')
+ msg = "Optimization terminated successfully. (HiGHS Status 7:"
+ assert res.status == 0
+ assert res.message.startswith(msg)
+
+ A, b, c, numbers, M = magic_square(6)
+ bounds = [(0, 1)] * len(c)
+ integrality = [1] * len(c)
+ options = {"time_limit": 0.1}
+ res = linprog(c=c, A_eq=A, b_eq=b, bounds=bounds, method='highs',
+ options=options, integrality=integrality)
+ msg = "Time limit reached. (HiGHS Status 13:"
+ assert res.status == 1
+ assert res.message.startswith(msg)
+
+ options = {"maxiter": 10}
+ res = linprog(c=c, A_eq=A, b_eq=b, bounds=bounds, method='highs-ds',
+ options=options)
+ msg = "Iteration limit reached. (HiGHS Status 14:"
+ assert res.status == 1
+ assert res.message.startswith(msg)
+
+ res = linprog(1, bounds=(1, -1), method='highs')
+ msg = "The problem is infeasible. (HiGHS Status 8:"
+ assert res.status == 2
+ assert res.message.startswith(msg)
+
+ res = linprog(-1, method='highs')
+ msg = "The problem is unbounded. (HiGHS Status 10:"
+ assert res.status == 3
+ assert res.message.startswith(msg)
+
+ from scipy.optimize._linprog_highs import _highs_to_scipy_status_message
+ status, message = _highs_to_scipy_status_message(58, "Hello!")
+ msg = "The HiGHS status code was not recognized. (HiGHS Status 58:"
+ assert status == 4
+ assert message.startswith(msg)
+
+ status, message = _highs_to_scipy_status_message(None, None)
+ msg = "HiGHS did not provide a status code. (HiGHS Status None: None)"
+ assert status == 4
+ assert message.startswith(msg)
+
+
+def test_bug_17380():
+ linprog([1, 1], A_ub=[[-1, 0]], b_ub=[-2.5], integrality=[1, 1])
+
+
+A_ub = None
+b_ub = None
+A_eq = None
+b_eq = None
+bounds = None
+
+################
+# Common Tests #
+################
+
+
+class LinprogCommonTests:
+ """
+ Base class for `linprog` tests. Generally, each test will be performed
+ once for every derived class of LinprogCommonTests, each of which will
+ typically change self.options and/or self.method. Effectively, these tests
+ are run for many combination of method (simplex, revised simplex, and
+ interior point) and options (such as pivoting rule or sparse treatment).
+ """
+
+ ##################
+ # Targeted Tests #
+ ##################
+
+ def test_callback(self):
+ generic_callback_test(self)
+
+ def test_disp(self):
+ # test that display option does not break anything.
+ A, b, c = lpgen_2d(20, 20)
+ res = linprog(c, A_ub=A, b_ub=b, method=self.method,
+ options={"disp": True})
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_docstring_example(self):
+ # Example from linprog docstring.
+ c = [-1, 4]
+ A = [[-3, 1], [1, 2]]
+ b = [6, 4]
+ x0_bounds = (None, None)
+ x1_bounds = (-3, None)
+ res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),
+ options=self.options, method=self.method)
+ _assert_success(res, desired_fun=-22)
+
+ def test_type_error(self):
+ # (presumably) checks that linprog recognizes type errors
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = [1]
+ A_eq = [[1]]
+ b_eq = "hello"
+ assert_raises(TypeError, linprog,
+ c, A_eq=A_eq, b_eq=b_eq,
+ method=self.method, options=self.options)
+
+ def test_aliasing_b_ub(self):
+ # (presumably) checks that linprog does not modify b_ub
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = np.array([1.0])
+ A_ub = np.array([[1.0]])
+ b_ub_orig = np.array([3.0])
+ b_ub = b_ub_orig.copy()
+ bounds = (-4.0, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-4, desired_x=[-4])
+ assert_allclose(b_ub_orig, b_ub)
+
+ def test_aliasing_b_eq(self):
+ # (presumably) checks that linprog does not modify b_eq
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = np.array([1.0])
+ A_eq = np.array([[1.0]])
+ b_eq_orig = np.array([3.0])
+ b_eq = b_eq_orig.copy()
+ bounds = (-4.0, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3, desired_x=[3])
+ assert_allclose(b_eq_orig, b_eq)
+
+ def test_non_ndarray_args(self):
+ # (presumably) checks that linprog accepts list in place of arrays
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = [1.0]
+ A_ub = [[1.0]]
+ b_ub = [3.0]
+ A_eq = [[1.0]]
+ b_eq = [2.0]
+ bounds = (-1.0, 10.0)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=2, desired_x=[2])
+
+ def test_unknown_options(self):
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+
+ def f(c, A_ub=None, b_ub=None, A_eq=None,
+ b_eq=None, bounds=None, options=None):
+ linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=options)
+
+ o = {key: self.options[key] for key in self.options}
+ o['spam'] = 42
+
+ with pytest.warns(OptimizeWarning):
+ f(c, A_ub=A_ub, b_ub=b_ub, options=o)
+
+ def test_integrality_without_highs(self):
+ # ensure that using `integrality` parameter without `method='highs'`
+ # raises warning and produces correct solution to relaxed problem
+ # source: https://en.wikipedia.org/wiki/Integer_programming#Example
+ A_ub = np.array([[-1, 1], [3, 2], [2, 3]])
+ b_ub = np.array([1, 12, 12])
+ c = -np.array([0, 1])
+
+ bounds = [(0, np.inf)] * len(c)
+ integrality = [1] * len(c)
+
+ with pytest.warns(OptimizeWarning):
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [1.8, 2.8])
+ np.testing.assert_allclose(res.fun, -2.8)
+
+ def test_invalid_inputs(self):
+
+ def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None):
+ linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ # Test ill-formatted bounds
+ assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4)])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Creating an ndarray from ragged", VisibleDeprecationWarning)
+ assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4), (3, 4, 5)])
+ assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, -2), (1, 2)])
+
+ # Test other invalid inputs
+ assert_raises(ValueError, f, [1, 2], A_ub=[[1, 2]], b_ub=[1, 2])
+ assert_raises(ValueError, f, [1, 2], A_ub=[[1]], b_ub=[1])
+ assert_raises(ValueError, f, [1, 2], A_eq=[[1, 2]], b_eq=[1, 2])
+ assert_raises(ValueError, f, [1, 2], A_eq=[[1]], b_eq=[1])
+ assert_raises(ValueError, f, [1, 2], A_eq=[1], b_eq=1)
+
+ # this last check doesn't make sense for sparse presolve
+ if ("_sparse_presolve" in self.options and
+ self.options["_sparse_presolve"]):
+ return
+ # there aren't 3-D sparse matrices
+
+ assert_raises(ValueError, f, [1, 2], A_ub=np.zeros((1, 1, 3)), b_eq=1)
+
+ def test_sparse_constraints(self):
+ # gh-13559: improve error message for sparse inputs when unsupported
+ def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None):
+ linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ rng = np.random.default_rng(9938284754882992)
+ m = 100
+ n = 150
+ A_eq = scipy.sparse.random_array((m, n), density=0.5, rng=rng)
+ x_valid = rng.standard_normal(n)
+ c = rng.standard_normal(n)
+ ub = x_valid + rng.random(n)
+ lb = x_valid - rng.random(n)
+ bounds = np.column_stack((lb, ub))
+ b_eq = A_eq @ x_valid
+
+ if self.method in {'simplex', 'revised simplex'}:
+ # simplex and revised simplex should raise error
+ with assert_raises(ValueError, match=f"Method '{self.method}' "
+ "does not support sparse constraint matrices."):
+ linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
+ method=self.method, options=self.options)
+ else:
+ # other methods should succeed
+ options = {**self.options}
+ if self.method in {'interior-point'}:
+ options['sparse'] = True
+
+ res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
+ method=self.method, options=options)
+ assert res.success
+
+ def test_maxiter(self):
+ # test iteration limit w/ Enzo example
+ c = [4, 8, 3, 0, 0, 0]
+ A = [
+ [2, 5, 3, -1, 0, 0],
+ [3, 2.5, 8, 0, -1, 0],
+ [8, 10, 4, 0, 0, -1]]
+ b = [185, 155, 600]
+ maxiter = 3
+ res = linprog(c, A_eq=A, b_eq=b, method=self.method,
+ options={"maxiter": maxiter})
+ _assert_iteration_limit_reached(res, maxiter)
+ assert_equal(res.nit, maxiter)
+
+ def test_bounds_fixed(self):
+
+ # Test fixed bounds (upper equal to lower)
+ # If presolve option True, test if solution found in presolve (i.e.
+ # number of iterations is 0).
+ do_presolve = self.options.get('presolve', True)
+
+ res = linprog([1], bounds=(1, 1),
+ method=self.method, options=self.options)
+ _assert_success(res, 1, 1)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 2, 3], bounds=[(5, 5), (-1, -1), (3, 3)],
+ method=self.method, options=self.options)
+ _assert_success(res, 12, [5, -1, 3])
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 1], bounds=[(1, 1), (1, 3)],
+ method=self.method, options=self.options)
+ _assert_success(res, 2, [1, 1])
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 1, 2], A_eq=[[1, 0, 0], [0, 1, 0]], b_eq=[1, 7],
+ bounds=[(-5, 5), (0, 10), (3.5, 3.5)],
+ method=self.method, options=self.options)
+ _assert_success(res, 15, [1, 7, 3.5])
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ def test_bounds_infeasible(self):
+
+ # Test ill-valued bounds (upper less than lower)
+ # If presolve option True, test if solution found in presolve (i.e.
+ # number of iterations is 0).
+ do_presolve = self.options.get('presolve', True)
+
+ res = linprog([1], bounds=(1, -2), method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1], bounds=[(1, -2)], method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 2, 3], bounds=[(5, 0), (1, 2), (3, 4)],
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ def test_bounds_infeasible_2(self):
+
+ # Test ill-valued bounds (lower inf, upper -inf)
+ # If presolve option True, test if solution found in presolve (i.e.
+ # number of iterations is 0).
+ # For the simplex method, the cases do not result in an
+ # infeasible status, but in a RuntimeWarning. This is a
+ # consequence of having _presolve() take care of feasibility
+ # checks. See issue gh-11618.
+ do_presolve = self.options.get('presolve', True)
+ simplex_without_presolve = not do_presolve and self.method == 'simplex'
+
+ c = [1, 2, 3]
+ bounds_1 = [(1, 2), (np.inf, np.inf), (3, 4)]
+ bounds_2 = [(1, 2), (-np.inf, -np.inf), (3, 4)]
+
+ if simplex_without_presolve:
+ def g(c, bounds):
+ res = linprog(c, bounds=bounds,
+ method=self.method, options=self.options)
+ return res
+
+ with pytest.warns(RuntimeWarning):
+ with pytest.raises(IndexError):
+ g(c, bounds=bounds_1)
+
+ with pytest.warns(RuntimeWarning):
+ with pytest.raises(IndexError):
+ g(c, bounds=bounds_2)
+ else:
+ res = linprog(c=c, bounds=bounds_1,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+ res = linprog(c=c, bounds=bounds_2,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ def test_empty_constraint_1(self):
+ c = [-1, -2]
+ res = linprog(c, method=self.method, options=self.options)
+ _assert_unbounded(res)
+
+ def test_empty_constraint_2(self):
+ c = [-1, 1, -1, 1]
+ bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)]
+ res = linprog(c, bounds=bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ # Unboundedness detected in presolve requires no iterations
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_empty_constraint_3(self):
+ c = [1, -1, 1, -1]
+ bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)]
+ res = linprog(c, bounds=bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[0, 0, -1, 1], desired_fun=-2)
+
+ def test_inequality_constraints(self):
+ # Minimize linear function subject to linear inequality constraints.
+ # http://www.dam.brown.edu/people/huiwang/classes/am121/Archive/simplex_121_c.pdf
+ c = np.array([3, 2]) * -1 # maximize
+ A_ub = [[2, 1],
+ [1, 1],
+ [1, 0]]
+ b_ub = [10, 8, 4]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-18, desired_x=[2, 6])
+
+ def test_inequality_constraints2(self):
+ # Minimize linear function subject to linear inequality constraints.
+ # http://www.statslab.cam.ac.uk/~ff271/teaching/opt/notes/notes8.pdf
+ # (dead link)
+ c = [6, 3]
+ A_ub = [[0, 3],
+ [-1, -1],
+ [-2, 1]]
+ b_ub = [2, -1, -1]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=5, desired_x=[2 / 3, 1 / 3])
+
+ def test_bounds_simple(self):
+ c = [1, 2]
+ bounds = (1, 2)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[1, 1])
+
+ bounds = [(1, 2), (1, 2)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[1, 1])
+
+ def test_bounded_below_only_1(self):
+ c = np.array([1.0])
+ A_eq = np.array([[1.0]])
+ b_eq = np.array([3.0])
+ bounds = (1.0, None)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3, desired_x=[3])
+
+ def test_bounded_below_only_2(self):
+ c = np.ones(3)
+ A_eq = np.eye(3)
+ b_eq = np.array([1, 2, 3])
+ bounds = (0.5, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))
+
+ def test_bounded_above_only_1(self):
+ c = np.array([1.0])
+ A_eq = np.array([[1.0]])
+ b_eq = np.array([3.0])
+ bounds = (None, 10.0)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3, desired_x=[3])
+
+ def test_bounded_above_only_2(self):
+ c = np.ones(3)
+ A_eq = np.eye(3)
+ b_eq = np.array([1, 2, 3])
+ bounds = (-np.inf, 4)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))
+
+ def test_bounds_infinity(self):
+ c = np.ones(3)
+ A_eq = np.eye(3)
+ b_eq = np.array([1, 2, 3])
+ bounds = (-np.inf, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))
+
+ def test_bounds_mixed(self):
+ # Problem has one unbounded variable and
+ # another with a negative lower bound.
+ c = np.array([-1, 4]) * -1 # maximize
+ A_ub = np.array([[-3, 1],
+ [1, 2]], dtype=np.float64)
+ b_ub = [6, 4]
+ x0_bounds = (-np.inf, np.inf)
+ x1_bounds = (-3, np.inf)
+ bounds = (x0_bounds, x1_bounds)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-80 / 7, desired_x=[-8 / 7, 18 / 7])
+
+ def test_bounds_equal_but_infeasible(self):
+ c = [-4, 1]
+ A_ub = [[7, -2], [0, 1], [2, -2]]
+ b_ub = [14, 0, 3]
+ bounds = [(2, 2), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_bounds_equal_but_infeasible2(self):
+ c = [-4, 1]
+ A_eq = [[7, -2], [0, 1], [2, -2]]
+ b_eq = [14, 0, 3]
+ bounds = [(2, 2), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_bounds_equal_no_presolve(self):
+ # There was a bug when a lower and upper bound were equal but
+ # presolve was not on to eliminate the variable. The bound
+ # was being converted to an equality constraint, but the bound
+ # was not eliminated, leading to issues in postprocessing.
+ c = [1, 2]
+ A_ub = [[1, 2], [1.1, 2.2]]
+ b_ub = [4, 8]
+ bounds = [(1, 2), (2, 2)]
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ _assert_infeasible(res)
+
+ def test_zero_column_1(self):
+ m, n = 3, 4
+ rng = np.random.default_rng(558329500002933)
+ c = rng.random(n)
+ c[1] = 1
+ A_eq = rng.random((m, n))
+ A_eq[:, 1] = 0
+ b_eq = rng.random(m)
+ A_ub = [[1, 0, 1, 1]]
+ b_ub = 3
+ bounds = [(-10, 10), (-10, 10), (-10, None), (None, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-9.485758655190649) # method='highs' solution
+
+ def test_zero_column_2(self):
+ if self.method in {'highs-ds', 'highs-ipm'}:
+ # See upstream issue https://github.com/ERGO-Code/HiGHS/issues/648
+ pytest.xfail()
+
+ rng = np.random.default_rng(4492835845925983465)
+ m, n = 2, 4
+ c = rng.random(n)
+ c[1] = -1
+ A_eq = rng.random((m, n))
+ A_eq[:, 1] = 0
+ b_eq = rng.random(m)
+
+ A_ub = rng.random((m, n))
+ A_ub[:, 1] = 0
+ b_ub = rng.random(m)
+ bounds = (None, None)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ # Unboundedness detected in presolve
+ if self.options.get('presolve', True) and "highs" not in self.method:
+ # HiGHS detects unboundedness or infeasibility in presolve
+ # It needs an iteration of simplex to be sure of unboundedness
+ # Other solvers report that the problem is unbounded if feasible
+ assert_equal(res.nit, 0)
+
+ def test_zero_row_1(self):
+ c = [1, 2, 3]
+ A_eq = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
+ b_eq = [0, 3, 0]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3)
+
+ def test_zero_row_2(self):
+ A_ub = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
+ b_ub = [0, 3, 0]
+ c = [1, 2, 3]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0)
+
+ def test_zero_row_3(self):
+ m, n = 2, 4
+ rng = np.random.default_rng(49949482723982545)
+ c = rng.random(n)
+ A_eq = rng.random((m, n))
+ A_eq[0, :] = 0
+ b_eq = rng.random(m)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_zero_row_4(self):
+ m, n = 2, 4
+ rng = np.random.default_rng(1032934859282349)
+ c = rng.random(n)
+ A_ub = rng.random((m, n))
+ A_ub[0, :] = 0
+ b_ub = -rng.random(m)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_singleton_row_eq_1(self):
+ c = [1, 1, 1, 2]
+ A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]
+ b_eq = [1, 2, 2, 4]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_singleton_row_eq_2(self):
+ c = [1, 1, 1, 2]
+ A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]
+ b_eq = [1, 2, 1, 4]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=4)
+
+ def test_singleton_row_ub_1(self):
+ c = [1, 1, 1, 2]
+ A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]]
+ b_ub = [1, 2, -2, 4]
+ bounds = [(None, None), (0, None), (0, None), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_singleton_row_ub_2(self):
+ c = [1, 1, 1, 2]
+ A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]]
+ b_ub = [1, 2, -0.5, 4]
+ bounds = [(None, None), (0, None), (0, None), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0.5)
+
+ def test_infeasible(self):
+ # Test linprog response to an infeasible problem
+ c = [-1, -1]
+ A_ub = [[1, 0],
+ [0, 1],
+ [-1, -1]]
+ b_ub = [2, 2, -5]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_infeasible_inequality_bounds(self):
+ c = [1]
+ A_ub = [[2]]
+ b_ub = 4
+ bounds = (5, 6)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_unbounded(self):
+ # Test linprog response to an unbounded problem
+ c = np.array([1, 1]) * -1 # maximize
+ A_ub = [[-1, 1],
+ [-1, -1]]
+ b_ub = [-1, -2]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+
+ def test_unbounded_below_no_presolve_corrected(self):
+ c = [1]
+ bounds = [(None, 1)]
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c=c, bounds=bounds,
+ method=self.method,
+ options=o)
+ if self.method == "revised simplex":
+ # Revised simplex has a special pathway for no constraints.
+ assert_equal(res.status, 5)
+ else:
+ _assert_unbounded(res)
+
+ def test_unbounded_no_nontrivial_constraints_1(self):
+ """
+ Test whether presolve pathway for detecting unboundedness after
+ constraint elimination is working.
+ """
+ c = np.array([0, 0, 0, 1, -1, -1])
+ A_ub = np.array([[1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, -1]])
+ b_ub = np.array([2, -2, 0])
+ bounds = [(None, None), (None, None), (None, None),
+ (-1, 1), (-1, 1), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ if not self.method.lower().startswith("highs"):
+ assert_equal(res.x[-1], np.inf)
+ assert_equal(res.message[:36],
+ "The problem is (trivially) unbounded")
+
+ def test_unbounded_no_nontrivial_constraints_2(self):
+ """
+ Test whether presolve pathway for detecting unboundedness after
+ constraint elimination is working.
+ """
+ c = np.array([0, 0, 0, 1, -1, 1])
+ A_ub = np.array([[1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1]])
+ b_ub = np.array([2, -2, 0])
+ bounds = [(None, None), (None, None), (None, None),
+ (-1, 1), (-1, 1), (None, 0)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ if not self.method.lower().startswith("highs"):
+ assert_equal(res.x[-1], -np.inf)
+ assert_equal(res.message[:36],
+ "The problem is (trivially) unbounded")
+
+ def test_cyclic_recovery(self):
+ # Test linprogs recovery from cycling using the Klee-Minty problem
+ # Klee-Minty https://www.math.ubc.ca/~israel/m340/kleemin3.pdf
+ c = np.array([100, 10, 1]) * -1 # maximize
+ A_ub = [[1, 0, 0],
+ [20, 1, 0],
+ [200, 20, 1]]
+ b_ub = [1, 100, 10000]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[0, 0, 10000], atol=5e-6, rtol=1e-7)
+
+ def test_cyclic_bland(self):
+ # Test the effect of Bland's rule on a cycling problem
+ c = np.array([-10, 57, 9, 24.])
+ A_ub = np.array([[0.5, -5.5, -2.5, 9],
+ [0.5, -1.5, -0.5, 1],
+ [1, 0, 0, 0]])
+ b_ub = [0, 0, 1]
+
+ # copy the existing options dictionary but change maxiter
+ maxiter = 100
+ o = {key: val for key, val in self.options.items()}
+ o['maxiter'] = maxiter
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+
+ if self.method == 'simplex' and not self.options.get('bland'):
+ # simplex cycles without Bland's rule
+ _assert_iteration_limit_reached(res, o['maxiter'])
+ else:
+ # other methods, including simplex with Bland's rule, succeed
+ _assert_success(res, desired_x=[1, 0, 1, 0])
+ # note that revised simplex skips this test because it may or may not
+ # cycle depending on the initial basis
+
+ def test_remove_redundancy_infeasibility(self):
+ # mostly a test of redundancy removal, which is carefully tested in
+ # test__remove_redundancy.py
+ m, n = 10, 10
+ rng = np.random.default_rng(253985716283940)
+ c = rng.random(n)
+ A_eq = rng.random((m, n))
+ b_eq = rng.random(m)
+ A_eq[-1, :] = 2 * A_eq[-2, :]
+ b_eq[-1] *= -1
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ #################
+ # General Tests #
+ #################
+
+ def test_nontrivial_problem(self):
+ # Problem involves all constraint types,
+ # negative resource limits, and rounding issues.
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+
+ def test_lpgen_problem(self):
+ # Test linprog with a rather large problem (400 variables,
+ # 40 constraints) generated by https://gist.github.com/denis-bz/8647461
+ A_ub, b_ub, c = lpgen_2d(20, 20)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'sym_pos'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_network_flow(self):
+ # A network flow problem with supply and demand at nodes
+ # and with costs along directed edges.
+ # https://www.princeton.edu/~rvdb/542/lectures/lec10.pdf
+ c = [2, 4, 9, 11, 4, 3, 8, 7, 0, 15, 16, 18]
+ n, p = -1, 1
+ A_eq = [
+ [n, n, p, 0, p, 0, 0, 0, 0, p, 0, 0],
+ [p, 0, 0, p, 0, p, 0, 0, 0, 0, 0, 0],
+ [0, 0, n, n, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, p, p, 0, 0, p, 0],
+ [0, 0, 0, 0, n, n, n, 0, p, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, n, n, 0, 0, p],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, n, n, n]]
+ b_eq = [0, 19, -16, 33, 0, 0, -36]
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=755, atol=1e-6, rtol=1e-7)
+
+ def test_network_flow_limited_capacity(self):
+ # A network flow problem with supply and demand at nodes
+ # and with costs and capacities along directed edges.
+ # http://blog.sommer-forst.de/2013/04/10/
+ c = [2, 2, 1, 3, 1]
+ bounds = [
+ [0, 4],
+ [0, 2],
+ [0, 2],
+ [0, 3],
+ [0, 5]]
+ n, p = -1, 1
+ A_eq = [
+ [n, n, 0, 0, 0],
+ [p, 0, n, n, 0],
+ [0, p, p, 0, n],
+ [0, 0, 0, p, p]]
+ b_eq = [-4, 0, 0, 4]
+
+ with warnings.catch_warnings():
+ # this is an UmfpackWarning but I had trouble importing it
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "scipy.linalg.solve\nIll...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=14)
+
+ def test_simplex_algorithm_wikipedia_example(self):
+ # https://en.wikipedia.org/wiki/Simplex_algorithm#Example
+ c = [-2, -3, -4]
+ A_ub = [
+ [3, 2, 1],
+ [2, 5, 3]]
+ b_ub = [10, 15]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-20)
+
+ def test_enzo_example(self):
+ # https://github.com/scipy/scipy/issues/1779 lp2.py
+ #
+ # Translated from Octave code at:
+ # http://www.ecs.shimane-u.ac.jp/~kyoshida/lpeng.htm
+ # and placed under MIT licence by Enzo Michelangeli
+ # with permission explicitly granted by the original author,
+ # Prof. Kazunobu Yoshida
+ c = [4, 8, 3, 0, 0, 0]
+ A_eq = [
+ [2, 5, 3, -1, 0, 0],
+ [3, 2.5, 8, 0, -1, 0],
+ [8, 10, 4, 0, 0, -1]]
+ b_eq = [185, 155, 600]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=317.5,
+ desired_x=[66.25, 0, 17.5, 0, 183.75, 0],
+ atol=6e-6, rtol=1e-7)
+
+ def test_enzo_example_b(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ c = [2.8, 6.3, 10.8, -2.8, -6.3, -10.8]
+ A_eq = [[-1, -1, -1, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1],
+ [1, 0, 0, 1, 0, 0],
+ [0, 1, 0, 0, 1, 0],
+ [0, 0, 1, 0, 0, 1]]
+ b_eq = [-0.5, 0.4, 0.3, 0.3, 0.3]
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-1.77,
+ desired_x=[0.3, 0.2, 0.0, 0.0, 0.1, 0.3])
+
+ def test_enzo_example_c_with_degeneracy(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ m = 20
+ c = -np.ones(m)
+ tmp = 2 * np.pi * np.arange(1, m + 1) / (m + 1)
+ A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))
+ b_eq = [0, 0]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0, desired_x=np.zeros(m))
+
+ def test_enzo_example_c_with_unboundedness(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ m = 50
+ c = -np.ones(m)
+ tmp = 2 * np.pi * np.arange(m) / (m + 1)
+ # This test relies on `cos(0) -1 == sin(0)`, so ensure that's true
+ # (SIMD code or -ffast-math may cause spurious failures otherwise)
+ row0 = np.cos(tmp) - 1
+ row0[0] = 0.0
+ row1 = np.sin(tmp)
+ row1[0] = 0.0
+ A_eq = np.vstack((row0, row1))
+ b_eq = [0, 0]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+
+ def test_enzo_example_c_with_infeasibility(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ m = 50
+ c = -np.ones(m)
+ tmp = 2 * np.pi * np.arange(m) / (m + 1)
+ A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))
+ b_eq = [1, 1]
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ _assert_infeasible(res)
+
+ def test_basic_artificial_vars(self):
+ # Problem is chosen to test two phase simplex methods when at the end
+ # of phase 1 some artificial variables remain in the basis.
+ # Also, for `method='simplex'`, the row in the tableau corresponding
+ # with the artificial variables is not all zero.
+ c = np.array([-0.1, -0.07, 0.004, 0.004, 0.004, 0.004])
+ A_ub = np.array([[1.0, 0, 0, 0, 0, 0], [-1.0, 0, 0, 0, 0, 0],
+ [0, -1.0, 0, 0, 0, 0], [0, 1.0, 0, 0, 0, 0],
+ [1.0, 1.0, 0, 0, 0, 0]])
+ b_ub = np.array([3.0, 3.0, 3.0, 3.0, 20.0])
+ A_eq = np.array([[1.0, 0, -1, 1, -1, 1], [0, -1.0, -1, 1, -1, 1]])
+ b_eq = np.array([0, 0])
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0, desired_x=np.zeros_like(c),
+ atol=2e-6)
+
+ def test_optimize_result(self):
+ # check all fields in OptimizeResult
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(0)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+ assert_(res.success)
+ assert_(res.nit)
+ assert_(not res.status)
+ if 'highs' not in self.method:
+ # HiGHS status/message tested separately
+ assert_(res.message == "Optimization terminated successfully.")
+ assert_allclose(c @ res.x, res.fun)
+ assert_allclose(b_eq - A_eq @ res.x, res.con, atol=1e-11)
+ assert_allclose(b_ub - A_ub @ res.x, res.slack, atol=1e-11)
+ for key in ['eqlin', 'ineqlin', 'lower', 'upper']:
+ if key in res.keys():
+ assert isinstance(res[key]['marginals'], np.ndarray)
+ assert isinstance(res[key]['residual'], np.ndarray)
+
+ #################
+ # Bug Fix Tests #
+ #################
+
+ def test_bug_5400(self):
+ # https://github.com/scipy/scipy/issues/5400
+ bounds = [
+ (0, None),
+ (0, 100), (0, 100), (0, 100), (0, 100), (0, 100), (0, 100),
+ (0, 900), (0, 900), (0, 900), (0, 900), (0, 900), (0, 900),
+ (0, None), (0, None), (0, None), (0, None), (0, None), (0, None)]
+
+ f = 1 / 9
+ g = -1e4
+ h = -3.1
+ A_ub = np.array([
+ [1, -2.99, 0, 0, -3, 0, 0, 0, -1, -1, 0, -1, -1, 1, 1, 0, 0, 0, 0],
+ [1, 0, -2.9, h, 0, -3, 0, -1, 0, 0, -1, 0, -1, 0, 0, 1, 1, 0, 0],
+ [1, 0, 0, h, 0, 0, -3, -1, -1, 0, -1, -1, 0, 0, 0, 0, 0, 1, 1],
+ [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1],
+ [0, 1.99, -1, -1, 0, 0, 0, -1, f, f, 0, 0, 0, g, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 2, -1, -1, 0, 0, 0, -1, f, f, 0, g, 0, 0, 0, 0],
+ [0, -1, 1.9, 2.1, 0, 0, 0, f, -1, -1, 0, 0, 0, 0, 0, g, 0, 0, 0],
+ [0, 0, 0, 0, -1, 2, -1, 0, 0, 0, f, -1, f, 0, 0, 0, g, 0, 0],
+ [0, -1, -1, 2.1, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, 0, 0, g, 0],
+ [0, 0, 0, 0, -1, -1, 2, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, g]])
+
+ b_ub = np.array([
+ 0.0, 0, 0, 100, 100, 100, 100, 100, 100, 900, 900, 900, 900, 900,
+ 900, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
+
+ c = np.array([-1.0, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'sym_pos'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-106.63507541835018)
+
+ def test_bug_6139(self):
+ # linprog(method='simplex') fails to find a basic feasible solution
+ # if phase 1 pseudo-objective function is outside the provided tol.
+ # https://github.com/scipy/scipy/issues/6139
+
+ # Note: This is not strictly a bug as the default tolerance determines
+ # if a result is "close enough" to zero and should not be expected
+ # to work for all cases.
+
+ c = np.array([1, 1, 1])
+ A_eq = np.array([[1., 0., 0.], [-1000., 0., - 1000.]])
+ b_eq = np.array([5.00000000e+00, -1.00000000e+04])
+ A_ub = -np.array([[0., 1000000., 1010000.]])
+ b_ub = -np.array([10000000.])
+ bounds = (None, None)
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ _assert_success(res, desired_fun=14.95,
+ desired_x=np.array([5, 4.95, 5]))
+
+ def test_bug_6690(self):
+ # linprog simplex used to violate bound constraint despite reporting
+ # success.
+ # https://github.com/scipy/scipy/issues/6690
+
+ A_eq = np.array([[0, 0, 0, 0.93, 0, 0.65, 0, 0, 0.83, 0]])
+ b_eq = np.array([0.9626])
+ A_ub = np.array([
+ [0, 0, 0, 1.18, 0, 0, 0, -0.2, 0, -0.22],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0.43, 0, 0, 0, 0, 0, 0],
+ [0, -1.22, -0.25, 0, 0, 0, -2.06, 0, 0, 1.37],
+ [0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0]
+ ])
+ b_ub = np.array([0.615, 0, 0.172, -0.869, -0.022])
+ bounds = np.array([
+ [-0.84, -0.97, 0.34, 0.4, -0.33, -0.74, 0.47, 0.09, -1.45, -0.73],
+ [0.37, 0.02, 2.86, 0.86, 1.18, 0.5, 1.76, 0.17, 0.32, -0.15]
+ ]).T
+ c = np.array([
+ -1.64, 0.7, 1.8, -1.06, -1.16, 0.26, 2.13, 1.53, 0.66, 0.28
+ ])
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'cholesky'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'sym_pos'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ desired_fun = -1.19099999999
+ desired_x = np.array([0.3700, -0.9700, 0.3400, 0.4000, 1.1800,
+ 0.5000, 0.4700, 0.0900, 0.3200, -0.7300])
+ _assert_success(res, desired_fun=desired_fun, desired_x=desired_x)
+
+ # Add small tol value to ensure arrays are less than or equal.
+ atol = 1e-6
+ assert_array_less(bounds[:, 0] - atol, res.x)
+ assert_array_less(res.x, bounds[:, 1] + atol)
+
+ def test_bug_7044(self):
+ # linprog simplex failed to "identify correct constraints" (?)
+ # leading to a non-optimal solution if A is rank-deficient.
+ # https://github.com/scipy/scipy/issues/7044
+
+ A_eq, b_eq, c, _, _ = magic_square(3)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ desired_fun = 1.7002011030086288 # `method='highs' solution
+ _assert_success(res, desired_fun=desired_fun)
+ assert_allclose(A_eq.dot(res.x), b_eq)
+ assert_array_less(np.zeros(res.x.size) - 1e-5, res.x)
+
+ def test_bug_7237(self):
+ # https://github.com/scipy/scipy/issues/7237
+ # linprog simplex "explodes" when the pivot value is very
+ # close to zero.
+
+ c = np.array([-1, 0, 0, 0, 0, 0, 0, 0, 0])
+ A_ub = np.array([
+ [1., -724., 911., -551., -555., -896., 478., -80., -293.],
+ [1., 566., 42., 937., 233., 883., 392., -909., 57.],
+ [1., -208., -894., 539., 321., 532., -924., 942., 55.],
+ [1., 857., -859., 83., 462., -265., -971., 826., 482.],
+ [1., 314., -424., 245., -424., 194., -443., -104., -429.],
+ [1., 540., 679., 361., 149., -827., 876., 633., 302.],
+ [0., -1., -0., -0., -0., -0., -0., -0., -0.],
+ [0., -0., -1., -0., -0., -0., -0., -0., -0.],
+ [0., -0., -0., -1., -0., -0., -0., -0., -0.],
+ [0., -0., -0., -0., -1., -0., -0., -0., -0.],
+ [0., -0., -0., -0., -0., -1., -0., -0., -0.],
+ [0., -0., -0., -0., -0., -0., -1., -0., -0.],
+ [0., -0., -0., -0., -0., -0., -0., -1., -0.],
+ [0., -0., -0., -0., -0., -0., -0., -0., -1.],
+ [0., 1., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 1., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 1.]
+ ])
+ b_ub = np.array([
+ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1.])
+ A_eq = np.array([[0., 1., 1., 1., 1., 1., 1., 1., 1.]])
+ b_eq = np.array([[1.]])
+ bounds = [(None, None)] * 9
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=108.568535, atol=1e-6)
+
+ def test_bug_8174(self):
+ # https://github.com/scipy/scipy/issues/8174
+ # The simplex method sometimes "explodes" if the pivot value is very
+ # close to zero.
+ A_ub = np.array([
+ [22714, 1008, 13380, -2713.5, -1116],
+ [-4986, -1092, -31220, 17386.5, 684],
+ [-4986, 0, 0, -2713.5, 0],
+ [22714, 0, 0, 17386.5, 0]])
+ b_ub = np.zeros(A_ub.shape[0])
+ c = -np.ones(A_ub.shape[1])
+ bounds = [(0, 1)] * A_ub.shape[1]
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ if self.options.get('tol', 1e-9) < 1e-10 and self.method == 'simplex':
+ _assert_unable_to_find_basic_feasible_sol(res)
+ else:
+ _assert_success(res, desired_fun=-2.0080717488789235, atol=1e-6)
+
+ def test_bug_8174_2(self):
+ # Test supplementary example from issue 8174.
+ # https://github.com/scipy/scipy/issues/8174
+ # https://stackoverflow.com/questions/47717012/linprog-in-scipy-optimize-checking-solution
+ c = np.array([1, 0, 0, 0, 0, 0, 0])
+ A_ub = -np.identity(7)
+ b_ub = np.array([[-2], [-2], [-2], [-2], [-2], [-2], [-2]])
+ A_eq = np.array([
+ [1, 1, 1, 1, 1, 1, 0],
+ [0.3, 1.3, 0.9, 0, 0, 0, -1],
+ [0.3, 0, 0, 0, 0, 0, -2/3],
+ [0, 0.65, 0, 0, 0, 0, -1/15],
+ [0, 0, 0.3, 0, 0, 0, -1/15]
+ ])
+ b_eq = np.array([[100], [0], [0], [0], [0]])
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=43.3333333331385)
+
+ def test_bug_8561(self):
+ # Test that pivot row is chosen correctly when using Bland's rule
+ # This was originally written for the simplex method with
+ # Bland's rule only, but it doesn't hurt to test all methods/options
+ # https://github.com/scipy/scipy/issues/8561
+ c = np.array([7, 0, -4, 1.5, 1.5])
+ A_ub = np.array([
+ [4, 5.5, 1.5, 1.0, -3.5],
+ [1, -2.5, -2, 2.5, 0.5],
+ [3, -0.5, 4, -12.5, -7],
+ [-1, 4.5, 2, -3.5, -2],
+ [5.5, 2, -4.5, -1, 9.5]])
+ b_ub = np.array([0, 0, 0, 0, 1])
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, options=self.options,
+ method=self.method)
+ _assert_success(res, desired_x=[0, 0, 19, 16/3, 29/3])
+
+ def test_bug_8662(self):
+ # linprog simplex used to report incorrect optimal results
+ # https://github.com/scipy/scipy/issues/8662
+ c = [-10, 10, 6, 3]
+ A_ub = [[8, -8, -4, 6],
+ [-8, 8, 4, -6],
+ [-4, 4, 8, -4],
+ [3, -3, -3, -10]]
+ b_ub = [9, -9, -9, -4]
+ bounds = [(0, None), (0, None), (0, None), (0, None)]
+ desired_fun = 36.0000000000
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res1 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ # Set boundary condition as a constraint
+ A_ub.append([0, 0, -1, 0])
+ b_ub.append(0)
+ bounds[2] = (None, None)
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res2 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ rtol = 1e-5
+ _assert_success(res1, desired_fun=desired_fun, rtol=rtol)
+ _assert_success(res2, desired_fun=desired_fun, rtol=rtol)
+
+ def test_bug_8663(self):
+ # exposed a bug in presolve
+ # https://github.com/scipy/scipy/issues/8663
+ c = [1, 5]
+ A_eq = [[0, -7]]
+ b_eq = [-6]
+ bounds = [(0, None), (None, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[0, 6./7], desired_fun=5*6./7)
+
+ def test_bug_8664(self):
+ # interior-point has trouble with this when presolve is off
+ # tested for interior-point with presolve off in TestLinprogIPSpecific
+ # https://github.com/scipy/scipy/issues/8664
+ c = [4]
+ A_ub = [[2], [5]]
+ b_ub = [4, 4]
+ A_eq = [[0], [-8], [9]]
+ b_eq = [3, 2, 10]
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_bug_8973(self):
+ """
+ Test whether bug described at:
+ https://github.com/scipy/scipy/issues/8973
+ was fixed.
+ """
+ c = np.array([0, 0, 0, 1, -1])
+ A_ub = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0]])
+ b_ub = np.array([2, -2])
+ bounds = [(None, None), (None, None), (None, None), (-1, 1), (-1, 1)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ # solution vector x is not unique
+ _assert_success(res, desired_fun=-2)
+ # HiGHS IPM had an issue where the following wasn't true!
+ assert_equal(c @ res.x, res.fun)
+
+ def test_bug_8973_2(self):
+ """
+ Additional test for:
+ https://github.com/scipy/scipy/issues/8973
+ suggested in
+ https://github.com/scipy/scipy/pull/8985
+ review by @antonior92
+ """
+ c = np.zeros(1)
+ A_ub = np.array([[1]])
+ b_ub = np.array([-2])
+ bounds = (None, None)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[-2], desired_fun=0)
+
+ def test_bug_10124(self):
+ """
+ Test for linprog docstring problem
+ 'disp'=True caused revised simplex failure
+ """
+ c = np.zeros(1)
+ A_ub = np.array([[1]])
+ b_ub = np.array([-2])
+ bounds = (None, None)
+ c = [-1, 4]
+ A_ub = [[-3, 1], [1, 2]]
+ b_ub = [6, 4]
+ bounds = [(None, None), (-3, None)]
+ o = {"disp": True}
+ o.update(self.options)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ _assert_success(res, desired_x=[10, -3], desired_fun=-22)
+
+ def test_bug_10349(self):
+ """
+ Test for redundancy removal tolerance issue
+ https://github.com/scipy/scipy/issues/10349
+ """
+ A_eq = np.array([[1, 1, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 1, 1],
+ [1, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0],
+ [0, 1, 0, 0, 0, 1]])
+ b_eq = np.array([221, 210, 10, 141, 198, 102])
+ c = np.concatenate((0, 1, np.zeros(4)), axis=None)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[129, 92, 12, 198, 0, 10], desired_fun=92)
+
+ @pytest.mark.skipif(sys.platform == 'darwin',
+ reason=("Failing on some local macOS builds, "
+ "see gh-13846"))
+ def test_bug_10466(self):
+ """
+ Test that autoscale fixes poorly-scaled problem
+ """
+ c = [-8., -0., -8., -0., -8., -0., -0., -0., -0., -0., -0., -0., -0.]
+ A_eq = [[1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0.],
+ [1., 0., 1., 0., 1., 0., -1., 0., 0., 0., 0., 0., 0.],
+ [1., 0., 1., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
+ [1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
+ [1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
+ [1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0.],
+ [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 1., 0.],
+ [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1.]]
+
+ b_eq = [3.14572800e+08, 4.19430400e+08, 5.24288000e+08,
+ 1.00663296e+09, 1.07374182e+09, 1.07374182e+09,
+ 1.07374182e+09, 1.07374182e+09, 1.07374182e+09,
+ 1.07374182e+09]
+
+ o = {}
+ # HiGHS methods don't use autoscale option
+ if not self.method.startswith("highs"):
+ o = {"autoscale": True}
+ o.update(self.options)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "scipy.linalg.solve\nIll...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "divide by zero encountered...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "overflow encountered...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Ill-conditioned matrix...", LinAlgWarning)
+ warnings.filterwarnings(
+ "ignore", "An ill-conditioned...", LinAlgWarning)
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ assert_allclose(res.fun, -8589934560)
+
+
+#########################
+# Method-specific Tests #
+#########################
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class LinprogSimplexTests(LinprogCommonTests):
+ method = "simplex"
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class LinprogIPTests(LinprogCommonTests):
+ method = "interior-point"
+
+ def test_bug_10466(self):
+ pytest.skip("Test is failing, but solver is deprecated.")
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class LinprogRSTests(LinprogCommonTests):
+ method = "revised simplex"
+
+ # Revised simplex does not reliably solve these problems.
+ # Failure is intermittent due to the random choice of elements to complete
+ # the basis after phase 1 terminates. In any case, linprog exists
+ # gracefully, reporting numerical difficulties. I do not think this should
+ # prevent revised simplex from being merged, as it solves the problems
+ # most of the time and solves a broader range of problems than the existing
+ # simplex implementation.
+ # I believe that the root cause is the same for all three and that this
+ # same issue prevents revised simplex from solving many other problems
+ # reliably. Somehow the pivoting rule allows the algorithm to pivot into
+ # a singular basis. I haven't been able to find a reference that
+ # acknowledges this possibility, suggesting that there is a bug. On the
+ # other hand, the pivoting rule is quite simple, and I can't find a
+ # mistake, which suggests that this is a possibility with the pivoting
+ # rule. Hopefully, a better pivoting rule will fix the issue.
+
+ def test_bug_5400(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+ def test_bug_8662(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+ def test_network_flow(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+
+class LinprogHiGHSTests(LinprogCommonTests):
+ def test_callback(self):
+ # this is the problem from test_callback
+ def cb(res):
+ return None
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+ assert_raises(NotImplementedError, linprog, c, A_ub=A_ub, b_ub=b_ub,
+ callback=cb, method=self.method)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, method=self.method)
+ _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])
+
+ @pytest.mark.parametrize("options",
+ [{"maxiter": -1},
+ {"disp": -1},
+ {"presolve": -1},
+ {"time_limit": -1},
+ {"dual_feasibility_tolerance": -1},
+ {"primal_feasibility_tolerance": -1},
+ {"ipm_optimality_tolerance": -1},
+ {"simplex_dual_edge_weight_strategy": "ekki"},
+ ])
+ def test_invalid_option_values(self, options):
+ def f(options):
+ linprog(1, method=self.method, options=options)
+ options.update(self.options)
+ with pytest.warns(OptimizeWarning):
+ f(options=options)
+
+ def test_crossover(self):
+ A_eq, b_eq, c, _, _ = magic_square(4, rng=np.random.default_rng(2212392))
+ bounds = (0, 1)
+ res = linprog(c, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+ # there should be nonzero crossover iterations for IPM (only)
+ assert_equal(res.crossover_nit == 0, self.method != "highs-ipm")
+
+ @pytest.mark.fail_slow(10)
+ def test_marginals(self):
+ # Ensure lagrange multipliers are correct by comparing the derivative
+ # w.r.t. b_ub/b_eq/ub/lb to the reported duals.
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=0)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+ lb, ub = bounds.T
+
+ # sensitivity w.r.t. b_ub
+ def f_bub(x):
+ return linprog(c, A_ub, x, A_eq, b_eq, bounds,
+ method=self.method).fun
+
+ dfdbub = approx_derivative(f_bub, b_ub, method='3-point', f0=res.fun)
+ assert_allclose(res.ineqlin.marginals, dfdbub)
+
+ # sensitivity w.r.t. b_eq
+ def f_beq(x):
+ return linprog(c, A_ub, b_ub, A_eq, x, bounds,
+ method=self.method).fun
+
+ dfdbeq = approx_derivative(f_beq, b_eq, method='3-point', f0=res.fun)
+ assert_allclose(res.eqlin.marginals, dfdbeq)
+
+ # sensitivity w.r.t. lb
+ def f_lb(x):
+ bounds = np.array([x, ub]).T
+ return linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method).fun
+
+ with np.errstate(invalid='ignore'):
+ # approx_derivative has trouble where lb is infinite
+ dfdlb = approx_derivative(f_lb, lb, method='3-point', f0=res.fun)
+ dfdlb[~np.isfinite(lb)] = 0
+
+ assert_allclose(res.lower.marginals, dfdlb)
+
+ # sensitivity w.r.t. ub
+ def f_ub(x):
+ bounds = np.array([lb, x]).T
+ return linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method).fun
+
+ with np.errstate(invalid='ignore'):
+ dfdub = approx_derivative(f_ub, ub, method='3-point', f0=res.fun)
+ dfdub[~np.isfinite(ub)] = 0
+
+ assert_allclose(res.upper.marginals, dfdub)
+
+ def test_dual_feasibility(self):
+ # Ensure solution is dual feasible using marginals
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=42)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+
+ # KKT dual feasibility equation from Theorem 1 from
+ # http://www.personal.psu.edu/cxg286/LPKKT.pdf
+ resid = (-c + A_ub.T @ res.ineqlin.marginals +
+ A_eq.T @ res.eqlin.marginals +
+ res.upper.marginals +
+ res.lower.marginals)
+ assert_allclose(resid, 0, atol=1e-12)
+
+ def test_complementary_slackness(self):
+ # Ensure that the complementary slackness condition is satisfied.
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=42)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+
+ # KKT complementary slackness equation from Theorem 1 from
+ # http://www.personal.psu.edu/cxg286/LPKKT.pdf modified for
+ # non-zero RHS
+ assert np.allclose(res.ineqlin.marginals @ (b_ub - A_ub @ res.x), 0)
+
+ @pytest.mark.xfail(reason='Upstream / Wrapper issue, see gh-20589')
+ def test_bug_20336(self):
+ """
+ Test that `linprog` now solves a poorly-scaled problem
+ """
+ boundaries = [(10000.0, 9010000.0), (0.0, None), (10000.0, None),
+ (0.0, 84.62623413258109), (10000.0, None), (10000.0, None),
+ (10000.0, None), (10000.0, None), (10000.0, None),
+ (10000.0, None), (10000.0, None), (10000.0, None),
+ (10000.0, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None)]
+ eq_entries = [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0,
+ -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 0.001,
+ -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0,
+ 0.001, -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10,
+ 1.0, -1.0, 0.001, -0.001, 3.7337777768059636e-10,
+ 3.7337777768059636e-10, 1.0, -1.0, 0.001, -0.001,
+ 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, 0.001,
+ -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0,
+ 0.001, -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10,
+ 1.0, -1.0, 0.001, -0.001, 3.7337777768059636e-10,
+ 3.7337777768059636e-10, 1.0, -1.0, 0.001, -0.001,
+ 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, 0.001,
+ -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0,
+ -1.0, 0.001, -0.001, 3.7337777768059636e-10,
+ 3.7337777768059636e-10, 1.0, -1.0]
+ eq_indizes = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10,
+ 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 16,
+ 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21,
+ 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 25, 25, 26, 26, 26, 26,
+ 27, 27, 28, 28, 28, 28, 29, 29, 30, 30, 30, 30, 31, 31]
+ eq_vars = [15, 14, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 31,
+ 30, 13, 1, 0, 32, 3, 14, 13, 4, 0, 4, 0, 32, 31, 2, 12, 2, 12, 16,
+ 15, 5, 4, 5, 4, 18, 17, 6, 5, 6, 5, 20, 19, 7, 6, 7, 6, 22, 21, 8,
+ 7, 8, 7, 24, 23, 9, 8, 9, 8, 26, 25, 10, 9, 10, 9, 28, 27, 11, 10,
+ 11, 10, 30, 29, 12, 11, 12, 11]
+ eq_values = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9000000.0, 0.0,
+ 0.006587392118285457, -5032.197406716549, 0.0041860502789104696,
+ -7918.93439542944, 0.0063205763583549035, -5244.625751707402,
+ 0.006053760598424349, -5475.7793929428, 0.005786944838493795,
+ -5728.248403917573, 0.0055201290785632405, -6005.123623538355,
+ 0.005253313318632687, -6310.123825488683, 0.004986497558702133,
+ -6647.763714796453, 0.004719681798771578, -7023.578908071522,
+ 0.004452866038841024, -7444.431798646482]
+ coefficients = [0.0, 0.0, 0.0, -0.011816666666666668, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
+ np_eq_entries = np.asarray(eq_entries, dtype=np.float64)
+ np_eq_indizes = np.asarray(eq_indizes, dtype=np.int32)
+ np_eq_vars = np.asarray(eq_vars, dtype=np.int32)
+
+ a_eq= scipy.sparse.csr_array((np_eq_entries,(np_eq_indizes, np_eq_vars)),
+ shape=(32, 33))
+ b_eq = np.asarray(eq_values, dtype=np.float64)
+ c = np.asarray(coefficients, dtype=np.float64)
+
+ result = scipy.optimize.linprog(c, A_ub=None, b_ub=None, A_eq=a_eq, b_eq=b_eq,
+ bounds=boundaries)
+ assert result.status==0
+ x = result.x
+ n_r_x = np.linalg.norm(a_eq @ x - b_eq)
+ n_r = np.linalg.norm(result.eqlin.residual)
+ assert_allclose(n_r, n_r_x)
+
+
+################################
+# Simplex Option-Specific Tests#
+################################
+
+
+class TestLinprogSimplexDefault(LinprogSimplexTests):
+
+ def setup_method(self):
+ self.options = {}
+
+ def test_bug_5400(self):
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_7237_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate error is raised.
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_8174_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate warning is issued.
+ self.options.update({'tol': 1e-12})
+ with pytest.warns(OptimizeWarning):
+ super().test_bug_8174()
+
+
+class TestLinprogSimplexBland(LinprogSimplexTests):
+
+ def setup_method(self):
+ self.options = {'bland': True}
+
+ def test_bug_5400(self):
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_8174_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate error is raised.
+ self.options.update({'tol': 1e-12})
+ with pytest.raises(AssertionError):
+ with pytest.warns(OptimizeWarning):
+ super().test_bug_8174()
+
+
+class TestLinprogSimplexNoPresolve(LinprogSimplexTests):
+
+ def setup_method(self):
+ self.options = {'presolve': False}
+
+ is_32_bit = np.intp(0).itemsize < 8
+ is_linux = sys.platform.startswith('linux')
+
+ @pytest.mark.xfail(
+ condition=is_32_bit and is_linux,
+ reason='Fails with warning on 32-bit linux')
+ def test_bug_5400(self):
+ super().test_bug_5400()
+
+ def test_bug_6139_low_tol(self):
+ # Linprog(method='simplex') fails to find a basic feasible solution
+ # if phase 1 pseudo-objective function is outside the provided tol.
+ # https://github.com/scipy/scipy/issues/6139
+ # Without ``presolve`` eliminating such rows the result is incorrect.
+ self.options.update({'tol': 1e-12})
+ with pytest.raises(AssertionError, match='linprog status 4'):
+ return super().test_bug_6139()
+
+ def test_bug_7237_low_tol(self):
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_8174_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate warning is issued.
+ self.options.update({'tol': 1e-12})
+ with pytest.warns(OptimizeWarning):
+ super().test_bug_8174()
+
+ def test_unbounded_no_nontrivial_constraints_1(self):
+ pytest.skip("Tests behavior specific to presolve")
+
+ def test_unbounded_no_nontrivial_constraints_2(self):
+ pytest.skip("Tests behavior specific to presolve")
+
+
+#######################################
+# Interior-Point Option-Specific Tests#
+#######################################
+
+
+class TestLinprogIPDense(LinprogIPTests):
+ options = {"sparse": False}
+
+ # see https://github.com/scipy/scipy/issues/20216 for skip reason
+ @pytest.mark.skipif(
+ sys.platform == 'darwin',
+ reason="Fails on some macOS builds for reason not relevant to test"
+ )
+ def test_bug_6139(self):
+ super().test_bug_6139()
+
+if has_cholmod:
+ class TestLinprogIPSparseCholmod(LinprogIPTests):
+ options = {"sparse": True, "cholesky": True}
+
+
+if has_umfpack:
+ class TestLinprogIPSparseUmfpack(LinprogIPTests):
+ options = {"sparse": True, "cholesky": False}
+
+ def test_network_flow_limited_capacity(self):
+ pytest.skip("Failing due to numerical issues on some platforms.")
+
+
+class TestLinprogIPSparse(LinprogIPTests):
+ options = {"sparse": True, "cholesky": False, "sym_pos": False}
+
+ @pytest.mark.skipif(
+ sys.platform == 'darwin',
+ reason="Fails on macOS x86 Accelerate builds (gh-20510)"
+ )
+ @pytest.mark.xfail_on_32bit("This test is sensitive to machine epsilon level "
+ "perturbations in linear system solution in "
+ "_linprog_ip._sym_solve.")
+ def test_bug_6139(self):
+ super().test_bug_6139()
+
+ @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877')
+ def test_bug_6690(self):
+ # Test defined in base class, but can't mark as xfail there
+ super().test_bug_6690()
+
+ def test_magic_square_sparse_no_presolve(self):
+ # test linprog with a problem with a rank-deficient A_eq matrix
+ A_eq, b_eq, c, _, _ = magic_square(3)
+ bounds = (0, 1)
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "Matrix is exactly singular", MatrixRankWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ desired_fun = 1.7002011030086288 # method='highs' solution
+ _assert_success(res, desired_fun=desired_fun)
+
+ def test_sparse_solve_options(self):
+ # checking that problem is solved with all column permutation options
+ A_eq, b_eq, c, _, _ = magic_square(3)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Invalid permc_spec option", OptimizeWarning)
+ o = {key: self.options[key] for key in self.options}
+ permc_specs = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A',
+ 'COLAMD', 'ekki-ekki-ekki')
+ # 'ekki-ekki-ekki' raises warning about invalid permc_spec option
+ # and uses default
+ for permc_spec in permc_specs:
+ o["permc_spec"] = permc_spec
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ desired_fun = 1.7002011030086288 # `method='highs' solution
+ _assert_success(res, desired_fun=desired_fun)
+
+
+class TestLinprogIPSparsePresolve(LinprogIPTests):
+ options = {"sparse": True, "_sparse_presolve": True}
+
+ @pytest.mark.skipif(
+ sys.platform == 'darwin',
+ reason="Fails on macOS x86 Accelerate builds (gh-20510)"
+ )
+ @pytest.mark.xfail_on_32bit("This test is sensitive to machine epsilon level "
+ "perturbations in linear system solution in "
+ "_linprog_ip._sym_solve.")
+ def test_bug_6139(self):
+ super().test_bug_6139()
+
+ def test_enzo_example_c_with_infeasibility(self):
+ pytest.skip('_sparse_presolve=True incompatible with presolve=False')
+
+ @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877')
+ def test_bug_6690(self):
+ # Test defined in base class, but can't mark as xfail there
+ super().test_bug_6690()
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class TestLinprogIPSpecific:
+ method = "interior-point"
+ # the following tests don't need to be performed separately for
+ # sparse presolve, sparse after presolve, and dense
+
+ def test_solver_select(self):
+ # check that default solver is selected as expected
+ if has_cholmod:
+ options = {'sparse': True, 'cholesky': True}
+ elif has_umfpack:
+ options = {'sparse': True, 'cholesky': False}
+ else:
+ options = {'sparse': True, 'cholesky': False, 'sym_pos': False}
+ A, b, c = lpgen_2d(20, 20)
+ res1 = linprog(c, A_ub=A, b_ub=b, method=self.method, options=options)
+ res2 = linprog(c, A_ub=A, b_ub=b, method=self.method) # default solver
+ assert_allclose(res1.fun, res2.fun,
+ err_msg="linprog default solver unexpected result",
+ rtol=2e-15, atol=1e-15)
+
+ def test_unbounded_below_no_presolve_original(self):
+ # formerly caused segfault in TravisCI w/ "cholesky":True
+ c = [-1]
+ bounds = [(None, 1)]
+ res = linprog(c=c, bounds=bounds,
+ method=self.method,
+ options={"presolve": False, "cholesky": True})
+ _assert_success(res, desired_fun=-1)
+
+ def test_cholesky(self):
+ # use cholesky factorization and triangular solves
+ A, b, c = lpgen_2d(20, 20)
+ res = linprog(c, A_ub=A, b_ub=b, method=self.method,
+ options={"cholesky": True}) # only for dense
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_alternate_initial_point(self):
+ # use "improved" initial point
+ A, b, c = lpgen_2d(20, 20)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "scipy.linalg.solve\nIll...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Ill-conditioned matrix...", LinAlgWarning)
+ warnings.filterwarnings(
+ "ignore", "An ill-conditioned...", LinAlgWarning)
+
+ res = linprog(c, A_ub=A, b_ub=b, method=self.method,
+ options={"ip": True, "disp": True})
+ # ip code is independent of sparse/dense
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_bug_8664(self):
+ # interior-point has trouble with this when presolve is off
+ c = [4]
+ A_ub = [[2], [5]]
+ b_ub = [4, 4]
+ A_eq = [[0], [-8], [9]]
+ b_eq = [3, 2, 10]
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options={"presolve": False})
+ assert_(not res.success, "Incorrectly reported success")
+
+
+########################################
+# Revised Simplex Option-Specific Tests#
+########################################
+
+
+class TestLinprogRSCommon(LinprogRSTests):
+ options = {}
+
+ def test_cyclic_bland(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+ def test_nontrivial_problem_with_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_unbounded_variables(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bounds = [(None, None), (None, None), (0, None), (None, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_bounded_variables(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bounds = [(None, 1), (1, None), (0, None), (.4, .6)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_negative_unbounded_variable(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ b_eq = [4]
+ x_star = np.array([-219/385, 582/385, 0, 4/10])
+ f_star = 3951/385
+ bounds = [(None, None), (1, None), (0, None), (.4, .6)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_bad_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bad_guess = [1, 2, 3, .5]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=bad_guess)
+ assert_equal(res.status, 6)
+
+ def test_redundant_constraints_with_guess(self):
+ rng = np.random.default_rng(984298498729345)
+ A, b, c, _, _ = magic_square(3, rng=rng)
+ p = rng.random(c.shape)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_eq=A, b_eq=b, method=self.method)
+ res2 = linprog(c, A_eq=A, b_eq=b, method=self.method, x0=res.x)
+ res3 = linprog(c + p, A_eq=A, b_eq=b, method=self.method, x0=res.x)
+ _assert_success(res2, desired_fun=res.fun)
+ assert_equal(res2.nit, 0)
+ _assert_success(res3)
+ assert_(res3.nit < res.nit) # hot start reduces iterations
+
+
+class TestLinprogRSBland(LinprogRSTests):
+ options = {"pivot": "bland"}
+
+
+############################################
+# HiGHS-Simplex-Dual Option-Specific Tests #
+############################################
+
+
+class TestLinprogHiGHSSimplexDual(LinprogHiGHSTests):
+ method = "highs-ds"
+ options = {}
+
+ def test_lad_regression(self):
+ '''
+ The scaled model should be optimal, i.e. not produce unscaled model
+ infeasible. See https://github.com/ERGO-Code/HiGHS/issues/494.
+ '''
+ # Test to ensure gh-13610 is resolved (mismatch between HiGHS scaled
+ # and unscaled model statuses)
+ c, A_ub, b_ub, bnds = l1_regression_prob()
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bnds,
+ method=self.method, options=self.options)
+ assert_equal(res.status, 0)
+ assert_(res.x is not None)
+ assert_(np.all(res.slack > -1e-6))
+ assert_(np.all(res.x <= [np.inf if ub is None else ub
+ for lb, ub in bnds]))
+ assert_(np.all(res.x >= [-np.inf if lb is None else lb - 1e-7
+ for lb, ub in bnds]))
+
+
+###################################
+# HiGHS-IPM Option-Specific Tests #
+###################################
+
+
+class TestLinprogHiGHSIPM(LinprogHiGHSTests):
+ method = "highs-ipm"
+ options = {}
+
+
+###################################
+# HiGHS-MIP Option-Specific Tests #
+###################################
+
+
+class TestLinprogHiGHSMIP:
+ method = "highs"
+ options = {}
+
+ @pytest.mark.fail_slow(10)
+ @pytest.mark.xfail(condition=(sys.maxsize < 2 ** 32 and
+ platform.system() == "Linux"),
+ run=False,
+ reason="gh-16347")
+ def test_mip1(self):
+ # solve non-relaxed magic square problem (finally!)
+ # also check that values are all integers - they don't always
+ # come out of HiGHS that way
+ n = 4
+ A, b, c, numbers, M = magic_square(n)
+ bounds = [(0, 1)] * len(c)
+ integrality = [1] * len(c)
+
+ res = linprog(c=c*0, A_eq=A, b_eq=b, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ s = (numbers.flatten() * res.x).reshape(n**2, n, n)
+ square = np.sum(s, axis=0)
+ np.testing.assert_allclose(square.sum(axis=0), M)
+ np.testing.assert_allclose(square.sum(axis=1), M)
+ np.testing.assert_allclose(np.diag(square).sum(), M)
+ np.testing.assert_allclose(np.diag(square[:, ::-1]).sum(), M)
+
+ np.testing.assert_allclose(res.x, np.round(res.x), atol=1e-12)
+
+ def test_mip2(self):
+ # solve MIP with inequality constraints and all integer constraints
+ # source: slide 5,
+ # https://www.cs.upc.edu/~erodri/webpage/cps/theory/lp/milp/slides.pdf
+
+ # use all array inputs to test gh-16681 (integrality couldn't be array)
+ A_ub = np.array([[2, -2], [-8, 10]])
+ b_ub = np.array([-1, 13])
+ c = -np.array([1, 1])
+
+ bounds = np.array([(0, np.inf)] * len(c))
+ integrality = np.ones_like(c)
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [1, 2])
+ np.testing.assert_allclose(res.fun, -3)
+
+ def test_mip3(self):
+ # solve MIP with inequality constraints and all integer constraints
+ # source: https://en.wikipedia.org/wiki/Integer_programming#Example
+ A_ub = np.array([[-1, 1], [3, 2], [2, 3]])
+ b_ub = np.array([1, 12, 12])
+ c = -np.array([0, 1])
+
+ bounds = [(0, np.inf)] * len(c)
+ integrality = [1] * len(c)
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.fun, -2)
+ # two optimal solutions possible, just need one of them
+ assert np.allclose(res.x, [1, 2]) or np.allclose(res.x, [2, 2])
+
+ def test_mip4(self):
+ # solve MIP with inequality constraints and only one integer constraint
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_ub = np.array([[-1, -2], [-4, -1], [2, 1]])
+ b_ub = np.array([14, -33, 20])
+ c = np.array([8, 1])
+
+ bounds = [(0, np.inf)] * len(c)
+ integrality = [0, 1]
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [6.5, 7])
+ np.testing.assert_allclose(res.fun, 59)
+
+ def test_mip5(self):
+ # solve MIP with inequality and inequality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_ub = np.array([[1, 1, 1]])
+ b_ub = np.array([7])
+ A_eq = np.array([[4, 2, 1]])
+ b_eq = np.array([12])
+ c = np.array([-3, -2, -1])
+
+ bounds = [(0, np.inf), (0, np.inf), (0, 1)]
+ integrality = [0, 1, 0]
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method,
+ integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [0, 6, 0])
+ np.testing.assert_allclose(res.fun, -12)
+
+ # gh-16897: these fields were not present, ensure that they are now
+ assert res.get("mip_node_count", None) is not None
+ assert res.get("mip_dual_bound", None) is not None
+ assert res.get("mip_gap", None) is not None
+
+ @pytest.mark.xslow
+ def test_mip6(self):
+ # solve a larger MIP with only equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ bounds = [(0, np.inf)]*8
+ integrality = [1]*8
+
+ res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.fun, 1854)
+
+ @pytest.mark.xslow
+ def test_mip_rel_gap_passdown(self):
+ # MIP taken from test_mip6, solved with different values of mip_rel_gap
+ # solve a larger MIP with only equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ bounds = [(0, np.inf)]*8
+ integrality = [1]*8
+
+ mip_rel_gaps = [0.5, 0.25, 0.01, 0.001]
+ sol_mip_gaps = []
+ for mip_rel_gap in mip_rel_gaps:
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method,
+ integrality=integrality,
+ options={"mip_rel_gap": mip_rel_gap})
+ final_mip_gap = res["mip_gap"]
+ # assert that the solution actually has mip_gap lower than the
+ # required mip_rel_gap supplied
+ assert final_mip_gap <= mip_rel_gap
+ sol_mip_gaps.append(final_mip_gap)
+
+ # make sure that the mip_rel_gap parameter is actually doing something
+ # check that differences between solution gaps are declining
+ # monotonically with the mip_rel_gap parameter. np.diff does
+ # x[i+1] - x[i], so flip the array before differencing to get
+ # what should be a positive, monotone decreasing series of solution
+ # gaps
+ gap_diffs = np.diff(np.flip(sol_mip_gaps))
+ assert np.all(gap_diffs >= 0)
+ assert not np.all(gap_diffs == 0)
+
+ def test_semi_continuous(self):
+ # See issue #18106. This tests whether the solution is being
+ # checked correctly (status is 0) when integrality > 1:
+ # values are allowed to be 0 even if 0 is out of bounds.
+
+ c = np.array([1., 1., -1, -1])
+ bounds = np.array([[0.5, 1.5], [0.5, 1.5], [0.5, 1.5], [0.5, 1.5]])
+ integrality = np.array([2, 3, 2, 3])
+
+ res = linprog(c, bounds=bounds,
+ integrality=integrality, method='highs')
+
+ np.testing.assert_allclose(res.x, [0, 0, 1.5, 1])
+ assert res.status == 0
+
+ def test_bug_20584(self):
+ """
+ Test that when integrality is a list of all zeros, linprog gives the
+ same result as when it is an array of all zeros / integrality=None
+ """
+ c = [1, 1]
+ A_ub = [[-1, 0]]
+ b_ub = [-2.5]
+ res1 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=[0, 0])
+ res2 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=np.asarray([0, 0]))
+ res3 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=None)
+ assert_equal(res1.x, res2.x)
+ assert_equal(res1.x, res3.x)
+
+
+###########################
+# Autoscale-Specific Tests#
+###########################
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class AutoscaleTests:
+ options = {"autoscale": True}
+
+ test_bug_6139 = LinprogCommonTests.test_bug_6139
+ test_bug_6690 = LinprogCommonTests.test_bug_6690
+ test_bug_7237 = LinprogCommonTests.test_bug_7237
+
+
+class TestAutoscaleIP(AutoscaleTests):
+ method = "interior-point"
+
+ def test_bug_6139(self):
+ self.options['tol'] = 1e-10
+ return AutoscaleTests.test_bug_6139(self)
+
+
+class TestAutoscaleSimplex(AutoscaleTests):
+ method = "simplex"
+
+
+class TestAutoscaleRS(AutoscaleTests):
+ method = "revised simplex"
+
+ def test_nontrivial_problem_with_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_bad_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bad_guess = [1, 2, 3, .5]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=bad_guess)
+ assert_equal(res.status, 6)
+
+
+###########################
+# Redundancy Removal Tests#
+###########################
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class RRTests:
+ method = "interior-point"
+ LCT = LinprogCommonTests
+ # these are a few of the existing tests that have redundancy
+ test_RR_infeasibility = LCT.test_remove_redundancy_infeasibility
+ test_bug_10349 = LCT.test_bug_10349
+ test_bug_7044 = LCT.test_bug_7044
+ test_NFLC = LCT.test_network_flow_limited_capacity
+ test_enzo_example_b = LCT.test_enzo_example_b
+
+
+class TestRRSVD(RRTests):
+ options = {"rr_method": "SVD"}
+
+
+class TestRRPivot(RRTests):
+ options = {"rr_method": "pivot"}
+
+
+class TestRRID(RRTests):
+ options = {"rr_method": "ID"}
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_common.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..650deedce88b6babd8a3f2b62a5839f1a6cb966c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_common.py
@@ -0,0 +1,297 @@
+from numpy.testing import assert_, assert_allclose, assert_equal
+from pytest import raises as assert_raises
+import numpy as np
+
+from scipy.optimize._lsq.common import (
+ step_size_to_bound, find_active_constraints, make_strictly_feasible,
+ CL_scaling_vector, intersect_trust_region, build_quadratic_1d,
+ minimize_quadratic_1d, evaluate_quadratic, reflective_transformation,
+ left_multiplied_operator, right_multiplied_operator)
+
+
+class TestBounds:
+ def test_step_size_to_bounds(self):
+ lb = np.array([-1.0, 2.5, 10.0])
+ ub = np.array([1.0, 5.0, 100.0])
+ x = np.array([0.0, 2.5, 12.0])
+
+ s = np.array([0.1, 0.0, 0.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, 10)
+ assert_equal(hits, [1, 0, 0])
+
+ s = np.array([0.01, 0.05, -1.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, 2)
+ assert_equal(hits, [0, 0, -1])
+
+ s = np.array([10.0, -0.0001, 100.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, np.array(-0))
+ assert_equal(hits, [0, -1, 0])
+
+ s = np.array([1.0, 0.5, -2.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, 1.0)
+ assert_equal(hits, [1, 0, -1])
+
+ s = np.zeros(3)
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, np.inf)
+ assert_equal(hits, [0, 0, 0])
+
+ def test_find_active_constraints(self):
+ lb = np.array([0.0, -10.0, 1.0])
+ ub = np.array([1.0, 0.0, 100.0])
+
+ x = np.array([0.5, -5.0, 2.0])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [0, 0, 0])
+
+ x = np.array([0.0, 0.0, 10.0])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [-1, 1, 0])
+
+ active = find_active_constraints(x, lb, ub, rtol=0)
+ assert_equal(active, [-1, 1, 0])
+
+ x = np.array([1e-9, -1e-8, 100 - 1e-9])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [0, 0, 1])
+
+ active = find_active_constraints(x, lb, ub, rtol=1.5e-9)
+ assert_equal(active, [-1, 0, 1])
+
+ lb = np.array([1.0, -np.inf, -np.inf])
+ ub = np.array([np.inf, 10.0, np.inf])
+
+ x = np.ones(3)
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [-1, 0, 0])
+
+ # Handles out-of-bound cases.
+ x = np.array([0.0, 11.0, 0.0])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [-1, 1, 0])
+
+ active = find_active_constraints(x, lb, ub, rtol=0)
+ assert_equal(active, [-1, 1, 0])
+
+ def test_make_strictly_feasible(self):
+ lb = np.array([-0.5, -0.8, 2.0])
+ ub = np.array([0.8, 1.0, 3.0])
+
+ x = np.array([-0.5, 0.0, 2 + 1e-10])
+
+ x_new = make_strictly_feasible(x, lb, ub, rstep=0)
+ assert_(x_new[0] > -0.5)
+ assert_equal(x_new[1:], x[1:])
+
+ x_new = make_strictly_feasible(x, lb, ub, rstep=1e-4)
+ assert_equal(x_new, [-0.5 + 1e-4, 0.0, 2 * (1 + 1e-4)])
+
+ x = np.array([-0.5, -1, 3.1])
+ x_new = make_strictly_feasible(x, lb, ub)
+ assert_(np.all((x_new >= lb) & (x_new <= ub)))
+
+ x_new = make_strictly_feasible(x, lb, ub, rstep=0)
+ assert_(np.all((x_new >= lb) & (x_new <= ub)))
+
+ lb = np.array([-1, 100.0])
+ ub = np.array([1, 100.0 + 1e-10])
+ x = np.array([0, 100.0])
+ x_new = make_strictly_feasible(x, lb, ub, rstep=1e-8)
+ assert_equal(x_new, [0, 100.0 + 0.5e-10])
+
+ def test_scaling_vector(self):
+ lb = np.array([-np.inf, -5.0, 1.0, -np.inf])
+ ub = np.array([1.0, np.inf, 10.0, np.inf])
+ x = np.array([0.5, 2.0, 5.0, 0.0])
+ g = np.array([1.0, 0.1, -10.0, 0.0])
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+ assert_equal(v, [1.0, 7.0, 5.0, 1.0])
+ assert_equal(dv, [0.0, 1.0, -1.0, 0.0])
+
+
+class TestQuadraticFunction:
+ def setup_method(self):
+ self.J = np.array([
+ [0.1, 0.2],
+ [-1.0, 1.0],
+ [0.5, 0.2]])
+ self.g = np.array([0.8, -2.0])
+ self.diag = np.array([1.0, 2.0])
+
+ def test_build_quadratic_1d(self):
+ s = np.zeros(2)
+ a, b = build_quadratic_1d(self.J, self.g, s)
+ assert_equal(a, 0)
+ assert_equal(b, 0)
+
+ a, b = build_quadratic_1d(self.J, self.g, s, diag=self.diag)
+ assert_equal(a, 0)
+ assert_equal(b, 0)
+
+ s = np.array([1.0, -1.0])
+ a, b = build_quadratic_1d(self.J, self.g, s)
+ assert_equal(a, 2.05)
+ assert_equal(b, 2.8)
+
+ a, b = build_quadratic_1d(self.J, self.g, s, diag=self.diag)
+ assert_equal(a, 3.55)
+ assert_equal(b, 2.8)
+
+ s0 = np.array([0.5, 0.5])
+ a, b, c = build_quadratic_1d(self.J, self.g, s, diag=self.diag, s0=s0)
+ assert_equal(a, 3.55)
+ assert_allclose(b, 2.39)
+ assert_allclose(c, -0.1525)
+
+ def test_minimize_quadratic_1d(self):
+ a = 5
+ b = -1
+
+ t, y = minimize_quadratic_1d(a, b, 1, 2)
+ assert_equal(t, 1)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -2, -1)
+ assert_equal(t, -1)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -1, 1)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
+
+ c = 10
+ t, y = minimize_quadratic_1d(a, b, -1, 1, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t**2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, 0, np.inf, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, 0, c=c)
+ assert_equal(t, 0)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ a = -1
+ b = 0.2
+ t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf)
+ assert_equal(y, -np.inf)
+
+ t, y = minimize_quadratic_1d(a, b, 0, np.inf)
+ assert_equal(t, np.inf)
+ assert_equal(y, -np.inf)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, 0)
+ assert_equal(t, -np.inf)
+ assert_equal(y, -np.inf)
+
+ def test_evaluate_quadratic(self):
+ s = np.array([1.0, -1.0])
+
+ value = evaluate_quadratic(self.J, self.g, s)
+ assert_equal(value, 4.85)
+
+ value = evaluate_quadratic(self.J, self.g, s, diag=self.diag)
+ assert_equal(value, 6.35)
+
+ s = np.array([[1.0, -1.0],
+ [1.0, 1.0],
+ [0.0, 0.0]])
+
+ values = evaluate_quadratic(self.J, self.g, s)
+ assert_allclose(values, [4.85, -0.91, 0.0])
+
+ values = evaluate_quadratic(self.J, self.g, s, diag=self.diag)
+ assert_allclose(values, [6.35, 0.59, 0.0])
+
+
+class TestTrustRegion:
+ def test_intersect(self):
+ Delta = 1.0
+
+ x = np.zeros(3)
+ s = np.array([1.0, 0.0, 0.0])
+ t_neg, t_pos = intersect_trust_region(x, s, Delta)
+ assert_equal(t_neg, -1)
+ assert_equal(t_pos, 1)
+
+ s = np.array([-1.0, 1.0, -1.0])
+ t_neg, t_pos = intersect_trust_region(x, s, Delta)
+ assert_allclose(t_neg, -3**-0.5)
+ assert_allclose(t_pos, 3**-0.5)
+
+ x = np.array([0.5, -0.5, 0])
+ s = np.array([0, 0, 1.0])
+ t_neg, t_pos = intersect_trust_region(x, s, Delta)
+ assert_allclose(t_neg, -2**-0.5)
+ assert_allclose(t_pos, 2**-0.5)
+
+ x = np.ones(3)
+ assert_raises(ValueError, intersect_trust_region, x, s, Delta)
+
+ x = np.zeros(3)
+ s = np.zeros(3)
+ assert_raises(ValueError, intersect_trust_region, x, s, Delta)
+
+
+def test_reflective_transformation():
+ lb = np.array([-1, -2], dtype=float)
+ ub = np.array([5, 3], dtype=float)
+
+ y = np.array([0, 0])
+ x, g = reflective_transformation(y, lb, ub)
+ assert_equal(x, y)
+ assert_equal(g, np.ones(2))
+
+ y = np.array([-4, 4], dtype=float)
+
+ x, g = reflective_transformation(y, lb, np.array([np.inf, np.inf]))
+ assert_equal(x, [2, 4])
+ assert_equal(g, [-1, 1])
+
+ x, g = reflective_transformation(y, np.array([-np.inf, -np.inf]), ub)
+ assert_equal(x, [-4, 2])
+ assert_equal(g, [1, -1])
+
+ x, g = reflective_transformation(y, lb, ub)
+ assert_equal(x, [2, 2])
+ assert_equal(g, [-1, -1])
+
+ lb = np.array([-np.inf, -2])
+ ub = np.array([5, np.inf])
+ y = np.array([10, 10], dtype=float)
+ x, g = reflective_transformation(y, lb, ub)
+ assert_equal(x, [0, 10])
+ assert_equal(g, [-1, 1])
+
+
+def test_linear_operators():
+ A = np.arange(6).reshape((3, 2))
+
+ d_left = np.array([-1, 2, 5])
+ DA = np.diag(d_left).dot(A)
+ J_left = left_multiplied_operator(A, d_left)
+
+ d_right = np.array([5, 10])
+ AD = A.dot(np.diag(d_right))
+ J_right = right_multiplied_operator(A, d_right)
+
+ x = np.array([-2, 3])
+ X = -2 * np.arange(2, 8).reshape((2, 3))
+ xt = np.array([0, -2, 15])
+
+ assert_allclose(DA.dot(x), J_left.matvec(x))
+ assert_allclose(DA.dot(X), J_left.matmat(X))
+ assert_allclose(DA.T.dot(xt), J_left.rmatvec(xt))
+
+ assert_allclose(AD.dot(x), J_right.matvec(x))
+ assert_allclose(AD.dot(X), J_right.matmat(X))
+ assert_allclose(AD.T.dot(xt), J_right.rmatvec(xt))
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_linear.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cc394a46ab5f8b4339ecd4b72002332f7e1639b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_linear.py
@@ -0,0 +1,290 @@
+import warnings
+
+import pytest
+
+import numpy as np
+from numpy.linalg import lstsq
+from numpy.testing import assert_allclose, assert_equal, assert_
+
+from scipy.sparse import random_array, coo_array
+from scipy.sparse.linalg import aslinearoperator
+from scipy.optimize import lsq_linear
+from scipy.optimize._minimize import Bounds
+
+
+A = np.array([
+ [0.171, -0.057],
+ [-0.049, -0.248],
+ [-0.166, 0.054],
+])
+b = np.array([0.074, 1.014, -0.383])
+
+
+class BaseMixin:
+ def setup_method(self):
+ self.rnd = np.random.default_rng(1092892)
+
+ def test_dense_no_bounds(self):
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, method=self.method, lsq_solver=lsq_solver)
+ assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])
+ assert_allclose(res.x, res.unbounded_sol[0])
+
+ def test_dense_bounds(self):
+ # Solutions for comparison are taken from MATLAB.
+ lb = np.array([-1, -10])
+ ub = np.array([1, 0])
+ unbounded_sol = lstsq(A, b, rcond=-1)[0]
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ lb = np.array([0.0, -np.inf])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, np.inf), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
+ atol=1e-6)
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ lb = np.array([-1, 0])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, np.inf), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([0.448427311733504, 0]),
+ atol=1e-15)
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ ub = np.array([np.inf, -5])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([-0.105560998682388, -5]))
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ ub = np.array([-1, np.inf])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([-1, -4.181102129483254]))
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ lb = np.array([0, -4])
+ ub = np.array([1, 0])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([0.005236663400791, -4]))
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ def test_bounds_variants(self):
+ x = np.array([1, 3])
+ A = self.rnd.uniform(size=(2, 2))
+ b = A@x
+ lb = np.array([1, 1])
+ ub = np.array([2, 2])
+ bounds_old = (lb, ub)
+ bounds_new = Bounds(lb, ub)
+ res_old = lsq_linear(A, b, bounds_old)
+ res_new = lsq_linear(A, b, bounds_new)
+ assert not np.allclose(res_new.x, res_new.unbounded_sol[0])
+ assert_allclose(res_old.x, res_new.x)
+
+ def test_np_matrix(self):
+ # gh-10711
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", PendingDeprecationWarning)
+ A = np.matrix([[20, -4, 0, 2, 3], [10, -2, 1, 0, -1]])
+ k = np.array([20, 15])
+ lsq_linear(A, k)
+
+ def test_dense_rank_deficient(self):
+ A = np.array([[-0.307, -0.184]])
+ b = np.array([0.773])
+ lb = [-0.1, -0.1]
+ ub = [0.1, 0.1]
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, [-0.1, -0.1])
+ assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0])
+
+ A = np.array([
+ [0.334, 0.668],
+ [-0.516, -1.032],
+ [0.192, 0.384],
+ ])
+ b = np.array([-1.436, 0.135, 0.909])
+ lb = [0, -1]
+ ub = [1, -0.5]
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.optimality, 0, atol=1e-11)
+ assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0])
+
+ def test_full_result(self):
+ lb = np.array([0, -4])
+ ub = np.array([1, 0])
+ res = lsq_linear(A, b, (lb, ub), method=self.method)
+
+ assert_allclose(res.x, [0.005236663400791, -4])
+ assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0])
+
+ r = A.dot(res.x) - b
+ assert_allclose(res.cost, 0.5 * np.dot(r, r))
+ assert_allclose(res.fun, r)
+
+ assert_allclose(res.optimality, 0.0, atol=1e-12)
+ assert_equal(res.active_mask, [0, -1])
+ assert_(res.nit < 15)
+ assert_(res.status == 1 or res.status == 3)
+ assert_(isinstance(res.message, str))
+ assert_(res.success)
+
+ # This is a test for issue #9982.
+ def test_almost_singular(self):
+ A = np.array(
+ [[0.8854232310355122, 0.0365312146937765, 0.0365312146836789],
+ [0.3742460132129041, 0.0130523214078376, 0.0130523214077873],
+ [0.9680633871281361, 0.0319366128718639, 0.0319366128718388]])
+
+ b = np.array(
+ [0.0055029366538097, 0.0026677442422208, 0.0066612514782381])
+
+ result = lsq_linear(A, b, method=self.method)
+ assert_(result.cost < 1.1e-8)
+
+ @pytest.mark.xslow
+ def test_large_rank_deficient(self):
+ rng = np.random.default_rng(1290209)
+ n, m = np.sort(rng.integers(2, 1000, size=2))
+ m *= 2 # make m >> n
+ A = 1.0 * rng.integers(-99, 99, size=[m, n])
+ b = 1.0 * rng.integers(-99, 99, size=[m])
+ bounds = 1.0 * np.sort(rng.integers(-99, 99, size=(2, n)), axis=0)
+ bounds[1, :] += 1.0 # ensure up > lb
+
+ # Make the A matrix strongly rank deficient by replicating some columns
+ w = rng.choice(n, n) # Select random columns with duplicates
+ A = A[:, w]
+
+ x_bvls = lsq_linear(A, b, bounds=bounds, method='bvls').x
+ x_trf = lsq_linear(A, b, bounds=bounds, method='trf').x
+
+ cost_bvls = np.sum((A @ x_bvls - b)**2)
+ cost_trf = np.sum((A @ x_trf - b)**2)
+
+ assert_(abs(cost_bvls - cost_trf) < cost_trf*1e-10)
+
+ def test_convergence_small_array(self):
+ A = np.array([[49.0, 41.0, -32.0],
+ [-19.0, -32.0, -8.0],
+ [-13.0, 10.0, 69.0]])
+ b = np.array([-41.0, -90.0, 47.0])
+ bounds = np.array([[31.0, -44.0, 26.0],
+ [54.0, -32.0, 28.0]])
+
+ x_bvls = lsq_linear(A, b, bounds=bounds, method='bvls').x
+ x_trf = lsq_linear(A, b, bounds=bounds, method='trf').x
+
+ cost_bvls = np.sum((A @ x_bvls - b)**2)
+ cost_trf = np.sum((A @ x_trf - b)**2)
+
+ assert_(abs(cost_bvls - cost_trf) < cost_trf*1e-10)
+
+
+class SparseMixin:
+ def test_sparse_and_LinearOperator(self):
+ m = 5000
+ n = 1000
+ rng = np.random.RandomState(0)
+ A = random_array((m, n), random_state=rng)
+ b = rng.randn(m)
+ res = lsq_linear(A, b)
+ assert_allclose(res.optimality, 0, atol=1e-6)
+
+ A = aslinearoperator(A)
+ res = lsq_linear(A, b)
+ assert_allclose(res.optimality, 0, atol=1e-6)
+
+ @pytest.mark.fail_slow(10)
+ def test_sparse_bounds(self):
+ m = 5000
+ n = 1000
+
+ rng = np.random.RandomState(0)
+ A = random_array((m, n), random_state=rng)
+ b = rng.randn(m)
+ lb = rng.randn(n)
+ ub = lb + 1
+ res = lsq_linear(A, b, (lb, ub))
+ assert_allclose(res.optimality, 0.0, atol=1e-6)
+
+ res = lsq_linear(A, b, (lb, ub), lsmr_tol=1e-13,
+ lsmr_maxiter=1500)
+ assert_allclose(res.optimality, 0.0, atol=1e-6)
+
+ res = lsq_linear(A, b, (lb, ub), lsmr_tol='auto')
+ assert_allclose(res.optimality, 0.0, atol=1e-6)
+
+ def test_sparse_ill_conditioned(self):
+ # Sparse matrix with condition number of ~4 million
+ data = np.array([1., 1., 1., 1. + 1e-6, 1.])
+ row = np.array([0, 0, 1, 2, 2])
+ col = np.array([0, 2, 1, 0, 2])
+ A = coo_array((data, (row, col)), shape=(3, 3))
+
+ # Get the exact solution
+ exact_sol = lsq_linear(A.toarray(), b, lsq_solver='exact')
+
+ # Default lsmr arguments should not fully converge the solution
+ default_lsmr_sol = lsq_linear(A, b, lsq_solver='lsmr')
+ with pytest.raises(AssertionError):
+ assert_allclose(exact_sol.x, default_lsmr_sol.x)
+
+ # By increasing the maximum lsmr iters, it will converge
+ conv_lsmr = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=10)
+ assert_allclose(exact_sol.x, conv_lsmr.x)
+
+
+class TestTRF(BaseMixin, SparseMixin):
+ method = 'trf'
+ lsq_solvers = ['exact', 'lsmr']
+
+
+class TestBVLS(BaseMixin):
+ method = 'bvls'
+ lsq_solvers = ['exact']
+
+
+class TestErrorChecking:
+ def test_option_lsmr_tol(self):
+ # Should work with a positive float, string equal to 'auto', or None
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=1e-2)
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol='auto')
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=None)
+
+ # Should raise error with negative float, strings
+ # other than 'auto', and integers
+ err_message = "`lsmr_tol` must be None, 'auto', or positive float."
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=-0.1)
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol='foo')
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=1)
+
+ def test_option_lsmr_maxiter(self):
+ # Should work with positive integers or None
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=1)
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=None)
+
+ # Should raise error with 0 or negative max iter
+ err_message = "`lsmr_maxiter` must be None or positive integer."
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=0)
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=-1)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_milp.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_milp.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fdd5ae213d2aa072269aa890a4d934044665074
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_milp.py
@@ -0,0 +1,477 @@
+"""
+Unit test for Mixed Integer Linear Programming
+"""
+import re
+import sys
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal
+import pytest
+
+from .test_linprog import magic_square
+from scipy.optimize import milp, Bounds, LinearConstraint
+from scipy import sparse
+
+
+_IS_32BIT = (sys.maxsize < 2**32)
+
+def test_milp_iv():
+
+ message = "`c` must be a dense array"
+ with pytest.raises(ValueError, match=message):
+ milp(sparse.coo_array([0, 0]))
+
+ message = "`c` must be a one-dimensional array of finite numbers with"
+ with pytest.raises(ValueError, match=message):
+ milp(np.zeros((3, 4)))
+ with pytest.raises(ValueError, match=message):
+ milp([])
+ with pytest.raises(ValueError, match=message):
+ milp(None)
+
+ message = "`bounds` must be convertible into an instance of..."
+ with pytest.raises(ValueError, match=message):
+ milp(1, bounds=10)
+
+ message = "`constraints` (or each element within `constraints`) must be"
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(1, constraints=10)
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(np.zeros(3), constraints=([[1, 2, 3]], [2, 3], [2, 3]))
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(np.zeros(2), constraints=([[1, 2]], [2], sparse.coo_array([2])))
+
+ message = "The shape of `A` must be (len(b_l), len(c))."
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(np.zeros(3), constraints=([[1, 2]], [2], [2]))
+
+ message = "`integrality` must be a dense array"
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2], integrality=sparse.coo_array([1, 2]))
+
+ message = ("`integrality` must contain integers 0-3 and be broadcastable "
+ "to `c.shape`.")
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], integrality=[1, 2])
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], integrality=[1, 5, 3])
+
+ message = "Lower and upper bounds must be dense arrays."
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2], sparse.coo_array([3, 4])))
+
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2], [3, 4, 5]))
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2, 3], [4, 5]))
+
+ message = "`bounds.lb` and `bounds.ub` must contain reals and..."
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2], [3, 4]))
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2, 3], ["3+4", 4, 5]))
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2, 3], [set(), 4, 5]))
+
+
+@pytest.mark.xfail(run=False,
+ reason="Needs to be fixed in `_highs_wrapper`")
+def test_milp_options(capsys):
+ # run=False now because of gh-16347
+ message = "Unrecognized options detected: {'ekki'}..."
+ options = {'ekki': True}
+ with pytest.warns(RuntimeWarning, match=message):
+ milp(1, options=options)
+
+ A, b, c, numbers, M = magic_square(3)
+ options = {"disp": True, "presolve": False, "time_limit": 0.05}
+ res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1,
+ options=options)
+
+ captured = capsys.readouterr()
+ assert "Presolve is switched off" in captured.out
+ assert "Time Limit Reached" in captured.out
+ assert not res.success
+
+
+def test_result():
+ A, b, c, numbers, M = magic_square(3)
+ res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1)
+ assert res.status == 0
+ assert res.success
+ msg = "Optimization terminated successfully. (HiGHS Status 7:"
+ assert res.message.startswith(msg)
+ assert isinstance(res.x, np.ndarray)
+ assert isinstance(res.fun, float)
+ assert isinstance(res.mip_node_count, int)
+ assert isinstance(res.mip_dual_bound, float)
+ assert isinstance(res.mip_gap, float)
+
+ A, b, c, numbers, M = magic_square(6)
+ res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1,
+ options={'time_limit': 0.05})
+ assert res.status == 1
+ assert not res.success
+ msg = "Time limit reached. (HiGHS Status 13:"
+ assert res.message.startswith(msg)
+ assert (res.fun is res.mip_dual_bound is res.mip_gap
+ is res.mip_node_count is res.x is None)
+
+ res = milp(1, bounds=(1, -1))
+ assert res.status == 2
+ assert not res.success
+ msg = "The problem is infeasible. (HiGHS Status 8:"
+ assert res.message.startswith(msg)
+ assert (res.fun is res.mip_dual_bound is res.mip_gap
+ is res.mip_node_count is res.x is None)
+
+ res = milp(-1)
+ assert res.status == 3
+ assert not res.success
+ msg = "The problem is unbounded. (HiGHS Status 10:"
+ assert res.message.startswith(msg)
+ assert (res.fun is res.mip_dual_bound is res.mip_gap
+ is res.mip_node_count is res.x is None)
+
+
+def test_milp_optional_args():
+ # check that arguments other than `c` are indeed optional
+ res = milp(1)
+ assert res.fun == 0
+ assert_array_equal(res.x, [0])
+
+
+def test_milp_1():
+ # solve magic square problem
+ n = 3
+ A, b, c, numbers, M = magic_square(n)
+ A = sparse.csc_array(A) # confirm that sparse arrays are accepted
+ res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1)
+
+ # check that solution is a magic square
+ x = np.round(res.x)
+ s = (numbers.flatten() * x).reshape(n**2, n, n)
+ square = np.sum(s, axis=0)
+ np.testing.assert_allclose(square.sum(axis=0), M)
+ np.testing.assert_allclose(square.sum(axis=1), M)
+ np.testing.assert_allclose(np.diag(square).sum(), M)
+ np.testing.assert_allclose(np.diag(square[:, ::-1]).sum(), M)
+
+
+def test_milp_2():
+ # solve MIP with inequality constraints and all integer constraints
+ # source: slide 5,
+ # https://www.cs.upc.edu/~erodri/webpage/cps/theory/lp/milp/slides.pdf
+ # also check that `milp` accepts all valid ways of specifying constraints
+ c = -np.ones(2)
+ A = [[-2, 2], [-8, 10]]
+ b_l = [1, -np.inf]
+ b_u = [np.inf, 13]
+ linear_constraint = LinearConstraint(A, b_l, b_u)
+
+ # solve original problem
+ res1 = milp(c=c, constraints=(A, b_l, b_u), integrality=True)
+ res2 = milp(c=c, constraints=linear_constraint, integrality=True)
+ res3 = milp(c=c, constraints=[(A, b_l, b_u)], integrality=True)
+ res4 = milp(c=c, constraints=[linear_constraint], integrality=True)
+ res5 = milp(c=c, integrality=True,
+ constraints=[(A[:1], b_l[:1], b_u[:1]),
+ (A[1:], b_l[1:], b_u[1:])])
+ res6 = milp(c=c, integrality=True,
+ constraints=[LinearConstraint(A[:1], b_l[:1], b_u[:1]),
+ LinearConstraint(A[1:], b_l[1:], b_u[1:])])
+ res7 = milp(c=c, integrality=True,
+ constraints=[(A[:1], b_l[:1], b_u[:1]),
+ LinearConstraint(A[1:], b_l[1:], b_u[1:])])
+ xs = np.array([res1.x, res2.x, res3.x, res4.x, res5.x, res6.x, res7.x])
+ funs = np.array([res1.fun, res2.fun, res3.fun,
+ res4.fun, res5.fun, res6.fun, res7.fun])
+ np.testing.assert_allclose(xs, np.broadcast_to([1, 2], xs.shape))
+ np.testing.assert_allclose(funs, -3)
+
+ # solve relaxed problem
+ res = milp(c=c, constraints=(A, b_l, b_u))
+ np.testing.assert_allclose(res.x, [4, 4.5])
+ np.testing.assert_allclose(res.fun, -8.5)
+
+
+def test_milp_3():
+ # solve MIP with inequality constraints and all integer constraints
+ # source: https://en.wikipedia.org/wiki/Integer_programming#Example
+ c = [0, -1]
+ A = [[-1, 1], [3, 2], [2, 3]]
+ b_u = [1, 12, 12]
+ b_l = np.full_like(b_u, -np.inf, dtype=np.float64)
+ constraints = LinearConstraint(A, b_l, b_u)
+
+ integrality = np.ones_like(c)
+
+ # solve original problem
+ res = milp(c=c, constraints=constraints, integrality=integrality)
+ assert_allclose(res.fun, -2)
+ # two optimal solutions possible, just need one of them
+ assert np.allclose(res.x, [1, 2]) or np.allclose(res.x, [2, 2])
+
+ # solve relaxed problem
+ res = milp(c=c, constraints=constraints)
+ assert_allclose(res.fun, -2.8)
+ assert_allclose(res.x, [1.8, 2.8])
+
+
+def test_milp_4():
+ # solve MIP with inequality constraints and only one integer constraint
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ c = [8, 1]
+ integrality = [0, 1]
+ A = [[1, 2], [-4, -1], [2, 1]]
+ b_l = [-14, -np.inf, -np.inf]
+ b_u = [np.inf, -33, 20]
+ constraints = LinearConstraint(A, b_l, b_u)
+ bounds = Bounds(-np.inf, np.inf)
+
+ res = milp(c, integrality=integrality, bounds=bounds,
+ constraints=constraints)
+ assert_allclose(res.fun, 59)
+ assert_allclose(res.x, [6.5, 7])
+
+
+def test_milp_5():
+ # solve MIP with inequality and equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ c = [-3, -2, -1]
+ integrality = [0, 0, 1]
+ lb = [0, 0, 0]
+ ub = [np.inf, np.inf, 1]
+ bounds = Bounds(lb, ub)
+ A = [[1, 1, 1], [4, 2, 1]]
+ b_l = [-np.inf, 12]
+ b_u = [7, 12]
+ constraints = LinearConstraint(A, b_l, b_u)
+
+ res = milp(c, integrality=integrality, bounds=bounds,
+ constraints=constraints)
+ # there are multiple solutions
+ assert_allclose(res.fun, -12)
+
+
+@pytest.mark.xslow
+def test_milp_6():
+ # solve a larger MIP with only equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ integrality = 1
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ res = milp(c=c, constraints=(A_eq, b_eq, b_eq), integrality=integrality)
+
+ np.testing.assert_allclose(res.fun, 1854)
+
+
+def test_infeasible_prob_16609():
+ # Ensure presolve does not mark trivially infeasible problems
+ # as Optimal -- see gh-16609
+ c = [1.0, 0.0]
+ integrality = [0, 1]
+
+ lb = [0, -np.inf]
+ ub = [np.inf, np.inf]
+ bounds = Bounds(lb, ub)
+
+ A_eq = [[0.0, 1.0]]
+ b_eq = [0.5]
+ constraints = LinearConstraint(A_eq, b_eq, b_eq)
+
+ res = milp(c, integrality=integrality, bounds=bounds,
+ constraints=constraints)
+ np.testing.assert_equal(res.status, 2)
+
+
+_msg_time = "Time limit reached. (HiGHS Status 13:"
+_msg_iter = "Iteration limit reached. (HiGHS Status 14:"
+
+# See https://github.com/scipy/scipy/pull/19255#issuecomment-1778438888
+@pytest.mark.xfail(reason="Often buggy, revisit with callbacks, gh-19255")
+@pytest.mark.skipif(np.intp(0).itemsize < 8,
+ reason="Unhandled 32-bit GCC FP bug")
+@pytest.mark.slow
+@pytest.mark.parametrize(["options", "msg"], [({"time_limit": 0.1}, _msg_time),
+ ({"node_limit": 1}, _msg_iter)])
+def test_milp_timeout_16545(options, msg):
+ # Ensure solution is not thrown away if MILP solver times out
+ # -- see gh-16545
+ rng = np.random.default_rng(5123833489170494244)
+ A = rng.integers(0, 5, size=(100, 100))
+ b_lb = np.full(100, fill_value=-np.inf)
+ b_ub = np.full(100, fill_value=25)
+ constraints = LinearConstraint(A, b_lb, b_ub)
+ variable_lb = np.zeros(100)
+ variable_ub = np.ones(100)
+ variable_bounds = Bounds(variable_lb, variable_ub)
+ integrality = np.ones(100)
+ c_vector = -np.ones(100)
+ res = milp(
+ c_vector,
+ integrality=integrality,
+ bounds=variable_bounds,
+ constraints=constraints,
+ options=options,
+ )
+
+ assert res.message.startswith(msg)
+ assert res["x"] is not None
+
+ # ensure solution is feasible
+ x = res["x"]
+ tol = 1e-8 # sometimes needed due to finite numerical precision
+ assert np.all(b_lb - tol <= A @ x) and np.all(A @ x <= b_ub + tol)
+ assert np.all(variable_lb - tol <= x) and np.all(x <= variable_ub + tol)
+ assert np.allclose(x, np.round(x))
+
+
+def test_three_constraints_16878():
+ # `milp` failed when exactly three constraints were passed
+ # Ensure that this is no longer the case.
+ rng = np.random.default_rng(5123833489170494244)
+ A = rng.integers(0, 5, size=(6, 6))
+ bl = np.full(6, fill_value=-np.inf)
+ bu = np.full(6, fill_value=10)
+ constraints = [LinearConstraint(A[:2], bl[:2], bu[:2]),
+ LinearConstraint(A[2:4], bl[2:4], bu[2:4]),
+ LinearConstraint(A[4:], bl[4:], bu[4:])]
+ constraints2 = [(A[:2], bl[:2], bu[:2]),
+ (A[2:4], bl[2:4], bu[2:4]),
+ (A[4:], bl[4:], bu[4:])]
+ lb = np.zeros(6)
+ ub = np.ones(6)
+ variable_bounds = Bounds(lb, ub)
+ c = -np.ones(6)
+ res1 = milp(c, bounds=variable_bounds, constraints=constraints)
+ res2 = milp(c, bounds=variable_bounds, constraints=constraints2)
+ ref = milp(c, bounds=variable_bounds, constraints=(A, bl, bu))
+ assert res1.success and res2.success
+ assert_allclose(res1.x, ref.x)
+ assert_allclose(res2.x, ref.x)
+
+
+@pytest.mark.xslow
+def test_mip_rel_gap_passdown():
+ # Solve problem with decreasing mip_gap to make sure mip_rel_gap decreases
+ # Adapted from test_linprog::TestLinprogHiGHSMIP::test_mip_rel_gap_passdown
+ # MIP taken from test_mip_6 above
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ mip_rel_gaps = [0.25, 0.01, 0.001]
+ sol_mip_gaps = []
+ for mip_rel_gap in mip_rel_gaps:
+ res = milp(c=c, bounds=(0, np.inf), constraints=(A_eq, b_eq, b_eq),
+ integrality=True, options={"mip_rel_gap": mip_rel_gap})
+ # assert that the solution actually has mip_gap lower than the
+ # required mip_rel_gap supplied
+ assert res.mip_gap <= mip_rel_gap
+ # check that `res.mip_gap` is as defined in the documentation
+ assert res.mip_gap == (res.fun - res.mip_dual_bound)/res.fun
+ sol_mip_gaps.append(res.mip_gap)
+
+ # make sure that the mip_rel_gap parameter is actually doing something
+ # check that differences between solution gaps are declining
+ # monotonically with the mip_rel_gap parameter.
+ assert np.all(np.diff(sol_mip_gaps) < 0)
+
+@pytest.mark.xfail(reason='Upstream / Wrapper issue, see gh-20116')
+def test_large_numbers_gh20116():
+ h = 10 ** 12
+ A = np.array([[100.4534, h], [100.4534, -h]])
+ b = np.array([h, 0])
+ constraints = LinearConstraint(A=A, ub=b)
+ bounds = Bounds([0, 0], [1, 1])
+ c = np.array([0, 0])
+ res = milp(c=c, constraints=constraints, bounds=bounds, integrality=1)
+ assert res.status == 0
+ assert np.all(A @ res.x < b)
+
+
+def test_presolve_gh18907():
+ from scipy.optimize import milp
+ import numpy as np
+ inf = np.inf
+
+ # set up problem
+ c = np.array([-0.85850509, -0.82892676, -0.80026454, -0.63015535, -0.5099006,
+ -0.50077193, -0.4894404, -0.47285865, -0.39867774, -0.38069646,
+ -0.36733012, -0.36733012, -0.35820411, -0.31576141, -0.20626091,
+ -0.12466144, -0.10679516, -0.1061887, -0.1061887, -0.1061887,
+ -0., -0., -0., -0., 0., 0., 0., 0.])
+
+ A = np.array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 1., 0., 0., 0., 0., 0., 1., 0., 0., 0., -25., -0., -0., -0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ -1., 0., 0., 0., 0., 0., -1., 0., 0., 0., 2., 0., 0., 0.],
+ [0., 0., 0., 0., 1., 1., 1., 1., 0., 1., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0., 0., 0., 0., -0., -25., -0., -0.],
+ [0., 0., 0., 0., -1., -1., -1., -1., 0., -1., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 2., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 1., 1., 1., 0., 0., 0., 0., -0., -0., -25., -0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., -1., -1., -1., 0., 0., 0., 0., 0., 0., 2., 0.],
+ [1., 1., 1., 1., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1., 0.,
+ 1., 1., 0., 0., 0., 0., 1., 1., 1., -0., -0., -0., -25.],
+ [-1., -1., -1., -1., 0., 0., 0., 0., -1., 0., -1., -1., -1., -1.,
+ 0., -1., -1., 0., 0., 0., 0., -1., -1., -1., 0., 0., 0., 2.]])
+ bl = np.array([-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf])
+ bu = np.array([100., 0., 0., 0., 0., 0., 0., 0., 0.])
+ constraints = LinearConstraint(A, bl, bu)
+ integrality = 1
+ bounds = (0, 1)
+ r1 = milp(c=c, constraints=constraints, integrality=integrality, bounds=bounds,
+ options={'presolve': True})
+ r2 = milp(c=c, constraints=constraints, integrality=integrality, bounds=bounds,
+ options={'presolve': False})
+ assert r1.status == r2.status
+ assert_allclose(r1.fun, r2.fun)
+
+ # another example from the same issue
+ bounds = Bounds(lb=0, ub=1)
+ integrality = [1, 1, 0, 0]
+ c = [10, 9.52380952, -1000, -952.38095238]
+ A = [[1, 1, 0, 0], [0, 0, 1, 1], [200, 0, 0, 0], [0, 200, 0, 0],
+ [0, 0, 2000, 0], [0, 0, 0, 2000], [-1, 0, 1, 0], [-1, -1, 0, 1]]
+ ub = [1, 1, 200, 200, 1000, 1000, 0, 0]
+ constraints = LinearConstraint(A, ub=ub)
+ r1 = milp(c=c, constraints=constraints, bounds=bounds,
+ integrality=integrality, options={"presolve": False})
+ r2 = milp(c=c, constraints=constraints, bounds=bounds,
+ integrality=integrality, options={"presolve": False})
+ assert r1.status == r2.status
+ assert_allclose(r1.x, r2.x)
+
+def test_regression_gh24141():
+ c = np.ones(8, dtype=np.int64)
+ integrality = c.copy()
+
+ b = np.asarray([42, 252, 277, 41, 222, 48], dtype=np.int64)
+ a = np.asarray([
+ [0, 1, 1, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 0, 1],
+ [0, 1, 0, 1, 1, 1, 0, 0],
+ [0, 1, 0, 0, 1, 1, 0, 1],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ ], dtype=np.int64)
+
+ res = milp(c, integrality=integrality, constraints=(a, b, b))
+
+ assert res.success
+ assert_allclose(a @ res.x, b)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_minimize_constrained.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_minimize_constrained.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f806280fdc6109154c2e147e2d282a8a0bc5723
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_minimize_constrained.py
@@ -0,0 +1,996 @@
+import warnings
+
+import numpy as np
+import pytest
+from scipy.linalg import block_diag
+from scipy.sparse import csc_array
+from numpy.testing import (assert_array_almost_equal,
+ assert_array_less, assert_)
+from scipy.optimize import (NonlinearConstraint,
+ LinearConstraint,
+ Bounds,
+ minimize,
+ BFGS,
+ SR1,
+ rosen)
+
+
+class Maratos:
+ """Problem 15.4 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+ Subject to: x[0]**2 + x[1]**2 - 1 = 0
+ """
+
+ def __init__(self, degrees=60, constr_jac=None, constr_hess=None):
+ rads = degrees/180*np.pi
+ self.x0 = [np.cos(rads), np.sin(rads)]
+ self.x_opt = np.array([1.0, 0.0])
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = None
+
+ def fun(self, x):
+ return 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+
+ def grad(self, x):
+ return np.array([4*x[0]-1, 4*x[1]])
+
+ def hess(self, x):
+ return 4*np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return x[0]**2 + x[1]**2
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[2*x[0], 2*x[1]]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.eye(2)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 1, 1, jac, hess)
+
+
+class MaratosTestArgs:
+ """Problem 15.4 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+ Subject to: x[0]**2 + x[1]**2 - 1 = 0
+ """
+
+ def __init__(self, a, b, degrees=60, constr_jac=None, constr_hess=None):
+ rads = degrees/180*np.pi
+ self.x0 = [np.cos(rads), np.sin(rads)]
+ self.x_opt = np.array([1.0, 0.0])
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.a = a
+ self.b = b
+ self.bounds = None
+
+ def _test_args(self, a, b):
+ if self.a != a or self.b != b:
+ raise ValueError()
+
+ def fun(self, x, a, b):
+ self._test_args(a, b)
+ return 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+
+ def grad(self, x, a, b):
+ self._test_args(a, b)
+ return np.array([4*x[0]-1, 4*x[1]])
+
+ def hess(self, x, a, b):
+ self._test_args(a, b)
+ return 4*np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return x[0]**2 + x[1]**2
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[4*x[0], 4*x[1]]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.eye(2)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 1, 1, jac, hess)
+
+
+class MaratosGradInFunc:
+ """Problem 15.4 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+ Subject to: x[0]**2 + x[1]**2 - 1 = 0
+ """
+
+ def __init__(self, degrees=60, constr_jac=None, constr_hess=None):
+ rads = degrees/180*np.pi
+ self.x0 = [np.cos(rads), np.sin(rads)]
+ self.x_opt = np.array([1.0, 0.0])
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = None
+
+ def fun(self, x):
+ return (2*(x[0]**2 + x[1]**2 - 1) - x[0],
+ np.array([4*x[0]-1, 4*x[1]]))
+
+ @property
+ def grad(self):
+ return True
+
+ def hess(self, x):
+ return 4*np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return x[0]**2 + x[1]**2
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[4*x[0], 4*x[1]]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.eye(2)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 1, 1, jac, hess)
+
+
+class HyperbolicIneq:
+ """Problem 15.1 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 1/2*(x[0] - 2)**2 + 1/2*(x[1] - 1/2)**2
+ Subject to: 1/(x[0] + 1) - x[1] >= 1/4
+ x[0] >= 0
+ x[1] >= 0
+ """
+ def __init__(self, constr_jac=None, constr_hess=None):
+ self.x0 = [0, 0]
+ self.x_opt = [1.952823, 0.088659]
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = Bounds(0, np.inf)
+
+ def fun(self, x):
+ return 1/2*(x[0] - 2)**2 + 1/2*(x[1] - 1/2)**2
+
+ def grad(self, x):
+ return [x[0] - 2, x[1] - 1/2]
+
+ def hess(self, x):
+ return np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return 1/(x[0] + 1) - x[1]
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[-1/(x[0] + 1)**2, -1]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.array([[1/(x[0] + 1)**3, 0],
+ [0, 0]])
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 0.25, np.inf, jac, hess)
+
+
+class Rosenbrock:
+ """Rosenbrock function.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
+ """
+
+ def __init__(self, n=2, random_state=0):
+ rng = np.random.RandomState(random_state)
+ self.x0 = rng.uniform(-1, 1, n)
+ self.x_opt = np.ones(n)
+ self.bounds = None
+
+ def fun(self, x):
+ x = np.asarray(x)
+ r = np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
+ axis=0)
+ return r
+
+ def grad(self, x):
+ x = np.asarray(x)
+ xm = x[1:-1]
+ xm_m1 = x[:-2]
+ xm_p1 = x[2:]
+ der = np.zeros_like(x)
+ der[1:-1] = (200 * (xm - xm_m1**2) -
+ 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
+ der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
+ der[-1] = 200 * (x[-1] - x[-2]**2)
+ return der
+
+ def hess(self, x):
+ x = np.atleast_1d(x)
+ H = np.diag(-400 * x[:-1], 1) - np.diag(400 * x[:-1], -1)
+ diagonal = np.zeros(len(x), dtype=x.dtype)
+ diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2
+ diagonal[-1] = 200
+ diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:]
+ H = H + np.diag(diagonal)
+ return H
+
+ @property
+ def constr(self):
+ return ()
+
+
+class IneqRosenbrock(Rosenbrock):
+ """Rosenbrock subject to inequality constraints.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2)
+ subject to: x[0] + 2 x[1] <= 1
+
+ Taken from matlab ``fmincon`` documentation.
+ """
+ def __init__(self, random_state=0):
+ Rosenbrock.__init__(self, 2, random_state)
+ self.x0 = [-1, -0.5]
+ self.x_opt = [0.5022, 0.2489]
+ self.bounds = None
+
+ @property
+ def constr(self):
+ A = [[1, 2]]
+ b = 1
+ return LinearConstraint(A, -np.inf, b)
+
+
+class BoundedRosenbrock(Rosenbrock):
+ """Rosenbrock subject to inequality constraints.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2)
+ subject to: -2 <= x[0] <= 0
+ 0 <= x[1] <= 2
+
+ Taken from matlab ``fmincon`` documentation.
+ """
+ def __init__(self, random_state=0):
+ Rosenbrock.__init__(self, 2, random_state)
+ self.x0 = [-0.2, 0.2]
+ self.x_opt = None
+ self.bounds = Bounds([-2, 0], [0, 2])
+
+
+class EqIneqRosenbrock(Rosenbrock):
+ """Rosenbrock subject to equality and inequality constraints.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2)
+ subject to: x[0] + 2 x[1] <= 1
+ 2 x[0] + x[1] = 1
+
+ Taken from matlab ``fimincon`` documentation.
+ """
+ def __init__(self, random_state=0):
+ Rosenbrock.__init__(self, 2, random_state)
+ self.x0 = [-1, -0.5]
+ self.x_opt = [0.41494, 0.17011]
+ self.bounds = None
+
+ @property
+ def constr(self):
+ A_ineq = [[1, 2]]
+ b_ineq = 1
+ A_eq = [[2, 1]]
+ b_eq = 1
+ return (LinearConstraint(A_ineq, -np.inf, b_ineq),
+ LinearConstraint(A_eq, b_eq, b_eq))
+
+
+class Elec:
+ """Distribution of electrons on a sphere.
+
+ Problem no 2 from COPS collection [2]_. Find
+ the equilibrium state distribution (of minimal
+ potential) of the electrons positioned on a
+ conducting sphere.
+
+ References
+ ----------
+ .. [1] E. D. Dolan, J. J. Mor\'{e}, and T. S. Munson,
+ "Benchmarking optimization software with COPS 3.0.",
+ Argonne National Lab., Argonne, IL (US), 2004.
+ """
+ def __init__(self, n_electrons=200, random_state=0,
+ constr_jac=None, constr_hess=None):
+ self.n_electrons = n_electrons
+ self.rng = np.random.RandomState(random_state)
+ # Initial Guess
+ phi = self.rng.uniform(0, 2 * np.pi, self.n_electrons)
+ theta = self.rng.uniform(-np.pi, np.pi, self.n_electrons)
+ x = np.cos(theta) * np.cos(phi)
+ y = np.cos(theta) * np.sin(phi)
+ z = np.sin(theta)
+ self.x0 = np.hstack((x, y, z))
+ self.x_opt = None
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = None
+
+ def _get_cordinates(self, x):
+ x_coord = x[:self.n_electrons]
+ y_coord = x[self.n_electrons:2 * self.n_electrons]
+ z_coord = x[2 * self.n_electrons:]
+ return x_coord, y_coord, z_coord
+
+ def _compute_coordinate_deltas(self, x):
+ x_coord, y_coord, z_coord = self._get_cordinates(x)
+ dx = x_coord[:, None] - x_coord
+ dy = y_coord[:, None] - y_coord
+ dz = z_coord[:, None] - z_coord
+ return dx, dy, dz
+
+ def fun(self, x):
+ dx, dy, dz = self._compute_coordinate_deltas(x)
+ with np.errstate(divide='ignore'):
+ dm1 = (dx**2 + dy**2 + dz**2) ** -0.5
+ dm1[np.diag_indices_from(dm1)] = 0
+ return 0.5 * np.sum(dm1)
+
+ def grad(self, x):
+ dx, dy, dz = self._compute_coordinate_deltas(x)
+
+ with np.errstate(divide='ignore'):
+ dm3 = (dx**2 + dy**2 + dz**2) ** -1.5
+ dm3[np.diag_indices_from(dm3)] = 0
+
+ grad_x = -np.sum(dx * dm3, axis=1)
+ grad_y = -np.sum(dy * dm3, axis=1)
+ grad_z = -np.sum(dz * dm3, axis=1)
+
+ return np.hstack((grad_x, grad_y, grad_z))
+
+ def hess(self, x):
+ dx, dy, dz = self._compute_coordinate_deltas(x)
+ d = (dx**2 + dy**2 + dz**2) ** 0.5
+
+ with np.errstate(divide='ignore'):
+ dm3 = d ** -3
+ dm5 = d ** -5
+
+ i = np.arange(self.n_electrons)
+ dm3[i, i] = 0
+ dm5[i, i] = 0
+
+ Hxx = dm3 - 3 * dx**2 * dm5
+ Hxx[i, i] = -np.sum(Hxx, axis=1)
+
+ Hxy = -3 * dx * dy * dm5
+ Hxy[i, i] = -np.sum(Hxy, axis=1)
+
+ Hxz = -3 * dx * dz * dm5
+ Hxz[i, i] = -np.sum(Hxz, axis=1)
+
+ Hyy = dm3 - 3 * dy**2 * dm5
+ Hyy[i, i] = -np.sum(Hyy, axis=1)
+
+ Hyz = -3 * dy * dz * dm5
+ Hyz[i, i] = -np.sum(Hyz, axis=1)
+
+ Hzz = dm3 - 3 * dz**2 * dm5
+ Hzz[i, i] = -np.sum(Hzz, axis=1)
+
+ H = np.vstack((
+ np.hstack((Hxx, Hxy, Hxz)),
+ np.hstack((Hxy, Hyy, Hyz)),
+ np.hstack((Hxz, Hyz, Hzz))
+ ))
+
+ return H
+
+ @property
+ def constr(self):
+ def fun(x):
+ x_coord, y_coord, z_coord = self._get_cordinates(x)
+ return x_coord**2 + y_coord**2 + z_coord**2 - 1
+
+ if self.constr_jac is None:
+ def jac(x):
+ x_coord, y_coord, z_coord = self._get_cordinates(x)
+ Jx = 2 * np.diag(x_coord)
+ Jy = 2 * np.diag(y_coord)
+ Jz = 2 * np.diag(z_coord)
+ return csc_array(np.hstack((Jx, Jy, Jz)))
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ D = 2 * np.diag(v)
+ return block_diag(D, D, D)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, -np.inf, 0, jac, hess)
+
+
+class TestTrustRegionConstr:
+ list_of_problems = [Maratos(),
+ Maratos(constr_hess='2-point'),
+ Maratos(constr_hess=SR1()),
+ Maratos(constr_jac='2-point', constr_hess=SR1()),
+ MaratosGradInFunc(),
+ HyperbolicIneq(),
+ HyperbolicIneq(constr_hess='3-point'),
+ HyperbolicIneq(constr_hess=BFGS()),
+ HyperbolicIneq(constr_jac='3-point',
+ constr_hess=BFGS()),
+ Rosenbrock(),
+ IneqRosenbrock(),
+ EqIneqRosenbrock(),
+ BoundedRosenbrock(),
+ Elec(n_electrons=2),
+ Elec(n_electrons=2, constr_hess='2-point'),
+ Elec(n_electrons=2, constr_hess=SR1()),
+ Elec(n_electrons=2, constr_jac='3-point',
+ constr_hess=SR1())]
+
+ @pytest.mark.parametrize('prob', list_of_problems)
+ @pytest.mark.parametrize('grad', ('prob.grad', '3-point', False))
+ @pytest.mark.parametrize('hess', ("prob.hess", '3-point', lambda: SR1(),
+ lambda: BFGS(exception_strategy='damp_update'),
+ lambda: BFGS(exception_strategy='skip_update')))
+ def test_list_of_problems(self, prob, grad, hess):
+ grad = prob.grad if grad == "prob.grad" else grad
+ hess = hess() if callable(hess) else hess
+ hess = prob.hess if hess == "prob.hess" else hess
+ # Remove exceptions
+ if (grad in {'2-point', '3-point', 'cs', False} and
+ hess in {'2-point', '3-point', 'cs'}):
+ pytest.skip("Numerical Hessian needs analytical gradient")
+ if prob.grad is True and grad in {'3-point', False}:
+ pytest.skip("prob.grad incompatible with grad in {'3-point', False}")
+ sensitive = (isinstance(prob, BoundedRosenbrock) and grad == '3-point'
+ and isinstance(hess, BFGS))
+ if sensitive:
+ pytest.xfail("Seems sensitive to initial conditions w/ Accelerate")
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ result = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ jac=grad, hess=hess,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ if prob.x_opt is not None:
+ assert_array_almost_equal(result.x, prob.x_opt,
+ decimal=5)
+ # gtol
+ if result.status == 1:
+ assert_array_less(result.optimality, 1e-8)
+ # xtol
+ if result.status == 2:
+ assert_array_less(result.tr_radius, 1e-8)
+
+ if result.method == "tr_interior_point":
+ assert_array_less(result.barrier_parameter, 1e-8)
+
+ # check for max iter
+ message = f"Invalid termination condition: {result.status}."
+ assert result.status not in {0, 3}, message
+
+
+ def test_default_jac_and_hess(self):
+ def fun(x):
+ return (x - 1) ** 2
+ bounds = [(-2, 2)]
+ res = minimize(fun, x0=[-1.5], bounds=bounds, method='trust-constr')
+ assert_array_almost_equal(res.x, 1, decimal=5)
+
+ def test_default_hess(self):
+ def fun(x):
+ return (x - 1) ** 2
+ bounds = [(-2, 2)]
+ res = minimize(fun, x0=[-1.5], bounds=bounds, method='trust-constr',
+ jac='2-point')
+ assert_array_almost_equal(res.x, 1, decimal=5)
+
+ def test_no_constraints(self):
+ prob = Rosenbrock()
+ result = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ jac=prob.grad, hess=prob.hess)
+ result1 = minimize(prob.fun, prob.x0,
+ method='L-BFGS-B',
+ jac='2-point')
+
+ result2 = minimize(prob.fun, prob.x0,
+ method='L-BFGS-B',
+ jac='3-point')
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=5)
+ assert_array_almost_equal(result1.x, prob.x_opt, decimal=5)
+ assert_array_almost_equal(result2.x, prob.x_opt, decimal=5)
+
+ def test_hessp(self):
+ prob = Maratos()
+
+ def hessp(x, p):
+ H = prob.hess(x)
+ return H.dot(p)
+
+ result = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ jac=prob.grad, hessp=hessp,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ if prob.x_opt is not None:
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=2)
+
+ # gtol
+ if result.status == 1:
+ assert_array_less(result.optimality, 1e-8)
+ # xtol
+ if result.status == 2:
+ assert_array_less(result.tr_radius, 1e-8)
+
+ if result.method == "tr_interior_point":
+ assert_array_less(result.barrier_parameter, 1e-8)
+ # max iter
+ if result.status in (0, 3):
+ raise RuntimeError("Invalid termination condition.")
+
+ def test_args(self):
+ prob = MaratosTestArgs("a", 234)
+
+ result = minimize(prob.fun, prob.x0, ("a", 234),
+ method='trust-constr',
+ jac=prob.grad, hess=prob.hess,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ if prob.x_opt is not None:
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=2)
+
+ # gtol
+ if result.status == 1:
+ assert_array_less(result.optimality, 1e-8)
+ # xtol
+ if result.status == 2:
+ assert_array_less(result.tr_radius, 1e-8)
+ if result.method == "tr_interior_point":
+ assert_array_less(result.barrier_parameter, 1e-8)
+ # max iter
+ if result.status in (0, 3):
+ raise RuntimeError("Invalid termination condition.")
+
+ def test_raise_exception(self):
+ prob = Maratos()
+ message = "Whenever the gradient is estimated via finite-differences"
+ with pytest.raises(ValueError, match=message):
+ minimize(prob.fun, prob.x0, method='trust-constr', jac='2-point',
+ hess='2-point', constraints=prob.constr)
+
+ def test_issue_9044(self):
+ # https://github.com/scipy/scipy/issues/9044
+ # Test the returned `OptimizeResult` contains keys consistent with
+ # other solvers.
+
+ def callback(x, info):
+ assert_('nit' in info)
+ assert_('niter' in info)
+
+ result = minimize(lambda x: x**2, [0], jac=lambda x: 2*x,
+ hess=lambda x: 2, callback=callback,
+ method='trust-constr')
+ assert_(result.get('success'))
+ assert_(result.get('nit', -1) == 1)
+
+ # Also check existence of the 'niter' attribute, for backward
+ # compatibility
+ assert_(result.get('niter', -1) == 1)
+
+ def test_issue_15093(self):
+ # scipy docs define bounds as inclusive, so it shouldn't be
+ # an issue to set x0 on the bounds even if keep_feasible is
+ # True. Previously, trust-constr would treat bounds as
+ # exclusive.
+
+ x0 = np.array([0., 0.5])
+
+ def obj(x):
+ x1 = x[0]
+ x2 = x[1]
+ return x1 ** 2 + x2 ** 2
+
+ bounds = Bounds(np.array([0., 0.]), np.array([1., 1.]),
+ keep_feasible=True)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ result = minimize(
+ method='trust-constr',
+ fun=obj,
+ x0=x0,
+ bounds=bounds)
+
+ assert result['success']
+
+class TestEmptyConstraint:
+ """
+ Here we minimize x^2+y^2 subject to x^2-y^2>1.
+ The actual minimum is at (0, 0) which fails the constraint.
+ Therefore we will find a minimum on the boundary at (+/-1, 0).
+
+ When minimizing on the boundary, optimize uses a set of
+ constraints that removes the constraint that sets that
+ boundary. In our case, there's only one constraint, so
+ the result is an empty constraint.
+
+ This tests that the empty constraint works.
+ """
+ def test_empty_constraint(self):
+
+ def function(x):
+ return x[0]**2 + x[1]**2
+
+ def functionjacobian(x):
+ return np.array([2.*x[0], 2.*x[1]])
+
+ def functionhvp(x, v):
+ return 2.*v
+
+ def constraint(x):
+ return np.array([x[0]**2 - x[1]**2])
+
+ def constraintjacobian(x):
+ return np.array([[2*x[0], -2*x[1]]])
+
+ def constraintlcoh(x, v):
+ return np.array([[2., 0.], [0., -2.]]) * v[0]
+
+ constraint = NonlinearConstraint(constraint, 1., np.inf,
+ constraintjacobian, constraintlcoh)
+
+ startpoint = [1., 2.]
+
+ bounds = Bounds([-np.inf, -np.inf], [np.inf, np.inf])
+
+ result = minimize(
+ function,
+ startpoint,
+ method='trust-constr',
+ jac=functionjacobian,
+ hessp=functionhvp,
+ constraints=[constraint],
+ bounds=bounds,
+ )
+
+ assert_array_almost_equal(abs(result.x), np.array([1, 0]), decimal=4)
+
+
+def test_bug_11886():
+ def opt(x):
+ return x[0]**2+x[1]**2
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", PendingDeprecationWarning)
+ A = np.matrix(np.diag([1, 1]))
+ lin_cons = LinearConstraint(A, -1, np.inf)
+ # just checking that there are no errors
+ minimize(opt, 2*[1], constraints = lin_cons)
+
+
+def test_gh11649():
+ # trust - constr error when attempting to keep bound constrained solutions
+ # feasible. Algorithm attempts to go outside bounds when evaluating finite
+ # differences. (don't give objective an analytic gradient)
+ bnds = Bounds(lb=[-1, -1], ub=[1, 1], keep_feasible=True)
+
+ def assert_inbounds(x):
+ assert np.all(x >= bnds.lb)
+ assert np.all(x <= bnds.ub)
+
+ def obj(x):
+ assert_inbounds(x)
+ return np.exp(x[0])*(4*x[0]**2 + 2*x[1]**2 + 4*x[0]*x[1] + 2*x[1] + 1)
+
+ def nce(x):
+ assert_inbounds(x)
+ return x[0]**2 + x[1]
+
+ def nce_jac(x):
+ return np.array([2*x[0], 1])
+
+ def nci(x):
+ assert_inbounds(x)
+ return x[0]*x[1]
+
+ x0 = np.array((0.99, -0.99))
+ nlcs = [NonlinearConstraint(nci, -10, np.inf),
+ NonlinearConstraint(nce, 1, 1, jac=nce_jac)]
+
+ res = minimize(fun=obj, x0=x0, method='trust-constr',
+ bounds=bnds, constraints=nlcs)
+ assert_inbounds(res.x)
+ assert nlcs[0].lb < nlcs[0].fun(res.x) < nlcs[0].ub
+
+
+def test_gh24424():
+ def calculate_intermediates(a, b, c, data):
+ result = np.empty(
+ shape=len(data),
+ dtype=float
+ )
+ result[0] = a / (1 - b - c)
+ for i, d in enumerate(data[:-1], 1):
+ result[i] = a + c * result[i - 1] + b * d
+ return result
+
+ def calculate_jacobian_intermediates(log_a, b, c, data, intermediates):
+ a = np.exp(log_a)
+
+ result = np.empty(
+ shape=(len(data), 3),
+ dtype=float
+ )
+ result[0, 0] = a / (1 - b - c)
+ result[0, 1] = a / (1 - b - c) ** 2
+ result[0, 2] = a / (1 - b - c) ** 2
+
+ for i in range(1, len(data)):
+ previous_jacobian_term = c * result[i - 1]
+
+ result[i, 0] = a + previous_jacobian_term[0]
+ result[i, 1] = data[i - 1] + previous_jacobian_term[1]
+ result[i, 2] = intermediates[i - 1] + previous_jacobian_term[2]
+
+ return result
+
+ def objective_and_jacobian(theta, data):
+ log_a, b, c = theta
+
+ assert 0 <= b <= 1, "Bounds was violated for variable `a`."
+ assert 0 <= c <= 1, "Bounds was violated for variable `b`."
+ assert b + c < 1, "Constraint was violated."
+
+ a = np.exp(log_a)
+
+ intermediates = calculate_intermediates(
+ a=a,
+ b=b,
+ c=c,
+ data=data
+ )
+ result = np.sum(
+ np.log(intermediates) + data / intermediates
+ )
+
+ jacobian_intermediates = calculate_jacobian_intermediates(
+ log_a=log_a,
+ b=b,
+ c=c,
+ data=data,
+ intermediates=intermediates
+ )
+ jacobian = \
+ (1 / intermediates - data / intermediates ** 2) @ jacobian_intermediates
+
+ return result, jacobian
+
+ data = np.array([
+ 2.9934552262644166e-05, 1.83404750498639e-05, 3.8762287534860667e-05,
+ 5.4537741557086936e-06, 1.8971702025284017e-05, 5.327721423321283e-06,
+ 7.975416195706544e-06, 1.1382485956213557e-05, 3.9576073822143895e-05,
+ 1.6686716514067753e-05, 2.521966334088718e-05, 1.2203016286995732e-05,
+ 6.104844206226364e-06, 3.656990591660379e-05, 7.50740799602968e-06,
+ 5.1787715626447475e-05, 4.068430728392944e-05, 1.6425909413963983e-06,
+ 2.323453810347028e-05, 3.2537707515840034e-05, 1.0199717988183908e-05,
+ 9.011651369071027e-06, 9.423474666676454e-06, 5.080061504315627e-06,
+ 2.41505514167834e-05, 2.513422432759034e-05, 2.0642198121990002e-05,
+ 8.321874187176471e-06, 1.019170126320171e-05, 2.597532020137934e-07,
+ 3.908918145517398e-05, 3.165502329497437e-05, 3.902338742601731e-06,
+ 1.9642839599876334e-05, 1.4202292239184809e-05, 1.6770752189396043e-05,
+ 6.213979916610612e-06, 3.171396103300187e-05, 9.934130727121179e-06,
+ 3.0358455907343625e-05, 6.224043027231856e-07, 1.063405415951252e-06,
+ 1.6308810826809896e-05, 7.867464317695382e-06, 1.4108106007697538e-05,
+ 1.8722709625238567e-05, 1.3198437078692119e-05, 2.221667555167261e-06,
+ 6.256595702046974e-05, 2.6361829576605727e-05, 1.7374401653652944e-05,
+ 5.183207198861357e-06, 1.0048728069764142e-05, 2.3198968737030035e-06,
+ 7.439480755759099e-06, 1.2298059429320431e-05, 2.0185774097335823e-05,
+ 8.014211503092624e-06, 9.305654715149352e-06, 3.60136657702133e-05,
+ 2.32149271461897e-05, 1.8652336119941976e-05, 3.473510850318922e-05,
+ 1.0194877213172668e-05, 2.2083922152696592e-05, 1.1766282835177292e-05,
+ 1.7086225762873947e-05, 6.466499880883932e-05, 9.234869650567825e-06,
+ 1.9427199320844276e-05, 2.8241613272189955e-05, 5.378122279928882e-05,
+ 2.604144856548882e-05, 1.9454208137286557e-05, 4.287312368904257e-05,
+ 1.57187091820659e-05, 1.2484808801911742e-05, 1.7167397579819053e-05,
+ 0.0, 2.0252462281186e-05, 1.4774599170124377e-05,
+ 0.0, 3.0064855641072096e-05, 1.1951667450097332e-05,
+ 2.6717918042680187e-05, 2.2491563831828074e-05, 1.4748949757360303e-05,
+ 9.422793251613177e-05, 8.668457255209887e-05, 2.3355215071734614e-05,
+ 4.4706397982269585e-05, 2.7992021752856294e-05, 7.694104461408618e-05,
+ 4.020190100203822e-05, 4.0915164084390224e-05, 7.174183343729235e-05,
+ 7.103034737172072e-05, 8.224690780946857e-05, 0.00012873982383790664,
+ 4.995816817323732e-05, 0.0, 5.921437092197502e-05,
+ 1.544436592616776e-05, 5.8810138143918906e-05, 1.9400221788675188e-05,
+ 4.5630225293291145e-05, 3.204082932872853e-05, 2.2445753506172103e-05,
+ 4.2075935382479554e-05, 2.4598027012525572e-05, 5.7410672937657564e-05,
+ 7.502234318198545e-05, 7.592571131932753e-05, 6.356522172494383e-06,
+ 5.386009659469673e-06, 2.584466503185e-05, 2.5724698395300155e-05,
+ 5.205615091351065e-05, 7.859446356765305e-05, 7.273145118589368e-06,
+ 2.314487591559627e-05, 3.69477147738378e-05, 2.1830541071086155e-05,
+ 7.511731105500895e-05, 1.5450999502759258e-05, 0.0,
+ 1.582211718453788e-05, 2.702016660887833e-05, 2.3641331381091936e-05,
+ 1.7579054910909477e-05, 6.383358007440582e-05, 1.925774054598795e-05,
+ 2.6648621120684558e-05, 1.2325662981013882e-05, 1.575955730688859e-05,
+ 7.021212451816662e-05, 1.5772697293897e-05, 1.7655937683952653e-05,
+ 2.5284532609827995e-06, 3.106257322767402e-05, 7.668118254072083e-05,
+ 4.684839412305774e-05, 2.5356641538859304e-05, 3.105206100981116e-05,
+ 2.7265881197510174e-05, 1.3920984856376055e-05, 7.08918619393585e-06,
+ 4.858002948371407e-05, 1.7633679540206005e-05, 3.9984786626623e-06,
+ 1.2150737261530062e-05, 1.4932495278445555e-05, 1.4907183322390042e-05,
+ 1.4608977266060503e-05, 1.2850307928856668e-05, 8.004737075371617e-06,
+ 3.620174626132346e-06, 1.5131513705442799e-05, 3.098052405312182e-06,
+ 1.0007362202939136e-05, 2.4049828598531798e-05, 1.6466966920680003e-05,
+ 1.7180612084121284e-05, 2.1266769642355435e-05, 1.4784179724678913e-05,
+ 9.732346693107168e-06, 9.033960719308952e-06, 1.3459809558545056e-05
+ ])
+
+ minimize(
+ fun=objective_and_jacobian,
+ x0=[
+ np.log(np.mean(data)),
+ 0.45,
+ 0.3
+ ],
+ args=(
+ data
+ ),
+ method='trust-constr',
+ jac=True,
+ bounds=Bounds(
+ lb=[-np.inf, 0.0, 0.0],
+ ub=[np.inf, 1.0, 1.0],
+ keep_feasible=True
+ ),
+ constraints=LinearConstraint(
+ A=[0, 1, 1],
+ ub=0.999999,
+ keep_feasible=True
+ )
+ )
+
+
+def test_gh20665_too_many_constraints():
+ # gh-20665 reports a confusing error message when there are more equality
+ # constraints than variables. Check that the error message is improved.
+ message = "...more equality constraints than independent variables..."
+ with pytest.raises(ValueError, match=message):
+ x0 = np.ones((2,))
+ A_eq, b_eq = np.arange(6).reshape((3, 2)), np.ones((3,))
+ g = NonlinearConstraint(lambda x: A_eq @ x, lb=b_eq, ub=b_eq)
+ minimize(rosen, x0, method='trust-constr', constraints=[g])
+ # no error with `SVDFactorization`
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ minimize(rosen, x0, method='trust-constr', constraints=[g],
+ options={'factorization_method': 'SVDFactorization'})
+
+def test_issue_18882():
+ def lsf(u):
+ u1, u2 = u
+ a, b = [3.0, 4.0]
+ return 1.0 + u1**2 / a**2 - u2**2 / b**2
+
+ def of(u):
+ return np.sum(u**2)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ warnings.filterwarnings("ignore", "Singular Jacobian matrix.", UserWarning)
+ res = minimize(
+ of,
+ [0.0, 0.0],
+ method="trust-constr",
+ constraints=NonlinearConstraint(lsf, 0, 0),
+ )
+ assert (not res.success) and (res.constr_violation > 1e-8)
+
+class TestBoundedNelderMead:
+
+ @pytest.mark.parametrize('bounds, x_opt',
+ [(Bounds(-np.inf, np.inf), Rosenbrock().x_opt),
+ (Bounds(-np.inf, -0.8), [-0.8, -0.8]),
+ (Bounds(3.0, np.inf), [3.0, 9.0]),
+ (Bounds([3.0, 1.0], [4.0, 5.0]), [3., 5.]),
+ ])
+ def test_rosen_brock_with_bounds(self, bounds, x_opt):
+ prob = Rosenbrock()
+ with warnings.catch_warnings():
+ msg = "Initial guess is not within the specified bounds"
+ warnings.filterwarnings("ignore", msg, UserWarning)
+ result = minimize(prob.fun, [-10, -10],
+ method='Nelder-Mead',
+ bounds=bounds)
+ assert np.less_equal(bounds.lb, result.x).all()
+ assert np.less_equal(result.x, bounds.ub).all()
+ assert np.allclose(prob.fun(result.x), result.fun)
+ assert np.allclose(result.x, x_opt, atol=1.e-3)
+
+ def test_equal_all_bounds(self):
+ prob = Rosenbrock()
+ bounds = Bounds([4.0, 5.0], [4.0, 5.0])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Initial guess is not within the specified bounds",
+ UserWarning)
+ result = minimize(prob.fun, [-10, 8],
+ method='Nelder-Mead',
+ bounds=bounds)
+ assert np.allclose(result.x, [4.0, 5.0])
+
+ def test_equal_one_bounds(self):
+ prob = Rosenbrock()
+ bounds = Bounds([4.0, 5.0], [4.0, 20.0])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Initial guess is not within the specified bounds",
+ UserWarning)
+ result = minimize(prob.fun, [-10, 8],
+ method='Nelder-Mead',
+ bounds=bounds)
+ assert np.allclose(result.x, [4.0, 16.0])
+
+ def test_invalid_bounds(self):
+ prob = Rosenbrock()
+ message = 'An upper bound is less than the corresponding lower bound.'
+ with pytest.raises(ValueError, match=message):
+ bounds = Bounds([-np.inf, 1.0], [4.0, -5.0])
+ minimize(prob.fun, [-10, 3],
+ method='Nelder-Mead',
+ bounds=bounds)
+
+ @pytest.mark.xfail(reason="Failing on Azure Linux and macOS builds, "
+ "see gh-13846")
+ def test_outside_bounds_warning(self):
+ prob = Rosenbrock()
+ message = "Initial guess is not within the specified bounds"
+ with pytest.warns(UserWarning, match=message):
+ bounds = Bounds([-np.inf, 1.0], [4.0, 5.0])
+ minimize(prob.fun, [-10, 8],
+ method='Nelder-Mead',
+ bounds=bounds)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_minpack.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8d287e98ff7b33272119e214120234b4e9fc96e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_minpack.py
@@ -0,0 +1,1195 @@
+"""
+Unit tests for optimization routines from minpack.py.
+"""
+import warnings
+import pytest
+import threading
+
+from numpy.testing import (assert_, assert_almost_equal, assert_array_equal,
+ assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+import numpy as np
+from numpy import array, float64
+from multiprocessing.pool import ThreadPool
+
+from scipy import optimize, linalg
+from scipy.special import lambertw
+from scipy.optimize._minpack_py import leastsq, curve_fit, fixed_point
+from scipy.optimize import OptimizeWarning
+from scipy.optimize._minimize import Bounds
+
+
+class ReturnShape:
+ """This class exists to create a callable that does not have a '__name__' attribute.
+
+ __init__ takes the argument 'shape', which should be a tuple of ints.
+ When an instance is called with a single argument 'x', it returns numpy.ones(shape).
+ """
+
+ def __init__(self, shape):
+ self.shape = shape
+
+ def __call__(self, x):
+ return np.ones(self.shape)
+
+
+def dummy_func(x, shape):
+ """A function that returns an array of ones of the given shape.
+ `x` is ignored.
+ """
+ return np.ones(shape)
+
+
+def sequence_parallel(fs):
+ with ThreadPool(len(fs)) as pool:
+ return pool.map(lambda f: f(), fs)
+
+
+# Function and Jacobian for tests of solvers for systems of nonlinear
+# equations
+
+
+def pressure_network(flow_rates, Qtot, k):
+ """Evaluate non-linear equation system representing
+ the pressures and flows in a system of n parallel pipes::
+
+ f_i = P_i - P_0, for i = 1..n
+ f_0 = sum(Q_i) - Qtot
+
+ where Q_i is the flow rate in pipe i and P_i the pressure in that pipe.
+ Pressure is modeled as a P=kQ**2 where k is a valve coefficient and
+ Q is the flow rate.
+
+ Parameters
+ ----------
+ flow_rates : float
+ A 1-D array of n flow rates [kg/s].
+ k : float
+ A 1-D array of n valve coefficients [1/kg m].
+ Qtot : float
+ A scalar, the total input flow rate [kg/s].
+
+ Returns
+ -------
+ F : float
+ A 1-D array, F[i] == f_i.
+
+ """
+ P = k * flow_rates**2
+ F = np.hstack((P[1:] - P[0], flow_rates.sum() - Qtot))
+ return F
+
+
+def pressure_network_jacobian(flow_rates, Qtot, k):
+ """Return the jacobian of the equation system F(flow_rates)
+ computed by `pressure_network` with respect to
+ *flow_rates*. See `pressure_network` for the detailed
+ description of parameters.
+
+ Returns
+ -------
+ jac : float
+ *n* by *n* matrix ``df_i/dQ_i`` where ``n = len(flow_rates)``
+ and *f_i* and *Q_i* are described in the doc for `pressure_network`
+ """
+ n = len(flow_rates)
+ pdiff = np.diag(flow_rates[1:] * 2 * k[1:] - 2 * flow_rates[0] * k[0])
+
+ jac = np.empty((n, n))
+ jac[:n-1, :n-1] = pdiff * 0
+ jac[:n-1, n-1] = 0
+ jac[n-1, :] = np.ones(n)
+
+ return jac
+
+
+def pressure_network_fun_and_grad(flow_rates, Qtot, k):
+ return (pressure_network(flow_rates, Qtot, k),
+ pressure_network_jacobian(flow_rates, Qtot, k))
+
+
+class TestFSolve:
+ def test_pressure_network_no_gradient(self):
+ # fsolve without gradient, equal pipes -> equal flows.
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows, info, ier, mesg = optimize.fsolve(
+ pressure_network, initial_guess, args=(Qtot, k),
+ full_output=True)
+ assert_array_almost_equal(final_flows, np.ones(4))
+ assert_(ier == 1, mesg)
+
+ def test_pressure_network_with_gradient(self):
+ # fsolve with gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.fsolve(
+ pressure_network, initial_guess, args=(Qtot, k),
+ fprime=pressure_network_jacobian)
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_wrong_shape_func_callable(self):
+ func = ReturnShape(1)
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.fsolve, func, x0)
+
+ def test_wrong_shape_func_function(self):
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.fsolve, dummy_func, x0, args=((1,),))
+
+ def test_wrong_shape_fprime_callable(self):
+ func = ReturnShape(1)
+ deriv_func = ReturnShape((2,2))
+ assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func)
+
+ def test_wrong_shape_fprime_function(self):
+ def func(x):
+ return dummy_func(x, (2,))
+ def deriv_func(x):
+ return dummy_func(x, (3, 3))
+ assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func)
+
+ def test_func_can_raise(self):
+ def func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.fsolve(func, x0=[0])
+
+ def test_Dfun_can_raise(self):
+ def func(x):
+ return x - np.array([10])
+
+ def deriv_func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.fsolve(func, x0=[0], fprime=deriv_func)
+
+ def test_float32(self):
+ def func(x):
+ return np.array([x[0] - 100, x[1] - 1000], dtype=np.float32) ** 2
+ p = optimize.fsolve(func, np.array([1, 1], np.float32))
+ assert_allclose(func(p), [0, 0], atol=1e-3)
+
+ def test_reentrant_func(self):
+ def func(*args):
+ self.test_pressure_network_no_gradient()
+ return pressure_network(*args)
+
+ # fsolve without gradient, equal pipes -> equal flows.
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows, info, ier, mesg = optimize.fsolve(
+ func, initial_guess, args=(Qtot, k),
+ full_output=True)
+ assert_array_almost_equal(final_flows, np.ones(4))
+ assert_(ier == 1, mesg)
+
+ def test_reentrant_Dfunc(self):
+ def deriv_func(*args):
+ self.test_pressure_network_with_gradient()
+ return pressure_network_jacobian(*args)
+
+ # fsolve with gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.fsolve(
+ pressure_network, initial_guess, args=(Qtot, k),
+ fprime=deriv_func)
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_concurrent_no_gradient(self):
+ v = sequence_parallel([self.test_pressure_network_no_gradient] * 10)
+ assert all([result is None for result in v])
+
+ def test_concurrent_with_gradient(self):
+ v = sequence_parallel([self.test_pressure_network_with_gradient] * 10)
+ assert all([result is None for result in v])
+
+
+class TestRootHybr:
+ def test_pressure_network_no_gradient(self):
+ # root/hybr without gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.root(pressure_network, initial_guess,
+ method='hybr', args=(Qtot, k)).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_pressure_network_with_gradient(self):
+ # root/hybr with gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([[2., 0., 2., 0.]])
+ final_flows = optimize.root(pressure_network, initial_guess,
+ args=(Qtot, k), method='hybr',
+ jac=pressure_network_jacobian).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_pressure_network_with_gradient_combined(self):
+ # root/hybr with gradient and function combined, equal pipes -> equal
+ # flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.root(pressure_network_fun_and_grad,
+ initial_guess, args=(Qtot, k),
+ method='hybr', jac=True).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+
+class TestRootLM:
+ def test_pressure_network_no_gradient(self):
+ # root/lm without gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.root(pressure_network, initial_guess,
+ method='lm', args=(Qtot, k)).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+
+class TestNfev:
+ def setup_method(self):
+ self.nfev = threading.local()
+
+ def zero_f(self, y):
+ if not hasattr(self.nfev, 'c'):
+ self.nfev.c = 0
+ self.nfev.c += 1
+ return y**2-3
+
+ @pytest.mark.parametrize('method', ['hybr', 'lm', 'broyden1',
+ 'broyden2', 'anderson',
+ 'linearmixing', 'diagbroyden',
+ 'excitingmixing', 'krylov',
+ 'df-sane'])
+ def test_root_nfev(self, method):
+ self.nfev.c = 0
+ solution = optimize.root(self.zero_f, 100, method=method)
+ assert solution.nfev == self.nfev.c
+
+ def test_fsolve_nfev(self):
+ self.nfev.c = 0
+ x, info, ier, mesg = optimize.fsolve(self.zero_f, 100, full_output=True)
+ assert info['nfev'] == self.nfev.c
+
+
+class TestLeastSq:
+ def setup_method(self):
+ x = np.linspace(0, 10, 40)
+ a,b,c = 3.1, 42, -304.2
+ self.x = x
+ self.abc = a,b,c
+ y_true = a*x**2 + b*x + c
+ rng = np.random.default_rng(123)
+ self.y_meas = y_true + 0.01*rng.standard_normal(y_true.shape)
+
+ def residuals(self, p, y, x):
+ a,b,c = p
+ err = y-(a*x**2 + b*x + c)
+ return err
+
+ def residuals_jacobian(self, _p, _y, x):
+ return -np.vstack([x**2, x, np.ones_like(x)]).T
+
+ def test_basic(self):
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x))
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_basic_with_gradient(self):
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ Dfun=self.residuals_jacobian)
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_full_output(self):
+ p0 = array([[0,0,0]])
+ full_output = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ full_output=True)
+ params_fit, cov_x, infodict, mesg, ier = full_output
+ assert_(ier in (1,2,3,4), f'solution not found: {mesg}')
+
+ def test_input_untouched(self):
+ p0 = array([0,0,0],dtype=float64)
+ p0_copy = array(p0, copy=True)
+ full_output = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ full_output=True)
+ params_fit, cov_x, infodict, mesg, ier = full_output
+ assert_(ier in (1,2,3,4), f'solution not found: {mesg}')
+ assert_array_equal(p0, p0_copy)
+
+ def test_wrong_shape_func_callable(self):
+ func = ReturnShape(1)
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.leastsq, func, x0)
+
+ def test_wrong_shape_func_function(self):
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.leastsq, dummy_func, x0, args=((1,),))
+
+ def test_wrong_shape_Dfun_callable(self):
+ func = ReturnShape(1)
+ deriv_func = ReturnShape((2,2))
+ assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func)
+
+ def test_wrong_shape_Dfun_function(self):
+ def func(x):
+ return dummy_func(x, (2,))
+ def deriv_func(x):
+ return dummy_func(x, (3, 3))
+ assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func)
+
+ def test_float32(self):
+ # Regression test for gh-1447
+ def func(p,x,y):
+ q = p[0]*np.exp(-(x-p[1])**2/(2.0*p[2]**2))+p[3]
+ return q - y
+
+ x = np.array([1.475,1.429,1.409,1.419,1.455,1.519,1.472, 1.368,1.286,
+ 1.231], dtype=np.float32)
+ y = np.array([0.0168,0.0193,0.0211,0.0202,0.0171,0.0151,0.0185,0.0258,
+ 0.034,0.0396], dtype=np.float32)
+ p0 = np.array([1.0,1.0,1.0,1.0])
+ p1, success = optimize.leastsq(func, p0, args=(x,y))
+
+ assert_(success in [1,2,3,4])
+ assert_((func(p1,x,y)**2).sum() < 1e-4 * (func(p0,x,y)**2).sum())
+
+ def test_func_can_raise(self):
+ def func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.leastsq(func, x0=[0])
+
+ def test_Dfun_can_raise(self):
+ def func(x):
+ return x - np.array([10])
+
+ def deriv_func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.leastsq(func, x0=[0], Dfun=deriv_func)
+
+ def test_reentrant_func(self):
+ def func(*args):
+ self.test_basic()
+ return self.residuals(*args)
+
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(func, p0,
+ args=(self.y_meas, self.x))
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_reentrant_Dfun(self):
+ def deriv_func(*args):
+ self.test_basic()
+ return self.residuals_jacobian(*args)
+
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ Dfun=deriv_func)
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_concurrent_no_gradient(self):
+ v = sequence_parallel([self.test_basic] * 10)
+ assert all([result is None for result in v])
+
+ def test_concurrent_with_gradient(self):
+ v = sequence_parallel([self.test_basic_with_gradient] * 10)
+ assert all([result is None for result in v])
+
+ def test_func_input_output_length_check(self):
+
+ def func(x):
+ return 2 * (x[0] - 3) ** 2 + 1
+
+ with assert_raises(TypeError,
+ match='Improper input: func input vector length N='):
+ optimize.leastsq(func, x0=[0, 1])
+
+
+class TestCurveFit:
+ def setup_method(self):
+ self.y = array([1.0, 3.2, 9.5, 13.7])
+ self.x = array([1.0, 2.0, 3.0, 4.0])
+
+ def test_one_argument(self):
+ def func(x,a):
+ return x**a
+ popt, pcov = curve_fit(func, self.x, self.y)
+ assert_(len(popt) == 1)
+ assert_(pcov.shape == (1,1))
+ assert_almost_equal(popt[0], 1.9149, decimal=4)
+ assert_almost_equal(pcov[0,0], 0.0016, decimal=4)
+
+ # Test if we get the same with full_output. Regression test for #1415.
+ # Also test if check_finite can be turned off.
+ res = curve_fit(func, self.x, self.y,
+ full_output=1, check_finite=False)
+ (popt2, pcov2, infodict, errmsg, ier) = res
+ assert_array_almost_equal(popt, popt2)
+
+ def test_two_argument(self):
+ def func(x, a, b):
+ return b*x**a
+ popt, pcov = curve_fit(func, self.x, self.y)
+ assert_(len(popt) == 2)
+ assert_(pcov.shape == (2,2))
+ assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4)
+ assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]],
+ decimal=4)
+
+ def test_func_is_classmethod(self):
+ class test_self:
+ """This class tests if curve_fit passes the correct number of
+ arguments when the model function is a class instance method.
+ """
+
+ def func(self, x, a, b):
+ return b * x**a
+
+ test_self_inst = test_self()
+ popt, pcov = curve_fit(test_self_inst.func, self.x, self.y)
+ assert_(pcov.shape == (2,2))
+ assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4)
+ assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]],
+ decimal=4)
+
+ def test_regression_2639(self):
+ # This test fails if epsfcn in leastsq is too large.
+ x = [574.14200000000005, 574.154, 574.16499999999996,
+ 574.17700000000002, 574.18799999999999, 574.19899999999996,
+ 574.21100000000001, 574.22199999999998, 574.23400000000004,
+ 574.245]
+ y = [859.0, 997.0, 1699.0, 2604.0, 2013.0, 1964.0, 2435.0,
+ 1550.0, 949.0, 841.0]
+ guess = [574.1861428571428, 574.2155714285715, 1302.0, 1302.0,
+ 0.0035019999999983615, 859.0]
+ good = [5.74177150e+02, 5.74209188e+02, 1.74187044e+03, 1.58646166e+03,
+ 1.0068462e-02, 8.57450661e+02]
+
+ def f_double_gauss(x, x0, x1, A0, A1, sigma, c):
+ return (A0*np.exp(-(x-x0)**2/(2.*sigma**2))
+ + A1*np.exp(-(x-x1)**2/(2.*sigma**2)) + c)
+ popt, pcov = curve_fit(f_double_gauss, x, y, guess, maxfev=10000)
+ assert_allclose(popt, good, rtol=1e-5)
+
+ def test_pcov(self):
+ xdata = np.array([0, 1, 2, 3, 4, 5])
+ ydata = np.array([1, 1, 5, 7, 8, 12])
+ sigma = np.array([1, 2, 1, 2, 1, 2])
+
+ def f(x, a, b):
+ return a*x + b
+
+ for method in ['lm', 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma,
+ method=method)
+ perr_scaled = np.sqrt(np.diag(pcov))
+ assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3)
+
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma,
+ method=method)
+ perr_scaled = np.sqrt(np.diag(pcov))
+ assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3)
+
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma,
+ absolute_sigma=True, method=method)
+ perr = np.sqrt(np.diag(pcov))
+ assert_allclose(perr, [0.30714756, 0.85045308], rtol=1e-3)
+
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma,
+ absolute_sigma=True, method=method)
+ perr = np.sqrt(np.diag(pcov))
+ assert_allclose(perr, [3*0.30714756, 3*0.85045308], rtol=1e-3)
+
+ # infinite variances
+
+ def f_flat(x, a, b):
+ return a*x
+
+ pcov_expected = np.array([np.inf]*4).reshape(2, 2)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Covariance of the parameters could not be estimated",
+ OptimizeWarning)
+ popt, pcov = curve_fit(f_flat, xdata, ydata, p0=[2, 0], sigma=sigma)
+ popt1, pcov1 = curve_fit(f, xdata[:2], ydata[:2], p0=[2, 0])
+
+ assert_(pcov.shape == (2, 2))
+ assert_array_equal(pcov, pcov_expected)
+
+ assert_(pcov1.shape == (2, 2))
+ assert_array_equal(pcov1, pcov_expected)
+
+ def test_array_like(self):
+ # Test sequence input. Regression test for gh-3037.
+ def f_linear(x, a, b):
+ return a*x + b
+
+ x = [1, 2, 3, 4]
+ y = [3, 5, 7, 9]
+ assert_allclose(curve_fit(f_linear, x, y)[0], [2, 1], atol=1e-10)
+
+ def test_indeterminate_covariance(self):
+ # Test that a warning is returned when pcov is indeterminate
+ xdata = np.array([1, 2, 3, 4, 5, 6])
+ ydata = np.array([1, 2, 3, 4, 5.5, 6])
+ with pytest.warns(OptimizeWarning):
+ curve_fit(lambda x, a, b: a*x, xdata, ydata)
+
+ def test_NaN_handling(self):
+ # Test for correct handling of NaNs in input data: gh-3422
+
+ # create input with NaNs
+ xdata = np.array([1, np.nan, 3])
+ ydata = np.array([1, 2, 3])
+
+ assert_raises(ValueError, curve_fit,
+ lambda x, a, b: a*x + b, xdata, ydata)
+ assert_raises(ValueError, curve_fit,
+ lambda x, a, b: a*x + b, ydata, xdata)
+
+ assert_raises(ValueError, curve_fit, lambda x, a, b: a*x + b,
+ xdata, ydata, **{"check_finite": True})
+
+ @staticmethod
+ def _check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method):
+ kwargs = {'f': f, 'xdata': xdata_with_nan, 'ydata': ydata_with_nan,
+ 'method': method, 'check_finite': False}
+ # propagate test
+ error_msg = ("`nan_policy='propagate'` is not supported "
+ "by this function.")
+ with assert_raises(ValueError, match=error_msg):
+ curve_fit(**kwargs, nan_policy="propagate", maxfev=2000)
+
+ # raise test
+ with assert_raises(ValueError, match="The input contains nan"):
+ curve_fit(**kwargs, nan_policy="raise")
+
+ # omit test
+ result_with_nan, _ = curve_fit(**kwargs, nan_policy="omit")
+ kwargs['xdata'] = xdata_without_nan
+ kwargs['ydata'] = ydata_without_nan
+ result_without_nan, _ = curve_fit(**kwargs)
+ assert_allclose(result_with_nan, result_without_nan)
+
+ # not valid policy test
+ # check for argument names in any order
+ error_msg = (r"nan_policy must be one of \{(?:'raise'|'omit'|None)"
+ r"(?:, ?(?:'raise'|'omit'|None))*\}")
+ with assert_raises(ValueError, match=error_msg):
+ curve_fit(**kwargs, nan_policy="hi")
+
+ @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
+ def test_nan_policy_1d(self, method):
+ def f(x, a, b):
+ return a*x + b
+
+ xdata_with_nan = np.array([2, 3, np.nan, 4, 4, np.nan])
+ ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7])
+ xdata_without_nan = np.array([2, 3, 4])
+ ydata_without_nan = np.array([1, 2, 3])
+
+ self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method)
+
+ @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
+ def test_nan_policy_2d(self, method):
+ def f(x, a, b):
+ x1 = x[0, :]
+ x2 = x[1, :]
+ return a*x1 + b + x2
+
+ xdata_with_nan = np.array([[2, 3, np.nan, 4, 4, np.nan, 5],
+ [2, 3, np.nan, np.nan, 4, np.nan, 7]])
+ ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10])
+ xdata_without_nan = np.array([[2, 3, 5], [2, 3, 7]])
+ ydata_without_nan = np.array([1, 2, 10])
+
+ self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method)
+
+ @pytest.mark.parametrize('n', [2, 3])
+ @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
+ def test_nan_policy_2_3d(self, n, method):
+ def f(x, a, b):
+ x1 = x[..., 0, :].squeeze()
+ x2 = x[..., 1, :].squeeze()
+ return a*x1 + b + x2
+
+ xdata_with_nan = np.array([[[2, 3, np.nan, 4, 4, np.nan, 5],
+ [2, 3, np.nan, np.nan, 4, np.nan, 7]]])
+ xdata_with_nan = xdata_with_nan.squeeze() if n == 2 else xdata_with_nan
+ ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10])
+ xdata_without_nan = np.array([[[2, 3, 5], [2, 3, 7]]])
+ ydata_without_nan = np.array([1, 2, 10])
+
+ self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method)
+
+ def test_empty_inputs(self):
+ # Test both with and without bounds (regression test for gh-9864)
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [])
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [],
+ bounds=(1, 2))
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [1], [])
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [2], [],
+ bounds=(1, 2))
+
+ def test_function_zero_params(self):
+ # Fit args is zero, so "Unable to determine number of fit parameters."
+ assert_raises(ValueError, curve_fit, lambda x: x, [1, 2], [3, 4])
+
+ def test_None_x(self): # Added in GH10196
+ popt, pcov = curve_fit(lambda _, a: a * np.arange(10),
+ None, 2 * np.arange(10))
+ assert_allclose(popt, [2.])
+
+ def test_method_argument(self):
+ def f(x, a, b):
+ return a * np.exp(-b*x)
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ for method in ['trf', 'dogbox', 'lm', None]:
+ popt, pcov = curve_fit(f, xdata, ydata, method=method)
+ assert_allclose(popt, [2., 2.])
+
+ assert_raises(ValueError, curve_fit, f, xdata, ydata, method='unknown')
+
+ def test_full_output(self):
+ def f(x, a, b):
+ return a * np.exp(-b * x)
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ for method in ['trf', 'dogbox', 'lm', None]:
+ popt, pcov, infodict, errmsg, ier = curve_fit(
+ f, xdata, ydata, method=method, full_output=True)
+ assert_allclose(popt, [2., 2.])
+ assert "nfev" in infodict
+ assert "fvec" in infodict
+ if method == 'lm' or method is None:
+ assert "fjac" in infodict
+ assert "ipvt" in infodict
+ assert "qtf" in infodict
+ assert isinstance(errmsg, str)
+ assert ier in (1, 2, 3, 4)
+
+ def test_bounds(self):
+ def f(x, a, b):
+ return a * np.exp(-b*x)
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ # The minimum w/out bounds is at [2., 2.],
+ # and with bounds it's at [1.5, smth].
+ lb = [1., 0]
+ ub = [1.5, 3.]
+
+ # Test that both variants of the bounds yield the same result
+ bounds = (lb, ub)
+ bounds_class = Bounds(lb, ub)
+ for method in [None, 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, bounds=bounds,
+ method=method)
+ assert_allclose(popt[0], 1.5)
+
+ popt_class, pcov_class = curve_fit(f, xdata, ydata,
+ bounds=bounds_class,
+ method=method)
+ assert_allclose(popt_class, popt)
+
+ # With bounds, the starting estimate is feasible.
+ popt, pcov = curve_fit(f, xdata, ydata, method='trf',
+ bounds=([0., 0], [0.6, np.inf]))
+ assert_allclose(popt[0], 0.6)
+
+ # method='lm' doesn't support bounds.
+ assert_raises(ValueError, curve_fit, f, xdata, ydata, bounds=bounds,
+ method='lm')
+
+ def test_bounds_p0(self):
+ # This test is for issue #5719. The problem was that an initial guess
+ # was ignored when 'trf' or 'dogbox' methods were invoked.
+ def f(x, a):
+ return np.sin(x + a)
+
+ xdata = np.linspace(-2*np.pi, 2*np.pi, 40)
+ ydata = np.sin(xdata)
+ bounds = (-3 * np.pi, 3 * np.pi)
+ for method in ['trf', 'dogbox']:
+ popt_1, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi)
+ popt_2, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi,
+ bounds=bounds, method=method)
+
+ # If the initial guess is ignored, then popt_2 would be close 0.
+ assert_allclose(popt_1, popt_2)
+
+ def test_jac(self):
+ # Test that Jacobian callable is handled correctly and
+ # weighted if sigma is provided.
+ def f(x, a, b):
+ return a * np.exp(-b*x)
+
+ def jac(x, a, b):
+ e = np.exp(-b*x)
+ return np.vstack((e, -a * x * e)).T
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ # Test numerical options for least_squares backend.
+ for method in ['trf', 'dogbox']:
+ for scheme in ['2-point', '3-point', 'cs']:
+ popt, pcov = curve_fit(f, xdata, ydata, jac=scheme,
+ method=method)
+ assert_allclose(popt, [2, 2])
+
+ # Test the analytic option.
+ for method in ['lm', 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, method=method, jac=jac)
+ assert_allclose(popt, [2, 2])
+
+ # Now add an outlier and provide sigma.
+ ydata[5] = 100
+ sigma = np.ones(xdata.shape[0])
+ sigma[5] = 200
+ for method in ['lm', 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, sigma=sigma, method=method,
+ jac=jac)
+ # Still the optimization process is influenced somehow,
+ # have to set rtol=1e-3.
+ assert_allclose(popt, [2, 2], rtol=1e-3)
+
+ def test_maxfev_and_bounds(self):
+ # gh-6340: with no bounds, curve_fit accepts parameter maxfev (via leastsq)
+ # but with bounds, the parameter is `max_nfev` (via least_squares)
+ x = np.arange(0, 10)
+ y = 2*x
+ popt1, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), maxfev=100)
+ popt2, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), max_nfev=100)
+
+ assert_allclose(popt1, 2, atol=1e-14)
+ assert_allclose(popt2, 2, atol=1e-14)
+
+ @pytest.mark.parametrize("sigma_dim", [0, 1, 2])
+ def test_curvefit_omitnan(self, sigma_dim):
+ def exponential(x, a, b):
+ return b * np.exp(a * x)
+
+ rng = np.random.default_rng(578285731148908)
+ N = 100
+ x = np.linspace(1, 10, N)
+ y = exponential(x, 0.2, 0.5)
+
+ if (sigma_dim == 0):
+ sigma = 0.05
+ y += rng.normal(0, sigma, N)
+
+ elif (sigma_dim == 1):
+ sigma = x * 0.05
+ y += rng.normal(0, sigma, N)
+
+ elif (sigma_dim == 2):
+ # The covariance matrix must be symmetric positive-semidefinite
+ a = rng.normal(0, 2, (N, N))
+ sigma = a @ a.T
+ y += rng.multivariate_normal(np.zeros_like(x), sigma)
+ else:
+ assert False, "The sigma must be a scalar, 1D array or 2D array."
+
+ p0 = [0.1, 1.0]
+
+ # Choose indices to place NaNs.
+ i_x = rng.integers(N, size=5)
+ i_y = rng.integers(N, size=5)
+
+ # Add NaNs and compute result using `curve_fit`
+ x[i_x] = np.nan
+ y[i_y] = np.nan
+ res_opt, res_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma,
+ nan_policy="omit")
+
+ # Manually remove elements that should be eliminated, and
+ # calculate reference using `curve_fit`
+ i_delete = np.unique(np.concatenate((i_x, i_y)))
+ x = np.delete(x, i_delete, axis=0)
+ y = np.delete(y, i_delete, axis=0)
+
+ sigma = np.asarray(sigma)
+ if sigma.ndim == 1:
+ sigma = np.delete(sigma, i_delete)
+ elif sigma.ndim == 2:
+ sigma = np.delete(sigma, i_delete, axis=0)
+ sigma = np.delete(sigma, i_delete, axis=1)
+ ref_opt, ref_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma)
+
+ assert_allclose(res_opt, ref_opt, atol=1e-14)
+ assert_allclose(res_cov, ref_cov, atol=1e-14)
+
+ def test_curvefit_simplecovariance(self):
+
+ def func(x, a, b):
+ return a * np.exp(-b*x)
+
+ def jac(x, a, b):
+ e = np.exp(-b*x)
+ return np.vstack((e, -a * x * e)).T
+
+ rng = np.random.default_rng(123)
+ xdata = np.linspace(0, 4, 50)
+ y = func(xdata, 2.5, 1.3)
+ ydata = y + 0.2 * rng.standard_normal(size=len(xdata))
+
+ sigma = np.zeros(len(xdata)) + 0.2
+ covar = np.diag(sigma**2)
+
+ for jac1, jac2 in [(jac, jac), (None, None)]:
+ for absolute_sigma in [False, True]:
+ popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma,
+ jac=jac1, absolute_sigma=absolute_sigma)
+ popt2, pcov2 = curve_fit(func, xdata, ydata, sigma=covar,
+ jac=jac2, absolute_sigma=absolute_sigma)
+
+ assert_allclose(popt1, popt2, atol=1e-14)
+ assert_allclose(pcov1, pcov2, atol=1e-14)
+
+ def test_curvefit_covariance(self):
+
+ def funcp(x, a, b):
+ rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
+ [1./np.sqrt(2), 1./np.sqrt(2), 0],
+ [0, 0, 1.0]])
+ return rotn.dot(a * np.exp(-b*x))
+
+ def jacp(x, a, b):
+ rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
+ [1./np.sqrt(2), 1./np.sqrt(2), 0],
+ [0, 0, 1.0]])
+ e = np.exp(-b*x)
+ return rotn.dot(np.vstack((e, -a * x * e)).T)
+
+ def func(x, a, b):
+ return a * np.exp(-b*x)
+
+ def jac(x, a, b):
+ e = np.exp(-b*x)
+ return np.vstack((e, -a * x * e)).T
+
+ rng = np.random.default_rng(1234)
+ xdata = np.arange(1, 4)
+ y = func(xdata, 2.5, 1.0)
+ ydata = y + 0.2 * rng.standard_normal(size=len(xdata))
+ sigma = np.zeros(len(xdata)) + 0.2
+ covar = np.diag(sigma**2)
+ # Get a rotation matrix, and obtain ydatap = R ydata
+ # Chisq = ydata^T C^{-1} ydata
+ # = ydata^T R^T R C^{-1} R^T R ydata
+ # = ydatap^T Cp^{-1} ydatap
+ # Cp^{-1} = R C^{-1} R^T
+ # Cp = R C R^T, since R^-1 = R^T
+ rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
+ [1./np.sqrt(2), 1./np.sqrt(2), 0],
+ [0, 0, 1.0]])
+ ydatap = rotn.dot(ydata)
+ covarp = rotn.dot(covar).dot(rotn.T)
+
+ for jac1, jac2 in [(jac, jacp), (None, None)]:
+ for absolute_sigma in [False, True]:
+ popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma,
+ jac=jac1, absolute_sigma=absolute_sigma)
+ popt2, pcov2 = curve_fit(funcp, xdata, ydatap, sigma=covarp,
+ jac=jac2, absolute_sigma=absolute_sigma)
+
+ assert_allclose(popt1, popt2, rtol=1.4e-7, atol=1e-14)
+ assert_allclose(pcov1, pcov2, rtol=1.5e-7, atol=1e-14)
+
+ @pytest.mark.parametrize("absolute_sigma", [False, True])
+ def test_curvefit_scalar_sigma(self, absolute_sigma):
+ def func(x, a, b):
+ return a * x + b
+
+ x, y = self.x, self.y
+ _, pcov1 = curve_fit(func, x, y, sigma=2, absolute_sigma=absolute_sigma)
+ # Explicitly building the sigma 1D array
+ _, pcov2 = curve_fit(
+ func, x, y, sigma=np.full_like(y, 2), absolute_sigma=absolute_sigma
+ )
+ assert np.all(pcov1 == pcov2)
+
+ def test_dtypes(self):
+ # regression test for gh-9581: curve_fit fails if x and y dtypes differ
+ x = np.arange(-3, 5)
+ y = 1.5*x + 3.0 + 0.5*np.sin(x)
+
+ def func(x, a, b):
+ return a*x + b
+
+ for method in ['lm', 'trf', 'dogbox']:
+ for dtx in [np.float32, np.float64]:
+ for dty in [np.float32, np.float64]:
+ x = x.astype(dtx)
+ y = y.astype(dty)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", OptimizeWarning)
+ p, cov = curve_fit(func, x, y, method=method)
+
+ assert np.isfinite(cov).all()
+ assert not np.allclose(p, 1) # curve_fit's initial value
+
+ def test_dtypes2(self):
+ # regression test for gh-7117: curve_fit fails if
+ # both inputs are float32
+ def hyperbola(x, s_1, s_2, o_x, o_y, c):
+ b_2 = (s_1 + s_2) / 2
+ b_1 = (s_2 - s_1) / 2
+ return o_y + b_1*(x-o_x) + b_2*np.sqrt((x-o_x)**2 + c**2/4)
+
+ min_fit = np.array([-3.0, 0.0, -2.0, -10.0, 0.0])
+ max_fit = np.array([0.0, 3.0, 3.0, 0.0, 10.0])
+ guess = np.array([-2.5/3.0, 4/3.0, 1.0, -4.0, 0.5])
+
+ params = [-2, .4, -1, -5, 9.5]
+ xdata = np.array([-32, -16, -8, 4, 4, 8, 16, 32])
+ ydata = hyperbola(xdata, *params)
+
+ # run optimization twice, with xdata being float32 and float64
+ popt_64, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess,
+ bounds=(min_fit, max_fit))
+
+ xdata = xdata.astype(np.float32)
+ ydata = hyperbola(xdata, *params)
+
+ popt_32, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess,
+ bounds=(min_fit, max_fit))
+
+ assert_allclose(popt_32, popt_64, atol=2e-5)
+
+ def test_broadcast_y(self):
+ xdata = np.arange(10)
+ rng = np.random.default_rng(123)
+ target = 4.7 * xdata ** 2 + 3.5 * xdata + rng.random(size=len(xdata))
+ def fit_func(x, a, b):
+ return a * x ** 2 + b * x - target
+ for method in ['lm', 'trf', 'dogbox']:
+ popt0, pcov0 = curve_fit(fit_func,
+ xdata=xdata,
+ ydata=np.zeros_like(xdata),
+ method=method)
+ popt1, pcov1 = curve_fit(fit_func,
+ xdata=xdata,
+ ydata=0,
+ method=method)
+ assert_allclose(pcov0, pcov1)
+
+ def test_args_in_kwargs(self):
+ # Ensure that `args` cannot be passed as keyword argument to `curve_fit`
+
+ def func(x, a, b):
+ return a * x + b
+
+ with assert_raises(ValueError):
+ curve_fit(func,
+ xdata=[1, 2, 3, 4],
+ ydata=[5, 9, 13, 17],
+ p0=[1],
+ args=(1,))
+
+ def test_data_point_number_validation(self):
+ def func(x, a, b, c, d, e):
+ return a * np.exp(-b * x) + c + d + e
+
+ with assert_raises(TypeError, match="The number of func parameters="):
+ curve_fit(func,
+ xdata=[1, 2, 3, 4],
+ ydata=[5, 9, 13, 17])
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ def test_gh4555(self):
+ # gh-4555 reported that covariance matrices returned by `leastsq`
+ # can have negative diagonal elements and eigenvalues. (In fact,
+ # they can also be asymmetric.) This shows up in the output of
+ # `scipy.optimize.curve_fit`. Check that it has been resolved.giit
+ def f(x, a, b, c, d, e):
+ return a*np.log(x + 1 + b) + c*np.log(x + 1 + d) + e
+
+ rng = np.random.default_rng(408113519974467917)
+ n = 100
+ x = np.arange(n)
+ y = np.linspace(2, 7, n) + rng.random(n)
+ p, cov = optimize.curve_fit(f, x, y, maxfev=100000)
+ assert np.all(np.diag(cov) > 0)
+ eigs = linalg.eigh(cov)[0] # separate line for debugging
+ # some platforms see a small negative eigevenvalue
+ assert np.all(eigs > -1e-2)
+ assert_allclose(cov, cov.T)
+
+ def test_gh4555b(self):
+ # check that PR gh-17247 did not significantly change covariance matrix
+ # for simple cases
+ rng = np.random.default_rng(408113519974467917)
+
+ def func(x, a, b, c):
+ return a * np.exp(-b * x) + c
+
+ xdata = np.linspace(0, 4, 50)
+ y = func(xdata, 2.5, 1.3, 0.5)
+ y_noise = 0.2 * rng.normal(size=xdata.size)
+ ydata = y + y_noise
+ _, res = curve_fit(func, xdata, ydata)
+ # reference from commit 1d80a2f254380d2b45733258ca42eb6b55c8755b
+ ref = [[+0.0158972536486215, 0.0069207183284242, -0.0007474400714749],
+ [+0.0069207183284242, 0.0205057958128679, +0.0053997711275403],
+ [-0.0007474400714749, 0.0053997711275403, +0.0027833930320877]]
+ # Linux_Python_38_32bit_full fails with default tolerance
+ assert_allclose(res, ref, 2e-7)
+
+ def test_gh13670(self):
+ # gh-13670 reported that `curve_fit` executes callables
+ # with the same values of the parameters at the beginning of
+ # optimization. Check that this has been resolved.
+
+ rng = np.random.default_rng(8250058582555444926)
+ x = np.linspace(0, 3, 101)
+ y = 2 * x + 1 + rng.normal(size=101) * 0.5
+
+ def line(x, *p):
+ assert not np.all(line.last_p == p)
+ line.last_p = p
+ return x * p[0] + p[1]
+
+ def jac(x, *p):
+ assert not np.all(jac.last_p == p)
+ jac.last_p = p
+ return np.array([x, np.ones_like(x)]).T
+
+ line.last_p = None
+ jac.last_p = None
+ p0 = np.array([1.0, 5.0])
+ curve_fit(line, x, y, p0, method='lm', jac=jac)
+
+ @pytest.mark.parametrize('method', ['trf', 'dogbox'])
+ def test_gh20155_error_mentions_x0(self, method):
+ # `curve_fit` produced an error message that referred to an undocumented
+ # variable `x0`, which was really `p0`. Check that this is resolved.
+ def func(x,a):
+ return x**a
+ message = "Initial guess is outside of provided bounds"
+ with pytest.raises(ValueError, match=message):
+ curve_fit(func, self.x, self.y, p0=[1], bounds=(1000, 1001),
+ method=method)
+
+
+class TestFixedPoint:
+
+ def test_scalar_trivial(self):
+ # f(x) = 2x; fixed point should be x=0
+ def func(x):
+ return 2.0*x
+ x0 = 1.0
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, 0.0)
+
+ def test_scalar_basic1(self):
+ # f(x) = x**2; x0=1.05; fixed point should be x=1
+ def func(x):
+ return x**2
+ x0 = 1.05
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, 1.0)
+
+ def test_scalar_basic2(self):
+ # f(x) = x**0.5; x0=1.05; fixed point should be x=1
+ def func(x):
+ return x**0.5
+ x0 = 1.05
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, 1.0)
+
+ def test_array_trivial(self):
+ def func(x):
+ return 2.0*x
+ x0 = [0.3, 0.15]
+ with np.errstate(all='ignore'):
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, [0.0, 0.0])
+
+ def test_array_basic1(self):
+ # f(x) = c * x**2; fixed point should be x=1/c
+ def func(x, c):
+ return c * x**2
+ c = array([0.75, 1.0, 1.25])
+ x0 = [1.1, 1.15, 0.9]
+ with np.errstate(all='ignore'):
+ x = fixed_point(func, x0, args=(c,))
+ assert_almost_equal(x, 1.0/c)
+
+ def test_array_basic2(self):
+ # f(x) = c * x**0.5; fixed point should be x=c**2
+ def func(x, c):
+ return c * x**0.5
+ c = array([0.75, 1.0, 1.25])
+ x0 = [0.8, 1.1, 1.1]
+ x = fixed_point(func, x0, args=(c,))
+ assert_almost_equal(x, c**2)
+
+ def test_lambertw(self):
+ # python-list/2010-December/594592.html
+ xxroot = fixed_point(lambda xx: np.exp(-2.0*xx)/2.0, 1.0,
+ args=(), xtol=1e-12, maxiter=500)
+ assert_allclose(xxroot, np.exp(-2.0*xxroot)/2.0)
+ assert_allclose(xxroot, lambertw(1)/2)
+
+ def test_no_acceleration(self):
+ # GitHub issue 5460
+ ks = 2
+ kl = 6
+ m = 1.3
+ n0 = 1.001
+ i0 = ((m-1)/m)*(kl/ks/m)**(1/(m-1))
+
+ def func(n):
+ return np.log(kl/ks/n) / np.log(i0*n/(n - 1)) + 1
+
+ n = fixed_point(func, n0, method='iteration')
+ assert_allclose(n, m)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_nnls.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..e969dafcbfc9670980969373e043487245e5a78a
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_nnls.py
@@ -0,0 +1,468 @@
+import numpy as np
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+from scipy.optimize import nnls
+import pytest
+
+
+class TestNNLS:
+ def setup_method(self):
+ self.rng = np.random.default_rng(1685225766635251)
+
+ def test_nnls(self):
+ a = np.arange(25.0).reshape(-1, 5)
+ x = np.arange(5.0)
+ y = a @ x
+ x, res = nnls(a, y)
+ assert res < 1e-7
+ assert np.linalg.norm((a @ x) - y) < 1e-7
+
+ def test_nnls_empty(self):
+ a = np.zeros((2, 0))
+ y = np.ones((2,))
+ x, res = nnls(a, y)
+ assert res == np.linalg.norm(y)
+ assert x.size == 0
+
+ def test_nnls_tall(self):
+ a = self.rng.uniform(low=-10, high=10, size=[50, 10])
+ x = np.abs(self.rng.uniform(low=-2, high=2, size=[10]))
+ x[::2] = 0
+ b = a @ x
+ xact, rnorm = nnls(a, b)
+ assert_allclose(xact, x, rtol=0., atol=1e-10)
+ assert rnorm < 1e-12
+
+ def test_nnls_wide(self):
+ # If too wide then problem becomes too ill-conditioned ans starts
+ # emitting warnings, hence small m, n difference.
+ a = self.rng.uniform(low=-10, high=10, size=[100, 120])
+ x = np.abs(self.rng.uniform(low=-2, high=2, size=[120]))
+ x[::2] = 0
+ b = a @ x
+ xact, rnorm = nnls(a, b)
+ assert_allclose(xact, x, rtol=0., atol=1e-10)
+ assert rnorm < 1e-12
+
+ def test_maxiter(self):
+ # test that maxiter argument does stop iterations
+ a = self.rng.uniform(size=(5, 10))
+ b = self.rng.uniform(size=5)
+ with assert_raises(RuntimeError):
+ nnls(a, b, maxiter=1)
+
+ def test_nnls_inner_loop_case1(self):
+ # See gh-20168
+ n = np.array(
+ [3, 2, 0, 1, 1, 1, 3, 8, 14, 16, 29, 23, 41, 47, 53, 57, 67, 76,
+ 103, 89, 97, 94, 85, 95, 78, 78, 78, 77, 73, 50, 50, 56, 68, 98,
+ 95, 112, 134, 145, 158, 172, 213, 234, 222, 215, 216, 216, 206,
+ 183, 135, 156, 110, 92, 63, 60, 52, 29, 20, 16, 12, 5, 5, 5, 1, 2,
+ 3, 0, 2])
+ k = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0.7205812007860187, 0., 1.4411624015720375,
+ 0.7205812007860187, 2.882324803144075, 5.76464960628815,
+ 5.76464960628815, 12.249880413362318, 15.132205216506394,
+ 20.176273622008523, 27.382085629868712, 48.27894045266326,
+ 47.558359251877235, 68.45521407467177, 97.99904330689854,
+ 108.0871801179028, 135.46926574777152, 140.51333415327366,
+ 184.4687874012208, 171.49832578707245, 205.36564222401535,
+ 244.27702706646033, 214.01261663344755, 228.42424064916793,
+ 232.02714665309804, 205.36564222401535, 172.9394881886445,
+ 191.67459940908097, 162.1307701768542, 153.48379576742198,
+ 110.96950492104689, 103.04311171240067, 86.46974409432225,
+ 60.528820866025576, 43.234872047161126, 23.779179625938617,
+ 24.499760826724636, 17.29394881886445, 11.5292992125763,
+ 5.76464960628815, 5.044068405502131, 3.6029060039300935, 0.,
+ 2.882324803144075, 0., 0., 0.])
+ d = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0.003889242101538, 0., 0.007606268390096, 0.,
+ 0.025457371599973, 0.036952882091577, 0., 0.08518359183449,
+ 0.048201126400243, 0.196234990022205, 0.144116240157247,
+ 0.171145134062442, 0., 0., 0.269555036538714, 0., 0., 0.,
+ 0.010893241091872, 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0.048167058272886, 0.011238724891049, 0., 0., 0.055162603456078,
+ 0., 0., 0., 0., 0.027753339088588, 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0.])
+ # The following code sets up a system of equations such that
+ # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and
+ # monotonicity constraints on $p_i$. This translates to a system of
+ # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and
+ # non-negativity constraints on the $d_i$. If $n_i$ is zero the
+ # system is modified such that $d_i - d_{i+1}$ is then minimized.
+ N = len(n)
+ A = np.diag(n) @ np.tril(np.ones((N, N)))
+ w = n ** 0.5
+
+ nz = (n == 0).nonzero()[0]
+ A[nz, nz] = 1
+ A[nz, np.minimum(nz + 1, N - 1)] = -1
+ w[nz] = 1
+ k[nz] = 0
+ W = np.diag(w)
+
+ # Small perturbations can already make the infinite loop go away (just
+ # uncomment the next line)
+ # k = k + 1e-10 * np.random.normal(size=N)
+ dact, _ = nnls(W @ A, W @ k)
+ assert_allclose(dact, d, rtol=0., atol=1e-10)
+
+ def test_nnls_inner_loop_case2(self):
+ # See gh-20168
+ n = np.array(
+ [1, 0, 1, 2, 2, 2, 3, 3, 5, 4, 14, 14, 19, 26, 36, 42, 36, 64, 64,
+ 64, 81, 85, 85, 95, 95, 95, 75, 76, 69, 81, 62, 59, 68, 64, 71, 67,
+ 74, 78, 118, 135, 153, 159, 210, 195, 218, 243, 236, 215, 196, 175,
+ 185, 149, 144, 103, 104, 75, 56, 40, 32, 26, 17, 9, 12, 8, 2, 1, 1,
+ 1])
+ k = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0.7064355064917867, 0., 0., 2.11930651947536,
+ 0.7064355064917867, 0., 3.5321775324589333, 7.064355064917867,
+ 11.302968103868587, 16.95445215580288, 20.486629688261814,
+ 20.486629688261814, 37.44108184406469, 55.808405012851146,
+ 78.41434122058831, 103.13958394780086, 105.965325973768,
+ 125.74552015553803, 149.057891869767, 176.60887662294667,
+ 197.09550631120848, 211.930651947536, 204.86629688261814,
+ 233.8301526487814, 221.1143135319292, 195.6826352982249,
+ 197.80194181770025, 191.4440222592742, 187.91184472681525,
+ 144.11284332432447, 131.39700420747232, 116.5618585711448,
+ 93.24948685691584, 89.01087381796512, 53.68909849337579,
+ 45.211872415474346, 31.083162285638615, 24.72524272721253,
+ 16.95445215580288, 9.890097090885014, 9.890097090885014,
+ 2.8257420259671466, 2.8257420259671466, 1.4128710129835733,
+ 0.7064355064917867, 1.4128710129835733])
+ d = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0.0021916146355674473, 0., 0.,
+ 0.011252740799789484, 0., 0., 0.037746623295934395,
+ 0.03602328132946222, 0.09509167709829734, 0.10505765870204821,
+ 0.01391037014274718, 0.0188296228752321, 0.20723559202324254,
+ 0.3056220879462608, 0.13304643490426477, 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0.043185876949706214, 0.0037266261379722554,
+ 0., 0., 0., 0., 0., 0.094797899357143, 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0.23450935613672663, 0., 0., 0.07064355064917871])
+ # The following code sets up a system of equations such that
+ # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and
+ # monotonicity constraints on $p_i$. This translates to a system of
+ # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and
+ # non-negativity constraints on the $d_i$. If $n_i$ is zero the
+ # system is modified such that $d_i - d_{i+1}$ is then minimized.
+ N = len(n)
+ A = np.diag(n) @ np.tril(np.ones((N, N)))
+ w = n ** 0.5
+
+ nz = (n == 0).nonzero()[0]
+ A[nz, nz] = 1
+ A[nz, np.minimum(nz + 1, N - 1)] = -1
+ w[nz] = 1
+ k[nz] = 0
+ W = np.diag(w)
+
+ dact, _ = nnls(W @ A, W @ k)
+
+ p = np.cumsum(dact)
+ assert np.all(dact >= 0)
+ assert np.linalg.norm(k - n * p, ord=np.inf) < 28
+ assert_allclose(dact, d, rtol=0., atol=1e-10)
+
+ def test_nnls_gh20302(self):
+ # See gh-20302
+ A = np.array(
+ [0.33408569134321575, 0.11136189711440525, 0.049140798007949286,
+ 0.03712063237146841, 0.055680948557202625, 0.16642814595936478,
+ 0.11095209730624318, 0.09791993030943345, 0.14793612974165757,
+ 0.44380838922497273, 0.11099502671044059, 0.11099502671044059,
+ 0.14693672599330593, 0.3329850801313218, 1.498432860590948,
+ 0.0832374225132955, 0.11098323001772734, 0.19589481249472837,
+ 0.5919105600945457, 3.5514633605672747, 0.06658716751427037,
+ 0.11097861252378394, 0.24485832778293645, 0.9248217710315328,
+ 6.936163282736496, 0.05547609388181014, 0.11095218776362029,
+ 0.29376003042571264, 1.3314262531634435, 11.982836278470993,
+ 0.047506113282944136, 0.11084759766020298, 0.3423969672933396,
+ 1.8105107617833156, 19.010362998724812, 0.041507335004505576,
+ 0.11068622667868154, 0.39074115283013344, 2.361306169145206,
+ 28.335674029742474, 0.03682846280947718, 0.11048538842843154,
+ 0.4387861797121048, 2.9831054875676517, 40.2719240821633,
+ 0.03311278164362387, 0.11037593881207958, 0.4870572300443105,
+ 3.6791979604026523, 55.187969406039784, 0.030079304092299915,
+ 0.11029078167176636, 0.5353496017200152, 4.448394860761242,
+ 73.3985152025605, 0.02545939709595835, 0.11032405408248619,
+ 0.6328767609778363, 6.214921713313388, 121.19097340961108,
+ 0.022080881724881523, 0.11040440862440762, 0.7307742886903428,
+ 8.28033064683057, 186.30743955368786, 0.020715838214945492,
+ 0.1104844704797093, 0.7800578384588346, 9.42800814760186,
+ 226.27219554244465, 0.01843179728340054, 0.11059078370040323,
+ 0.8784095015912599, 11.94380463964355, 322.48272527037585,
+ 0.015812787653789077, 0.11068951357652354, 1.0257259848595766,
+ 16.27135849574896, 512.5477926160922, 0.014438550529330062,
+ 0.11069555405819713, 1.1234754801775881, 19.519316032262093,
+ 673.4164031130423, 0.012760770585072577, 0.110593345070629,
+ 1.2688431112524712, 24.920367089248398, 971.8943164806875,
+ 0.011427556646114315, 0.11046638091243838, 1.413623342459821,
+ 30.967408782453557, 1347.0822820367298, 0.010033330264470307,
+ 0.11036663290917338, 1.6071533470570285, 40.063087746029936,
+ 1983.122843428482, 0.008950061496507258, 0.11038409179025618,
+ 1.802244865119193, 50.37194055362024, 2795.642700725923,
+ 0.008071078821135658, 0.11030474388885401, 1.9956465761433504,
+ 61.80742482572119, 3801.1566267818534, 0.007191031207777556,
+ 0.11026247851925586, 2.238160187262168, 77.7718015155818,
+ 5366.2543045751445, 0.00636834224248, 0.11038459886965334,
+ 2.5328963107984297, 99.49331844784753, 7760.4788389321075,
+ 0.005624259098118485, 0.11061042892966355, 2.879742607664547,
+ 128.34496770138628, 11358.529641572684, 0.0050354270614989555,
+ 0.11077939535297703, 3.2263279459292575, 160.85168205252265,
+ 15924.316523199741, 0.0044997853165982555, 0.1109947044760903,
+ 3.6244287189055613, 202.60233390369015, 22488.859063309606,
+ 0.004023601950058174, 0.1113196539516095, 4.07713905729421,
+ 255.6270320242126, 31825.565487014468, 0.0036024117873727094,
+ 0.111674765408554, 4.582933773135057, 321.9583486728612,
+ 44913.18963986413, 0.003201503089582304, 0.11205260813538065,
+ 5.191786833370116, 411.79333489752383, 64857.45024636,
+ 0.0028633044552448853, 0.11262330857296549, 5.864295861648949,
+ 522.7223161899905, 92521.84996562831, 0.0025691897303891965,
+ 0.11304434813712465, 6.584584405106342, 656.5615739804199,
+ 129999.19164812315, 0.0022992911894424675, 0.11343169867916175,
+ 7.4080129906658305, 828.2026426227864, 183860.98666225857,
+ 0.0020449922071108764, 0.11383789952917212, 8.388975556433872,
+ 1058.2750599896935, 265097.9025274183, 0.001831274615120854,
+ 0.11414945100919989, 9.419351803810935, 1330.564050780237,
+ 373223.2162438565, 0.0016363333454631633, 0.11454333418242145,
+ 10.6143816579462, 1683.787012481595, 530392.9089317025,
+ 0.0014598610433380044, 0.11484240207592301, 11.959688127956882,
+ 2132.0874753402027, 754758.9662704318, 0.0012985240015312626,
+ 0.11513579480243862, 13.514425358573531, 2715.5160990137824,
+ 1083490.9235064993, 0.0011614735761289934, 0.11537304189548002,
+ 15.171418602667567, 3415.195870828736, 1526592.554260445,
+ 0.0010347472698811352, 0.11554677847006009, 17.080800985009617,
+ 4322.412404600832, 2172012.2333119176, 0.0009232988811258664,
+ 0.1157201264344419, 19.20004861829407, 5453.349531598553,
+ 3075689.135821584, 0.0008228871862975205, 0.11602709326795038,
+ 21.65735242414206, 6920.203923780365, 4390869.389638642,
+ 0.00073528900066722, 0.11642075843897651, 24.40223571298994,
+ 8755.811207598026, 6238515.485413593, 0.0006602764384729194,
+ 0.11752920604817965, 27.694443541914293, 11171.386093291572,
+ 8948280.260726549, 0.0005935538977939806, 0.11851292825953147,
+ 31.325508920763063, 14174.185724149384, 12735505.873148222,
+ 0.0005310755355633124, 0.11913794514470308, 35.381052949627765,
+ 17987.010118815077, 18157886.71494382, 0.00047239949671590953,
+ 0.1190446731724092, 39.71342528048061, 22679.438775422022,
+ 25718483.571328573, 0.00041829129789387623, 0.11851586773659825,
+ 44.45299332965028, 28542.57147989741, 36391778.63686921,
+ 0.00037321512015419886, 0.11880681324908665, 50.0668539579632,
+ 36118.26128449941, 51739409.29004541, 0.0003315539616702064,
+ 0.1184752823034871, 56.04387059062639, 45383.29960621684,
+ 72976345.76679668, 0.00029456064937920213, 0.11831519416731286,
+ 62.91195073220101, 57265.53993693082, 103507463.43600245,
+ 0.00026301867496859703, 0.11862142241083726, 70.8217262087034,
+ 72383.14781936012, 146901598.49939138, 0.00023618734450420032,
+ 0.11966825454879482, 80.26535457124461, 92160.51176984518,
+ 210125966.835247, 0.00021165918071578316, 0.12043407382728061,
+ 90.7169587544247, 116975.56852918258, 299515943.218972,
+ 0.00018757727511329545, 0.11992440455576689, 101.49899864101785,
+ 147056.26174166967, 423080865.0307836, 0.00016654469159895833,
+ 0.11957908856805206, 113.65970431102812, 184937.67016486943,
+ 597533612.3026931, 0.00014717439179415048, 0.11872067604728138,
+ 126.77899683346702, 231758.58906776624, 841283678.3159915,
+ 0.00012868496382376066, 0.1166314722122684, 139.93635237349534,
+ 287417.30847929465, 1172231492.6328032, 0.00011225559452625302,
+ 0.11427619522772557, 154.0034283704458, 355281.4912295324,
+ 1627544511.322488, 9.879511142981067e-05, 0.11295574406808354,
+ 170.96532050841535, 442971.0111288653, 2279085852.2580123,
+ 8.71257780313587e-05, 0.11192758284428547, 190.35067416684697,
+ 554165.2523674504, 3203629323.93623, 7.665069027765277e-05,
+ 0.11060694607065294, 211.28835951100046, 690933.608546013,
+ 4486577387.093535, 6.734021094824451e-05, 0.10915848194710433,
+ 234.24338803525194, 860487.9079859136, 6276829044.8032465,
+ 5.9191625040287665e-05, 0.10776821865668373, 259.7454711820425,
+ 1071699.0387579766, 8780430224.544102, 5.1856803674907676e-05,
+ 0.10606444911641115, 287.1843540288165, 1331126.3723998806,
+ 12251687131.5685, 4.503421404759231e-05, 0.10347361247668461,
+ 314.7338642485931, 1638796.0697522392, 16944331963.203278,
+ 3.90470387455642e-05, 0.1007804070023012, 344.3427560918527,
+ 2014064.4865519698, 23392351979.057854, 3.46557661636393e-05,
+ 0.10046706610839032, 385.56603915081587, 2533036.2523656,
+ 33044724430.235435, 3.148745865254635e-05, 0.1025441570117926,
+ 442.09038234164746, 3262712.3882769793, 47815050050.199135,
+ 2.9790762078715404e-05, 0.1089845379379672, 527.8068231298969,
+ 4375751.903321453, 72035815708.42941, 2.8772639817606534e-05,
+ 0.11823636789048445, 643.2048194503195, 5989838.001888927,
+ 110764084330.93005, 2.7951691815106586e-05, 0.12903432664913705,
+ 788.5500418523591, 8249371.000613411, 171368308481.2427,
+ 2.6844392423114212e-05, 0.1392060709754626, 955.6296403631383,
+ 11230229.319931043, 262063016295.25085, 2.499458273851386e-05,
+ 0.14559344445184325, 1122.7022399726002, 14820229.698461473,
+ 388475270970.9214, 2.337386729019776e-05, 0.15294300496886065,
+ 1324.8158105672455, 19644861.137128454, 578442936182.7473,
+ 2.0081014872174113e-05, 0.14760215298210377, 1436.2385042492353,
+ 23923681.729276657, 791311658718.4193, 1.773374462991839e-05,
+ 0.14642752940923615, 1600.5596278736678, 29949429.82503553,
+ 1112815989293.9326, 1.5303115839590797e-05, 0.14194150045081785,
+ 1742.873058605698, 36634451.931305364, 1529085389160.7544,
+ 1.3148448731163076e-05, 0.13699368732998807, 1889.5284359054356,
+ 44614279.74469635, 2091762812969.9607, 1.1739194407590062e-05,
+ 0.13739553134643406, 2128.794599579694, 56462810.11822766,
+ 2973783283306.8145, 1.0293367506254706e-05, 0.13533033372723272,
+ 2355.372854690074, 70176508.28667311, 4151852759764.441,
+ 9.678312586863569e-06, 0.14293577249119244, 2794.531827932675,
+ 93528671.31952812, 6215821967224.52, -1.174086323572049e-05,
+ 0.1429501325944908, 3139.4804810720925, 118031680.16618933,
+ -6466892421886.174, -2.1188265307407812e-05, 0.1477108290912869,
+ 3644.1133424610953, 153900132.62392554, -4828013117542.036,
+ -8.614483025123122e-05, 0.16037100755883044, 4444.386620899393,
+ 210846007.89660168, -1766340937974.433, 4.981445776141726e-05,
+ 0.16053420251962536, 4997.558254401547, 266327328.4755411,
+ 3862250287024.725, 1.8500019169456637e-05, 0.15448417164977674,
+ 5402.289867444643, 323399508.1475582, 12152445411933.408,
+ -5.647882376069748e-05, 0.1406372975946189, 5524.633133597753,
+ 371512945.9909363, -4162951345292.1514, 2.8048523486337994e-05,
+ 0.13183417571186926, 5817.462495763679, 439447252.3728975,
+ 9294740538175.03]).reshape(89, 5)
+ b = np.ones(89, dtype=np.float64)
+ sol, rnorm = nnls(A, b)
+ assert_allclose(sol, np.array([0.61124315, 8.22262829, 0., 0., 0.]))
+ assert_allclose(rnorm, 1.0556460808977297)
+
+ def test_nnls_gh21021_ex1(self):
+ # Review examples used in gh-21021
+ A = [[0.004734199143798789, -0.09661916455815653, -0.04308779048103441,
+ 0.4039475561867938, -0.27742598780954364, -0.20816924034369574,
+ -0.17264070902176, 0.05251808558963846],
+ [-0.030263548855047975, -0.30356483926431466, 0.18080406600591398,
+ -0.06892233941254086, -0.41837298885432317, 0.30245352819647003,
+ -0.19008975278116397, -0.00990809825429995],
+ [-0.2561747595787612, -0.04376282125249583, 0.4422181991706678,
+ -0.13720906318924858, -0.0069523811763796475, -0.059238287107464795,
+ 0.028663214369642594, 0.5415531284893763],
+ [0.2949336072968401, 0.33997647534935094, 0.38441519339815755,
+ -0.306001783010386, 0.18120773805949028, -0.36669767490747895,
+ -0.021539960590992304, -0.2784251712424615],
+ [0.5009075736232653, -0.20161970347571165, 0.08404512586550646,
+ 0.2520496489348788, 0.14812015101612894, -0.25823455803981266,
+ -0.1596872058396596, 0.5960141613922691]
+ ]
+ b = [18.036779281222124, -18.126530733870887, 13.535652034584029,
+ -2.6654275476795966, 9.166315328199575]
+
+ # Obtained from matlab's lstnonneg
+ des_sol = np.array([0., 118.017802006619, 45.1996532316584, 102.62156313537,
+ 0., 55.8590204314398, 0., 29.7328833253434])
+ sol, res = nnls(A, b)
+ assert_allclose(sol, des_sol)
+ assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14
+
+ def test_nnls_gh21021_ex2(self):
+ A = np.array([
+ [0.2508259992635229, -0.24031300195203256],
+ [0.510647748500133, 0.2872936081767836],
+ [0.8196387904102849, -0.03520620107046682],
+ [0.030739759120097084, -0.07768656359879388]])
+ b = np.array([24.456141951303913,
+ 28.047143273432333,
+ 41.10526799545987,
+ -1.2078282698324068])
+
+ sol, res = nnls(A, b)
+ assert_allclose(sol, np.array([54.3047953202271, 0.0]))
+ assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14
+
+ def test_nnls_gh21021_ex3(self):
+ A = np.array([
+ [0.08247592017366788, 0.058398241636675674, -0.1031496693415968,
+ 0.03156983127072098, -0.029503680182026665],
+ [0.21463607509982277, -0.2164518969308173, -0.10816833396662294,
+ 0.12133867146012027, -0.15025010408668332],
+ [0.07251900316494089, -0.003044559315020767, 0.042682817961676424,
+ -0.018157525489298176, 0.11561953260568134],
+ [0.2328797918159187, -0.09112909645892767, 0.21348169727099078,
+ 0.00449447624089599, -0.16615256386885716],
+ [-0.02440856024843897, -0.20131427208575386, 0.030275781997161483,
+ -0.04560777213546784, 0.11007266012013553],
+ [-0.2928391429686263, -0.20437574856615687, -0.020892110811574407,
+ -0.10455040720819309, 0.05337267000160461],
+ [0.22041503019400316, 0.014262782992311842, 0.08274606359871121,
+ -0.17933172096518907, -0.11809690350702161],
+ [0.10440436007469953, 0.09171452270577712, 0.03942347724809893,
+ 0.11457669688231396, 0.07529747295631585],
+ [-0.052087576116032056, -0.15787717158077047, -0.08232202515883282,
+ -0.03194837933710708, -0.0546812506025729],
+ [-0.010388407673304468, 0.015174707581808923, 0.04764509565386281,
+ -0.1781221936030805, 0.10218894080536609],
+ [0.03272263140115928, -0.27576456949442574, 0.024897570959901753,
+ -0.1417129166632282, -0.03320796462136591],
+ [-0.12490006751823997, -0.03012003515442302, -0.051495264012509506,
+ 0.012070729698374614, 0.04811700123118234],
+ [0.15254854117990788, -0.051863547789218374, 0.058012914127346174,
+ -0.06717991061422621, -0.14514671564242257],
+ [0.12251250415395559, -0.17462495626695362, -0.025334728552179834,
+ 0.11425350676877533, 0.06183915953812639],
+ [0.19334259720491218, 0.2164301986218955, -0.018882278726614483,
+ 0.07950236716817938, -0.2220529357431092],
+ [-0.01822205701890852, 0.12630444976752267, -0.03118092027244001,
+ 0.02773743885242581, 0.06444433740044248],
+ [0.13344116850581977, -0.05142877469996826, 0.3385702016705455,
+ -0.25814970787123004, 0.2679034842977378],
+ [0.1309747058619377, 0.12090608957940627, -0.13957978654106512,
+ 0.17048819760322642, -0.241775259969348],
+ [0.28613102173467275, -0.47153463906732174, 0.20359970518269746,
+ -0.0962095202871843, -0.07703076550836387],
+ [0.2212788380372723, 0.02569245145758152, -0.021596152392209966,
+ 0.04610005150029433, -0.2024454395619734],
+ [-0.043225338359410316, 0.17816095186290315, -0.014709092962616079,
+ 0.06993970293287989, -0.09033722782555903],
+ [0.17747622942563512, -0.20991014784011458, 0.06265720409894943,
+ 0.0689704059061795, 0.024474319398401525],
+ [-0.1163880385601698, 0.29989570587630027, 0.033443765320984545,
+ 0.008470296514656, -0.0014457113271462002],
+ [0.024375314902718406, 0.05279830705548363, 0.02691082431023144,
+ 0.05265079368002343, 0.15542988147487913],
+ [-0.01855218360922308, -0.050265869142888164, 0.2567912677240452,
+ -0.2606428528561333, 0.25334396245022245]])
+
+ b = np.array([-7.876625373734849, -8.259856278691373, 3.2593082374900963,
+ 16.30170376973345, 2.311892943629045, -1.595345202555738,
+ 6.318582970536518, 3.0104212955340093, -6.286202915842167,
+ 3.6382333725029294, 1.9012066681249356, -3.932236581436514,
+ 4.4299317131740406, -1.9345885161292682, -1.4418721521970805,
+ -2.3810103256943926, 25.853603392922526, -10.658470311610483,
+ 15.547103681119214, -1.6491066136547277, -1.1232029689817422,
+ 4.7845749463206975, 2.553803732013229, 2.0549409701753705,
+ 19.60887153608244])
+
+ sol, res = nnls(A, b)
+ assert_allclose(sol, np.array([0.0, 0.0, 76.3611306173957, 0.0, 0.0]),
+ atol=5e-14)
+ assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14
+
+ def test_2D_singleton_RHS_input(self):
+ # Test that a 2D singleton RHS input is accepted
+ A = np.array([[1.0, 0.5, -1.],
+ [1.0, 0.5, 0.0],
+ [-1., 0.0, 1.0]])
+ b = np.array([[-1.0, 2.0, 2.0]]).T
+ x, r = nnls(A, b)
+ assert_allclose(x, np.array([1.0, 2.0, 3.0]))
+ assert_allclose(r, 0.0)
+
+ def test_2D_not_singleton_RHS_input_2(self):
+ # Test that a 2D but not a column vector RHS input is rejected
+ A = np.array([[1.0, 0.5, -1.],
+ [1.0, 0.5, 0.0],
+ [1.0, 0.5, 0.0],
+ [0.0, 0.0, 1.0]])
+ b = np.ones(shape=[4, 2], dtype=np.float64)
+ with pytest.raises(ValueError, match="Expected a 1D array"):
+ nnls(A, b)
+
+ def test_gh_22791_32bit(self):
+ # Scikit-learn got hit by this problem on 32-bit arch.
+ desired = [0, 0, 1.05617285, 0, 0, 0, 0, 0.23123048, 0, 0, 0, 0.26128651]
+ rng = np.random.RandomState(42)
+ n_samples, n_features = 5, 12
+ X = rng.randn(n_samples, n_features)
+ X[:2, :] = 0
+ y = rng.randn(n_samples)
+ coef, _ = nnls(X, y)
+ assert_allclose(coef, desired)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_nonlin.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cfc3a284ce3a3cfad81f447e72199a80f4fc572
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_nonlin.py
@@ -0,0 +1,571 @@
+""" Unit tests for nonlinear solvers
+Author: Ondrej Certik
+May 2007
+"""
+from numpy.testing import assert_
+import pytest
+from functools import partial
+
+from scipy.optimize import _nonlin as nonlin, root
+from scipy.sparse import csr_array
+from numpy import diag, dot
+from numpy.linalg import inv
+import numpy as np
+import scipy
+from scipy.sparse.linalg import minres
+
+from .test_minpack import pressure_network
+
+SOLVERS = {'anderson': nonlin.anderson,
+ 'diagbroyden': nonlin.diagbroyden,
+ 'linearmixing': nonlin.linearmixing,
+ 'excitingmixing': nonlin.excitingmixing,
+ 'broyden1': nonlin.broyden1,
+ 'broyden2': nonlin.broyden2,
+ 'krylov': nonlin.newton_krylov}
+MUST_WORK = {'anderson': nonlin.anderson, 'broyden1': nonlin.broyden1,
+ 'broyden2': nonlin.broyden2, 'krylov': nonlin.newton_krylov}
+
+# ----------------------------------------------------------------------------
+# Test problems
+# ----------------------------------------------------------------------------
+
+
+def F(x):
+ x = np.asarray(x).T
+ d = diag([3, 2, 1.5, 1, 0.5])
+ c = 0.01
+ f = -d @ x - c * float(x.T @ x) * x
+ return f
+
+
+F.xin = [1, 1, 1, 1, 1]
+F.KNOWN_BAD = {}
+F.JAC_KSP_BAD = {}
+F.ROOT_JAC_KSP_BAD = {}
+
+
+def F2(x):
+ return x
+
+
+F2.xin = [1, 2, 3, 4, 5, 6]
+F2.KNOWN_BAD = {'linearmixing': nonlin.linearmixing,
+ 'excitingmixing': nonlin.excitingmixing}
+F2.JAC_KSP_BAD = {}
+F2.ROOT_JAC_KSP_BAD = {}
+
+
+def F2_lucky(x):
+ return x
+
+
+F2_lucky.xin = [0, 0, 0, 0, 0, 0]
+F2_lucky.KNOWN_BAD = {}
+F2_lucky.JAC_KSP_BAD = {}
+F2_lucky.ROOT_JAC_KSP_BAD = {}
+
+
+def F3(x):
+ A = np.array([[-2, 1, 0.], [1, -2, 1], [0, 1, -2]])
+ b = np.array([1, 2, 3.])
+ return A @ x - b
+
+
+F3.xin = [1, 2, 3]
+F3.KNOWN_BAD = {}
+F3.JAC_KSP_BAD = {}
+F3.ROOT_JAC_KSP_BAD = {}
+
+
+def F4_powell(x):
+ A = 1e4
+ return [A*x[0]*x[1] - 1, np.exp(-x[0]) + np.exp(-x[1]) - (1 + 1/A)]
+
+
+F4_powell.xin = [-1, -2]
+F4_powell.KNOWN_BAD = {'linearmixing': nonlin.linearmixing,
+ 'excitingmixing': nonlin.excitingmixing,
+ 'diagbroyden': nonlin.diagbroyden}
+# In the extreme case, it does not converge for nolinear problem solved by
+# MINRES and root problem solved by GMRES/BiCGStab/CGS/MINRES/TFQMR when using
+# Krylov method to approximate Jacobian
+F4_powell.JAC_KSP_BAD = {'minres'}
+F4_powell.ROOT_JAC_KSP_BAD = {'gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr'}
+
+
+def F5(x):
+ return pressure_network(x, 4, np.array([.5, .5, .5, .5]))
+
+
+F5.xin = [2., 0, 2, 0]
+F5.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing,
+ 'linearmixing': nonlin.linearmixing,
+ 'diagbroyden': nonlin.diagbroyden}
+# In the extreme case, the Jacobian inversion yielded zero vector for nonlinear
+# problem solved by CGS/MINRES and it does not converge for root problem solved
+# by MINRES and when using Krylov method to approximate Jacobian
+F5.JAC_KSP_BAD = {'cgs', 'minres'}
+F5.ROOT_JAC_KSP_BAD = {'minres'}
+
+
+def F6(x):
+ x1, x2 = x
+ J0 = np.array([[-4.256, 14.7],
+ [0.8394989, 0.59964207]])
+ v = np.array([(x1 + 3) * (x2**5 - 7) + 3*6,
+ np.sin(x2 * np.exp(x1) - 1)])
+ return -np.linalg.solve(J0, v)
+
+
+F6.xin = [-0.5, 1.4]
+F6.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing,
+ 'linearmixing': nonlin.linearmixing,
+ 'diagbroyden': nonlin.diagbroyden}
+F6.JAC_KSP_BAD = {}
+F6.ROOT_JAC_KSP_BAD = {}
+
+
+# ----------------------------------------------------------------------------
+# Tests
+# ----------------------------------------------------------------------------
+
+
+class TestNonlin:
+ """
+ Check the Broyden methods for a few test problems.
+
+ broyden1, broyden2, and newton_krylov must succeed for
+ all functions. Some of the others don't -- tests in KNOWN_BAD are skipped.
+
+ """
+
+ def _check_nonlin_func(self, f, func, f_tol=1e-2):
+ # Test all methods mentioned in the class `KrylovJacobian`
+ if func == SOLVERS['krylov']:
+ for method in ['gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr']:
+ if method in f.JAC_KSP_BAD:
+ continue
+
+ x = func(f, f.xin, method=method, line_search=None,
+ f_tol=f_tol, maxiter=200, verbose=0)
+ assert_(np.absolute(f(x)).max() < f_tol)
+
+ x = func(f, f.xin, f_tol=f_tol, maxiter=200, verbose=0)
+ assert_(np.absolute(f(x)).max() < f_tol)
+
+ def _check_root(self, f, method, f_tol=1e-2):
+ # Test Krylov methods
+ if method == 'krylov':
+ for jac_method in ['gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr']:
+ if jac_method in f.ROOT_JAC_KSP_BAD:
+ continue
+
+ res = root(f, f.xin, method=method,
+ options={'ftol': f_tol, 'maxiter': 200,
+ 'disp': 0,
+ 'jac_options': {'method': jac_method}})
+ assert_(np.absolute(res.fun).max() < f_tol)
+
+ res = root(f, f.xin, method=method,
+ options={'ftol': f_tol, 'maxiter': 200, 'disp': 0})
+ assert_(np.absolute(res.fun).max() < f_tol)
+
+ @pytest.mark.xfail
+ def _check_func_fail(self, *a, **kw):
+ pass
+
+ @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+ def test_problem_nonlin(self):
+ for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]:
+ for func in SOLVERS.values():
+ if func in f.KNOWN_BAD.values():
+ if func in MUST_WORK.values():
+ self._check_func_fail(f, func)
+ continue
+ self._check_nonlin_func(f, func)
+
+ @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+ @pytest.mark.parametrize("method", ['lgmres', 'gmres', 'bicgstab', 'cgs',
+ 'minres', 'tfqmr'])
+ def test_tol_norm_called(self, method):
+ # Check that supplying tol_norm keyword to nonlin_solve works
+ self._tol_norm_used = False
+
+ def local_norm_func(x):
+ self._tol_norm_used = True
+ return np.absolute(x).max()
+
+ nonlin.newton_krylov(F, F.xin, method=method, f_tol=1e-2,
+ maxiter=200, verbose=0,
+ tol_norm=local_norm_func)
+ assert_(self._tol_norm_used)
+
+ @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+ def test_problem_root(self):
+ for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]:
+ for meth in SOLVERS:
+ if meth in f.KNOWN_BAD:
+ if meth in MUST_WORK:
+ self._check_func_fail(f, meth)
+ continue
+ self._check_root(f, meth)
+
+ def test_no_convergence(self):
+ def wont_converge(x):
+ return 1e3 + x
+
+ with pytest.raises(scipy.optimize.NoConvergence):
+ nonlin.newton_krylov(wont_converge, xin=[0], maxiter=1)
+
+ def test_warnings_invalid_inner_param(self):
+ """
+ Test for ENH #21986, for behavior of `nonlin.newton_krylov`
+ Test the following scenarios:
+ 1. Raise warning for invalid inner param
+ 2. No warning for valid inner param
+ 3. No warning for user-provided callable method
+ """
+ # This should raise exactly one warning
+ # (`inner_atol` is not valid for `minres`)
+ with pytest.warns(UserWarning,
+ match="Please check inner method documentation"):
+ nonlin.newton_krylov(F, F.xin, method="minres", inner_atol=1e-5)
+
+ # This should not raise a warning (`minres` without `inner_atol`,
+ # but with `inner_maxiter` which is valid)
+ nonlin.newton_krylov(F, F.xin, method="minres", inner_maxiter=100,
+ inner_callback= lambda _ : ...)
+
+ # Test newton_krylov with a user-provided callable method
+ def user_provided_callable_method_enh_21986(op, rhs, **kwargs):
+ """A dummy user-provided callable method for testing."""
+ # Return a dummy result (mimicking minres)
+ return minres(op, rhs, **kwargs)
+ # This should not raise any warnings
+ nonlin.newton_krylov(F, F.xin,
+ method=user_provided_callable_method_enh_21986)
+
+ def test_non_inner_prefix(self):
+ with pytest.raises(ValueError,
+ match="Unknown parameter"
+ ):
+ # Pass a parameter without 'inner_' prefix
+ nonlin.newton_krylov(F, F.xin, method="minres", invalid_param=1e-5)
+
+
+class TestSecant:
+ """Check that some Jacobian approximations satisfy the secant condition"""
+
+ xs = [np.array([1., 2., 3., 4., 5.]),
+ np.array([2., 3., 4., 5., 1.]),
+ np.array([3., 4., 5., 1., 2.]),
+ np.array([4., 5., 1., 2., 3.]),
+ np.array([9., 1., 9., 1., 3.]),
+ np.array([0., 1., 9., 1., 3.]),
+ np.array([5., 5., 7., 1., 1.]),
+ np.array([1., 2., 7., 5., 1.]),]
+ fs = [x**2 - 1 for x in xs]
+
+ def _check_secant(self, jac_cls, npoints=1, **kw):
+ """
+ Check that the given Jacobian approximation satisfies secant
+ conditions for last `npoints` points.
+ """
+ jac = jac_cls(**kw)
+ jac.setup(self.xs[0], self.fs[0], None)
+ for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
+ jac.update(x, f)
+
+ for k in range(min(npoints, j+1)):
+ dx = self.xs[j-k+1] - self.xs[j-k]
+ df = self.fs[j-k+1] - self.fs[j-k]
+ assert_(np.allclose(dx, jac.solve(df)))
+
+ # Check that the `npoints` secant bound is strict
+ if j >= npoints:
+ dx = self.xs[j-npoints+1] - self.xs[j-npoints]
+ df = self.fs[j-npoints+1] - self.fs[j-npoints]
+ assert_(not np.allclose(dx, jac.solve(df)))
+
+ def test_broyden1(self):
+ self._check_secant(nonlin.BroydenFirst)
+
+ def test_broyden2(self):
+ self._check_secant(nonlin.BroydenSecond)
+
+ def test_broyden1_update(self):
+ # Check that BroydenFirst update works as for a dense matrix
+ jac = nonlin.BroydenFirst(alpha=0.1)
+ jac.setup(self.xs[0], self.fs[0], None)
+
+ B = np.identity(5) * (-1/0.1)
+
+ for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
+ df = f - self.fs[last_j]
+ dx = x - self.xs[last_j]
+ B += (df - dot(B, dx))[:, None] * dx[None, :] / dot(dx, dx)
+ jac.update(x, f)
+ assert_(np.allclose(jac.todense(), B, rtol=1e-10, atol=1e-13))
+
+ def test_broyden2_update(self):
+ # Check that BroydenSecond update works as for a dense matrix
+ jac = nonlin.BroydenSecond(alpha=0.1)
+ jac.setup(self.xs[0], self.fs[0], None)
+
+ H = np.identity(5) * (-0.1)
+
+ for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
+ df = f - self.fs[last_j]
+ dx = x - self.xs[last_j]
+ H += (dx - dot(H, df))[:, None] * df[None, :] / dot(df, df)
+ jac.update(x, f)
+ assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13))
+
+ def test_anderson(self):
+ # Anderson mixing (with w0=0) satisfies secant conditions
+ # for the last M iterates, see [Ey]_
+ #
+ # .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).
+ self._check_secant(nonlin.Anderson, M=3, w0=0, npoints=3)
+
+
+class TestLinear:
+ """Solve a linear equation;
+ some methods find the exact solution in a finite number of steps"""
+
+ def _check(self, jac, N, maxiter, complex=False, **kw):
+ rng = np.random.default_rng(123)
+
+ A = rng.standard_normal((N, N))
+ if complex:
+ A = A + 1j*rng.standard_normal((N, N))
+ b = rng.standard_normal(N)
+ if complex:
+ b = b + 1j*rng.standard_normal(N)
+
+ def func(x):
+ return dot(A, x) - b
+
+ sol = nonlin.nonlin_solve(func, np.zeros(N), jac, maxiter=maxiter,
+ f_tol=1e-6, line_search=None, verbose=0)
+ assert_(np.allclose(dot(A, sol), b, atol=1e-6))
+
+ def test_broyden1(self):
+ # Broyden methods solve linear systems exactly in 2*N steps
+ self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, False)
+ self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, True)
+
+ def test_broyden2(self):
+ # Broyden methods solve linear systems exactly in 2*N steps
+ self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, False)
+ self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, True)
+
+ def test_anderson(self):
+ # Anderson is rather similar to Broyden, if given enough storage space
+ self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, False)
+ self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, True)
+
+ def test_krylov(self):
+ # Krylov methods solve linear systems exactly in N inner steps
+ self._check(nonlin.KrylovJacobian, 20, 2, False, inner_m=10)
+ self._check(nonlin.KrylovJacobian, 20, 2, True, inner_m=10)
+
+ def _check_autojac(self, A, b):
+ def func(x):
+ return A.dot(x) - b
+
+ def jac(v):
+ return A
+
+ sol = nonlin.nonlin_solve(func, np.zeros(b.shape[0]), jac, maxiter=2,
+ f_tol=1e-6, line_search=None, verbose=0)
+ np.testing.assert_allclose(A @ sol, b, atol=1e-6)
+ # test jac input as array -- not a function
+ sol = nonlin.nonlin_solve(func, np.zeros(b.shape[0]), A, maxiter=2,
+ f_tol=1e-6, line_search=None, verbose=0)
+ np.testing.assert_allclose(A @ sol, b, atol=1e-6)
+
+ def test_jac_sparse(self):
+ A = csr_array([[1, 2], [2, 1]])
+ b = np.array([1, -1])
+ self._check_autojac(A, b)
+ self._check_autojac((1 + 2j) * A, (2 + 2j) * b)
+
+ def test_jac_ndarray(self):
+ A = np.array([[1, 2], [2, 1]])
+ b = np.array([1, -1])
+ self._check_autojac(A, b)
+ self._check_autojac((1 + 2j) * A, (2 + 2j) * b)
+
+
+class TestJacobianDotSolve:
+ """
+ Check that solve/dot methods in Jacobian approximations are consistent
+ """
+
+ def _func(self, x, A=None):
+ return x**2 - 1 + np.dot(A, x)
+
+ def _check_dot(self, jac_cls, complex=False, tol=1e-6, **kw):
+ rng = np.random.default_rng(123)
+
+ N = 7
+
+ def rand(*a):
+ q = rng.random(a)
+ if complex:
+ q = q + 1j*rng.random(a)
+ return q
+
+ def assert_close(a, b, msg):
+ d = abs(a - b).max()
+ f = tol + abs(b).max()*tol
+ if d > f:
+ raise AssertionError(f'{msg}: err {d:g}')
+
+ A = rand(N, N)
+
+ # initialize
+ x0 = rng.random(N)
+ jac = jac_cls(**kw)
+ jac.setup(x0, self._func(x0, A), partial(self._func, A=A))
+
+ # check consistency
+ for k in range(2*N):
+ v = rand(N)
+
+ if hasattr(jac, '__array__'):
+ Jd = np.array(jac)
+ if hasattr(jac, 'solve'):
+ Gv = jac.solve(v)
+ Gv2 = np.linalg.solve(Jd, v)
+ assert_close(Gv, Gv2, 'solve vs array')
+ if hasattr(jac, 'rsolve'):
+ Gv = jac.rsolve(v)
+ Gv2 = np.linalg.solve(Jd.T.conj(), v)
+ assert_close(Gv, Gv2, 'rsolve vs array')
+ if hasattr(jac, 'matvec'):
+ Jv = jac.matvec(v)
+ Jv2 = np.dot(Jd, v)
+ assert_close(Jv, Jv2, 'dot vs array')
+ if hasattr(jac, 'rmatvec'):
+ Jv = jac.rmatvec(v)
+ Jv2 = np.dot(Jd.T.conj(), v)
+ assert_close(Jv, Jv2, 'rmatvec vs array')
+
+ if hasattr(jac, 'matvec') and hasattr(jac, 'solve'):
+ Jv = jac.matvec(v)
+ Jv2 = jac.solve(jac.matvec(Jv))
+ assert_close(Jv, Jv2, 'dot vs solve')
+
+ if hasattr(jac, 'rmatvec') and hasattr(jac, 'rsolve'):
+ Jv = jac.rmatvec(v)
+ Jv2 = jac.rmatvec(jac.rsolve(Jv))
+ assert_close(Jv, Jv2, 'rmatvec vs rsolve')
+
+ x = rand(N)
+ jac.update(x, self._func(x, A))
+
+ def test_broyden1(self):
+ self._check_dot(nonlin.BroydenFirst, complex=False)
+ self._check_dot(nonlin.BroydenFirst, complex=True)
+
+ def test_broyden2(self):
+ self._check_dot(nonlin.BroydenSecond, complex=False)
+ self._check_dot(nonlin.BroydenSecond, complex=True)
+
+ def test_anderson(self):
+ self._check_dot(nonlin.Anderson, complex=False)
+ self._check_dot(nonlin.Anderson, complex=True)
+
+ def test_diagbroyden(self):
+ self._check_dot(nonlin.DiagBroyden, complex=False)
+ self._check_dot(nonlin.DiagBroyden, complex=True)
+
+ def test_linearmixing(self):
+ self._check_dot(nonlin.LinearMixing, complex=False)
+ self._check_dot(nonlin.LinearMixing, complex=True)
+
+ def test_excitingmixing(self):
+ self._check_dot(nonlin.ExcitingMixing, complex=False)
+ self._check_dot(nonlin.ExcitingMixing, complex=True)
+
+ def test_krylov(self):
+ self._check_dot(nonlin.KrylovJacobian, complex=False, tol=1e-3)
+ self._check_dot(nonlin.KrylovJacobian, complex=True, tol=1e-3)
+
+
+class TestNonlinOldTests:
+ """ Test case for a simple constrained entropy maximization problem
+ (the machine translation example of Berger et al in
+ Computational Linguistics, vol 22, num 1, pp 39--72, 1996.)
+ """
+
+ def test_broyden1(self):
+ x = nonlin.broyden1(F, F.xin, iter=12, alpha=1)
+ assert_(nonlin.norm(x) < 1e-9)
+ assert_(nonlin.norm(F(x)) < 1e-9)
+
+ def test_broyden2(self):
+ x = nonlin.broyden2(F, F.xin, iter=12, alpha=1)
+ assert_(nonlin.norm(x) < 1e-9)
+ assert_(nonlin.norm(F(x)) < 1e-9)
+
+ def test_anderson(self):
+ x = nonlin.anderson(F, F.xin, iter=12, alpha=0.03, M=5)
+ assert_(nonlin.norm(x) < 0.33)
+
+ def test_linearmixing(self):
+ x = nonlin.linearmixing(F, F.xin, iter=60, alpha=0.5)
+ assert_(nonlin.norm(x) < 1e-7)
+ assert_(nonlin.norm(F(x)) < 1e-7)
+
+ def test_exciting(self):
+ x = nonlin.excitingmixing(F, F.xin, iter=20, alpha=0.5)
+ assert_(nonlin.norm(x) < 1e-5)
+ assert_(nonlin.norm(F(x)) < 1e-5)
+
+ def test_diagbroyden(self):
+ x = nonlin.diagbroyden(F, F.xin, iter=11, alpha=1)
+ assert_(nonlin.norm(x) < 1e-8)
+ assert_(nonlin.norm(F(x)) < 1e-8)
+
+ def test_root_broyden1(self):
+ res = root(F, F.xin, method='broyden1',
+ options={'nit': 12, 'jac_options': {'alpha': 1}})
+ assert_(nonlin.norm(res.x) < 1e-9)
+ assert_(nonlin.norm(res.fun) < 1e-9)
+
+ def test_root_broyden2(self):
+ res = root(F, F.xin, method='broyden2',
+ options={'nit': 12, 'jac_options': {'alpha': 1}})
+ assert_(nonlin.norm(res.x) < 1e-9)
+ assert_(nonlin.norm(res.fun) < 1e-9)
+
+ def test_root_anderson(self):
+ res = root(F, F.xin, method='anderson',
+ options={'nit': 12,
+ 'jac_options': {'alpha': 0.03, 'M': 5}})
+ assert_(nonlin.norm(res.x) < 0.33)
+
+ def test_root_linearmixing(self):
+ res = root(F, F.xin, method='linearmixing',
+ options={'nit': 60,
+ 'jac_options': {'alpha': 0.5}})
+ assert_(nonlin.norm(res.x) < 1e-7)
+ assert_(nonlin.norm(res.fun) < 1e-7)
+
+ def test_root_excitingmixing(self):
+ res = root(F, F.xin, method='excitingmixing',
+ options={'nit': 20,
+ 'jac_options': {'alpha': 0.5}})
+ assert_(nonlin.norm(res.x) < 1e-5)
+ assert_(nonlin.norm(res.fun) < 1e-5)
+
+ def test_root_diagbroyden(self):
+ res = root(F, F.xin, method='diagbroyden',
+ options={'nit': 11,
+ 'jac_options': {'alpha': 1}})
+ assert_(nonlin.norm(res.x) < 1e-8)
+ assert_(nonlin.norm(res.fun) < 1e-8)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_optimize.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..80e0198068d17ee98f14302040c478e4c4812625
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_optimize.py
@@ -0,0 +1,3603 @@
+"""
+Unit tests for optimization routines from optimize.py
+
+Authors:
+ Ed Schofield, Nov 2005
+ Andrew Straw, April 2008
+
+"""
+import sys
+import itertools
+import inspect
+import platform
+import threading
+import warnings
+import multiprocessing
+
+import numpy as np
+from numpy.testing import (assert_allclose, assert_equal,
+ assert_almost_equal,
+ assert_no_warnings,
+ assert_array_less)
+import pytest
+from pytest import raises as assert_raises
+
+import scipy
+from scipy._lib._gcutils import assert_deallocated
+from scipy import optimize
+from scipy.optimize._minimize import Bounds, NonlinearConstraint
+from scipy.optimize._minimize import (MINIMIZE_METHODS,
+ MINIMIZE_METHODS_NEW_CB,
+ MINIMIZE_SCALAR_METHODS)
+from scipy.optimize._linprog import LINPROG_METHODS
+from scipy.optimize._root import ROOT_METHODS
+from scipy.optimize._root_scalar import ROOT_SCALAR_METHODS
+from scipy.optimize._qap import QUADRATIC_ASSIGNMENT_METHODS
+from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS
+from scipy.optimize._optimize import (
+ MemoizeJac, show_options, OptimizeResult, _minimize_bfgs
+)
+from scipy.optimize import rosen, rosen_der, rosen_hess
+
+from scipy.sparse import (coo_matrix, csc_matrix, csr_matrix, coo_array,
+ csr_array, csc_array)
+from scipy._lib._array_api_no_0d import xp_assert_equal
+from scipy._lib._array_api import make_xp_test_case
+from scipy._lib._util import MapWrapper
+
+lazy_xp_modules = [optimize]
+
+
+def test_check_grad():
+ # Verify if check_grad is able to estimate the derivative of the
+ # expit (logistic sigmoid) function.
+
+ def expit(x):
+ return 1 / (1 + np.exp(-x))
+
+ def der_expit(x):
+ return np.exp(-x) / (1 + np.exp(-x))**2
+
+ x0 = np.array([1.5])
+
+ r = optimize.check_grad(expit, der_expit, x0)
+ assert_almost_equal(r, 0)
+ # SPEC-007 leave one call with seed to check it still works
+ r = optimize.check_grad(expit, der_expit, x0,
+ direction='random', seed=1234)
+ assert_almost_equal(r, 0)
+
+ r = optimize.check_grad(expit, der_expit, x0, epsilon=1e-6)
+ assert_almost_equal(r, 0)
+ r = optimize.check_grad(expit, der_expit, x0, epsilon=1e-6,
+ direction='random', rng=1234)
+ assert_almost_equal(r, 0)
+
+ # Check if the epsilon parameter is being considered.
+ r = abs(optimize.check_grad(expit, der_expit, x0, epsilon=1e-1) - 0)
+ assert r > 1e-7
+ r = abs(optimize.check_grad(expit, der_expit, x0, epsilon=1e-1,
+ direction='random', rng=1234) - 0)
+ assert r > 1e-7
+
+ def x_sinx(x):
+ return (x*np.sin(x)).sum()
+
+ def der_x_sinx(x):
+ return np.sin(x) + x*np.cos(x)
+
+ x0 = np.arange(0, 2, 0.2)
+
+ r = optimize.check_grad(x_sinx, der_x_sinx, x0,
+ direction='random', rng=1234)
+ assert_almost_equal(r, 0)
+
+ assert_raises(ValueError, optimize.check_grad,
+ x_sinx, der_x_sinx, x0,
+ direction='random_projection', rng=1234)
+
+ # checking can be done for derivatives of vector valued functions
+ r = optimize.check_grad(himmelblau_grad, himmelblau_hess, himmelblau_x0,
+ direction='all', rng=1234)
+ assert r < 5e-7
+
+
+class CheckOptimize:
+ """ Base test case for a simple constrained entropy maximization problem
+ (the machine translation example of Berger et al in
+ Computational Linguistics, vol 22, num 1, pp 39--72, 1996.)
+ """
+
+ def setup_method(self):
+ self.F = np.array([[1, 1, 1],
+ [1, 1, 0],
+ [1, 0, 1],
+ [1, 0, 0],
+ [1, 0, 0]])
+ self.K = np.array([1., 0.3, 0.5])
+ self.startparams = np.zeros(3, np.float64)
+ self.solution = np.array([0., -0.524869316, 0.487525860])
+ self.maxiter = 1000
+ self.funccalls = threading.local()
+ self.gradcalls = threading.local()
+ self.trace = threading.local()
+
+ def func(self, x):
+ if not hasattr(self.funccalls, 'c'):
+ self.funccalls.c = 0
+
+ if not hasattr(self.gradcalls, 'c'):
+ self.gradcalls.c = 0
+
+ self.funccalls.c += 1
+ if self.funccalls.c > 6000:
+ raise RuntimeError("too many iterations in optimization routine")
+ log_pdot = np.dot(self.F, x)
+ logZ = np.log(sum(np.exp(log_pdot)))
+ f = logZ - np.dot(self.K, x)
+ if not hasattr(self.trace, 't'):
+ self.trace.t = []
+ self.trace.t.append(np.copy(x))
+ return f
+
+ def grad(self, x):
+ if not hasattr(self.gradcalls, 'c'):
+ self.gradcalls.c = 0
+ self.gradcalls.c += 1
+ log_pdot = np.dot(self.F, x)
+ logZ = np.log(sum(np.exp(log_pdot)))
+ p = np.exp(log_pdot - logZ)
+ return np.dot(self.F.transpose(), p) - self.K
+
+ def hess(self, x):
+ log_pdot = np.dot(self.F, x)
+ logZ = np.log(sum(np.exp(log_pdot)))
+ p = np.exp(log_pdot - logZ)
+ return np.dot(self.F.T,
+ np.dot(np.diag(p), self.F - np.dot(self.F.T, p)))
+
+ def hessp(self, x, p):
+ return np.dot(self.hess(x), p)
+
+
+class CheckOptimizeParameterized(CheckOptimize):
+
+ def test_cg(self):
+ # conjugate gradient optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='CG', jac=self.grad,
+ options=opts)
+ params, fopt, func_calls, grad_calls, warnflag = \
+ res['x'], res['fun'], res['nfev'], res['njev'], res['status']
+ else:
+ retval = optimize.fmin_cg(self.func, self.startparams,
+ self.grad, (), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, func_calls, grad_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 9, self.funccalls.c
+ assert self.gradcalls.c == 7, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[2:4],
+ [[0, -0.5, 0.5],
+ [0, -5.05700028e-01, 4.95985862e-01]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_cg_cornercase(self):
+ def f(r):
+ return 2.5 * (1 - np.exp(-1.5*(r - 0.5)))**2
+
+ # Check several initial guesses. (Too far away from the
+ # minimum, the function ends up in the flat region of exp.)
+ for x0 in np.linspace(-0.75, 3, 71):
+ sol = optimize.minimize(f, [x0], method='CG')
+ assert sol.success
+ assert_allclose(sol.x, [0.5], rtol=1e-5)
+
+ def test_bfgs(self):
+ # Broyden-Fletcher-Goldfarb-Shanno optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams,
+ jac=self.grad, method='BFGS', args=(),
+ options=opts)
+
+ params, fopt, gopt, Hopt, func_calls, grad_calls, warnflag = (
+ res['x'], res['fun'], res['jac'], res['hess_inv'],
+ res['nfev'], res['njev'], res['status'])
+ else:
+ retval = optimize.fmin_bfgs(self.func, self.startparams, self.grad,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, gopt, Hopt,
+ func_calls, grad_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 10, self.funccalls.c
+ assert self.gradcalls.c == 8, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[6:8],
+ [[0, -5.25060743e-01, 4.87748473e-01],
+ [0, -5.24885582e-01, 4.87530347e-01]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_bfgs_hess_inv0_neg(self):
+ # Ensure that BFGS does not accept neg. def. initial inverse
+ # Hessian estimate.
+ with pytest.raises(ValueError, match="'hess_inv0' matrix isn't "
+ "positive definite."):
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ opts = {'disp': self.disp, 'hess_inv0': -np.eye(5)}
+ optimize.minimize(optimize.rosen, x0=x0, method='BFGS', args=(),
+ options=opts)
+
+ def test_bfgs_hess_inv0_semipos(self):
+ # Ensure that BFGS does not accept semi pos. def. initial inverse
+ # Hessian estimate.
+ with pytest.raises(ValueError, match="'hess_inv0' matrix isn't "
+ "positive definite."):
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ hess_inv0 = np.eye(5)
+ hess_inv0[0, 0] = 0
+ opts = {'disp': self.disp, 'hess_inv0': hess_inv0}
+ optimize.minimize(optimize.rosen, x0=x0, method='BFGS', args=(),
+ options=opts)
+
+ def test_bfgs_hess_inv0_sanity(self):
+ # Ensure that BFGS handles `hess_inv0` parameter correctly.
+ fun = optimize.rosen
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ opts = {'disp': self.disp, 'hess_inv0': 1e-2 * np.eye(5)}
+ res = optimize.minimize(fun, x0=x0, method='BFGS', args=(),
+ options=opts)
+ res_true = optimize.minimize(fun, x0=x0, method='BFGS', args=(),
+ options={'disp': self.disp})
+ assert_allclose(res.fun, res_true.fun, atol=1e-6)
+
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ def test_bfgs_infinite(self):
+ # Test corner case where -Inf is the minimum. See gh-2019.
+ def func(x):
+ return -np.e ** (-x)
+ def fprime(x):
+ return -func(x)
+ x0 = [0]
+ with np.errstate(over='ignore'):
+ if self.use_wrapper:
+ opts = {'disp': self.disp}
+ x = optimize.minimize(func, x0, jac=fprime, method='BFGS',
+ args=(), options=opts)['x']
+ else:
+ x = optimize.fmin_bfgs(func, x0, fprime, disp=self.disp)
+ assert not np.isfinite(func(x))
+
+ def test_bfgs_xrtol(self):
+ # test for #17345 to test xrtol parameter
+ x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+ res = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'xrtol': 1e-3})
+ ref = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'gtol': 1e-3})
+ assert res.nit != ref.nit
+
+ def test_bfgs_c1(self):
+ # test for #18977 insufficiently low value of c1 leads to precision loss
+ # for poor starting parameters
+ x0 = [10.3, 20.7, 10.8, 1.9, -1.2]
+ res_c1_small = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c1': 1e-8})
+ res_c1_big = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c1': 1e-1})
+
+ assert res_c1_small.nfev > res_c1_big.nfev
+
+ def test_bfgs_c2(self):
+ # test that modification of c2 parameter
+ # results in different number of iterations
+ x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+ res_default = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c2': .9})
+ res_mod = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c2': 1e-2})
+ assert res_default.nit > res_mod.nit
+
+ @pytest.mark.parametrize(["c1", "c2"], [[0.5, 2],
+ [-0.1, 0.1],
+ [0.2, 0.1]])
+ def test_invalid_c1_c2(self, c1, c2):
+ with pytest.raises(ValueError, match="'c1' and 'c2'"):
+ x0 = [10.3, 20.7, 10.8, 1.9, -1.2]
+ optimize.minimize(optimize.rosen, x0, method='cg',
+ options={'c1': c1, 'c2': c2})
+
+ def test_powell(self):
+ # Powell (direction set) optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Powell', options=opts)
+ params, fopt, direc, numiter, func_calls, warnflag = (
+ res['x'], res['fun'], res['direc'], res['nit'],
+ res['nfev'], res['status'])
+ else:
+ retval = optimize.fmin_powell(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, direc, numiter, func_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+ # params[0] does not affect the objective function
+ assert_allclose(params[1:], self.solution[1:], atol=5e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ #
+ # However, some leeway must be added: the exact evaluation
+ # count is sensitive to numerical error, and floating-point
+ # computations are not bit-for-bit reproducible across
+ # machines, and when using e.g., MKL, data alignment
+ # etc., affect the rounding error.
+ #
+ assert self.funccalls.c <= 116 + 20, self.funccalls.c
+ assert self.gradcalls.c == 0, self.gradcalls.c
+
+ @pytest.mark.xfail(reason="This part of test_powell fails on some "
+ "platforms, but the solution returned by powell is "
+ "still valid.")
+ def test_powell_gh14014(self):
+ # This part of test_powell started failing on some CI platforms;
+ # see gh-14014. Since the solution is still correct and the comments
+ # in test_powell suggest that small differences in the bits are known
+ # to change the "trace" of the solution, seems safe to xfail to get CI
+ # green now and investigate later.
+
+ # Powell (direction set) optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Powell', options=opts)
+ params, fopt, direc, numiter, func_calls, warnflag = (
+ res['x'], res['fun'], res['direc'], res['nit'],
+ res['nfev'], res['status'])
+ else:
+ retval = optimize.fmin_powell(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, direc, numiter, func_calls, warnflag) = retval
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace[34:39],
+ [[0.72949016, -0.44156936, 0.47100962],
+ [0.72949016, -0.44156936, 0.48052496],
+ [1.45898031, -0.88313872, 0.95153458],
+ [0.72949016, -0.44156936, 0.47576729],
+ [1.72949016, -0.44156936, 0.47576729]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_powell_bounded(self):
+ # Powell (direction set) optimization routine
+ # same as test_powell above, but with bounds
+ bounds = [(-np.pi, np.pi) for _ in self.startparams]
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ bounds=bounds,
+ method='Powell', options=opts)
+ params, func_calls = (res['x'], res['nfev'])
+
+ assert func_calls == self.funccalls.c
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6, rtol=1e-5)
+
+ # The exact evaluation count is sensitive to numerical error, and
+ # floating-point computations are not bit-for-bit reproducible
+ # across machines, and when using e.g. MKL, data alignment etc.
+ # affect the rounding error.
+ # It takes 155 calls on my machine, but we can add the same +20
+ # margin as is used in `test_powell`
+ assert self.funccalls.c <= 155 + 20
+ assert self.gradcalls.c == 0
+
+ def test_neldermead(self):
+ # Nelder-Mead simplex algorithm
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Nelder-mead', options=opts)
+ params, fopt, numiter, func_calls, warnflag = (
+ res['x'], res['fun'], res['nit'], res['nfev'],
+ res['status'])
+ else:
+ retval = optimize.fmin(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, numiter, func_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 167, self.funccalls.c
+ assert self.gradcalls.c == 0, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[76:78],
+ [[0.1928968, -0.62780447, 0.35166118],
+ [0.19572515, -0.63648426, 0.35838135]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_neldermead_initial_simplex(self):
+ # Nelder-Mead simplex algorithm
+ simplex = np.zeros((4, 3))
+ simplex[...] = self.startparams
+ for j in range(3):
+ simplex[j+1, j] += 0.1
+
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': False,
+ 'return_all': True, 'initial_simplex': simplex}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Nelder-mead', options=opts)
+ params, fopt, numiter, func_calls, warnflag = (res['x'],
+ res['fun'],
+ res['nit'],
+ res['nfev'],
+ res['status'])
+ assert_allclose(res['allvecs'][0], simplex[0])
+ else:
+ retval = optimize.fmin(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=False, retall=False,
+ initial_simplex=simplex)
+
+ (params, fopt, numiter, func_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.17.0. Don't allow them to increase.
+ assert self.funccalls.c == 100, self.funccalls.c
+ assert self.gradcalls.c == 0, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.15.0
+ assert_allclose(self.trace.t[50:52],
+ [[0.14687474, -0.5103282, 0.48252111],
+ [0.14474003, -0.5282084, 0.48743951]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_neldermead_initial_simplex_bad(self):
+ # Check it fails with a bad simplices
+ bad_simplices = []
+
+ simplex = np.zeros((3, 2))
+ simplex[...] = self.startparams[:2]
+ for j in range(2):
+ simplex[j+1, j] += 0.1
+ bad_simplices.append(simplex)
+
+ simplex = np.zeros((3, 3))
+ bad_simplices.append(simplex)
+
+ for simplex in bad_simplices:
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': False,
+ 'return_all': False, 'initial_simplex': simplex}
+ assert_raises(ValueError,
+ optimize.minimize,
+ self.func,
+ self.startparams,
+ args=(),
+ method='Nelder-mead',
+ options=opts)
+ else:
+ assert_raises(ValueError, optimize.fmin,
+ self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=False, retall=False,
+ initial_simplex=simplex)
+
+ def test_neldermead_x0_ub(self):
+ # checks whether minimisation occurs correctly for entries where
+ # x0 == ub
+ # gh19991
+ def quad(x):
+ return np.sum(x**2)
+
+ res = optimize.minimize(
+ quad,
+ [1],
+ bounds=[(0, 1.)],
+ method='nelder-mead'
+ )
+ assert_allclose(res.x, [0])
+
+ res = optimize.minimize(
+ quad,
+ [1, 2],
+ bounds=[(0, 1.), (1, 3.)],
+ method='nelder-mead'
+ )
+ assert_allclose(res.x, [0, 1])
+
+ def test_ncg_negative_maxiter(self):
+ # Regression test for gh-8241
+ opts = {'maxiter': -1}
+ result = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ args=(), options=opts)
+ assert result.status == 1
+
+ def test_ncg_zero_xtol(self):
+ # Regression test for gh-20214
+ def cosine(x):
+ return np.cos(x[0])
+
+ def jac(x):
+ return -np.sin(x[0])
+
+ x0 = [0.1]
+ xtol = 0
+ result = optimize.minimize(cosine,
+ x0=x0,
+ jac=jac,
+ method="newton-cg",
+ options=dict(xtol=xtol))
+ assert result.status == 0
+ assert_almost_equal(result.x[0], np.pi)
+
+ def test_ncg(self):
+ # line-search Newton conjugate gradient optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ retval = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ args=(), options=opts)['x']
+ else:
+ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad,
+ args=(), maxiter=self.maxiter,
+ full_output=False, disp=self.disp,
+ retall=False)
+
+ params = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 7, self.funccalls.c
+ assert self.gradcalls.c <= 22, self.gradcalls.c # 0.13.0
+ # assert self.gradcalls <= 18, self.gradcalls # 0.9.0
+ # assert self.gradcalls == 18, self.gradcalls # 0.8.0
+ # assert self.gradcalls == 22, self.gradcalls # 0.7.0
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[3:5],
+ [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01],
+ [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]],
+ atol=1e-6, rtol=1e-7)
+
+ def test_ncg_hess(self):
+ # Newton conjugate gradient with Hessian
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ retval = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ hess=self.hess,
+ args=(), options=opts)['x']
+ else:
+ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad,
+ fhess=self.hess,
+ args=(), maxiter=self.maxiter,
+ full_output=False, disp=self.disp,
+ retall=False)
+
+ params = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c <= 7, self.funccalls.c # gh10673
+ assert self.gradcalls.c <= 18, self.gradcalls.c # 0.9.0
+ # assert self.gradcalls == 18, self.gradcalls # 0.8.0
+ # assert self.gradcalls == 22, self.gradcalls # 0.7.0
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[3:5],
+ [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01],
+ [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]],
+ atol=1e-6, rtol=1e-7)
+
+ def test_ncg_hessp(self):
+ # Newton conjugate gradient with Hessian times a vector p.
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ retval = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ hessp=self.hessp,
+ args=(), options=opts)['x']
+ else:
+ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad,
+ fhess_p=self.hessp,
+ args=(), maxiter=self.maxiter,
+ full_output=False, disp=self.disp,
+ retall=False)
+
+ params = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c <= 7, self.funccalls.c # gh10673
+ assert self.gradcalls.c <= 18, self.gradcalls.c # 0.9.0
+ # assert self.gradcalls == 18, self.gradcalls # 0.8.0
+ # assert self.gradcalls == 22, self.gradcalls # 0.7.0
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[3:5],
+ [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01],
+ [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]],
+ atol=1e-6, rtol=1e-7)
+
+ def test_cobyqa(self):
+ # COBYQA method.
+ if self.use_wrapper:
+ res = optimize.minimize(
+ self.func,
+ self.startparams,
+ method='cobyqa',
+ options={'maxiter': self.maxiter, 'disp': self.disp},
+ )
+ assert_allclose(res.fun, self.func(self.solution), atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 1.14.0. Don't allow them to increase. The exact evaluation
+ # count is sensitive to numerical error and floating-point
+ # computations are not bit-for-bit reproducible across machines. It
+ # takes 45 calls on my machine, but we can add the same +20 margin
+ # as is used in `test_powell`
+ assert self.funccalls.c <= 45 + 20, self.funccalls.c
+
+
+def test_maxfev_test():
+ rng = np.random.default_rng(271707100830272976862395227613146332411)
+
+ def cost(x):
+ return rng.random(1) * 1000 # never converged problem
+
+ for imaxfev in [1, 10, 50]:
+ # "TNC" and "L-BFGS-B" also supports max function evaluation, but
+ # these may violate the limit because of evaluating gradients
+ # by numerical differentiation. See the discussion in PR #14805.
+ for method in ['Powell', 'Nelder-Mead']:
+ result = optimize.minimize(cost, rng.random(10),
+ method=method,
+ options={'maxfev': imaxfev})
+ assert result["nfev"] == imaxfev
+
+
+def test_wrap_scalar_function_with_validation():
+
+ def func_(x):
+ return x
+
+ fcalls, func = optimize._optimize.\
+ _wrap_scalar_function_maxfun_validation(func_, np.asarray(1), 5)
+
+ for i in range(5):
+ func(np.asarray(i))
+ assert fcalls[0] == i+1
+
+ msg = "Too many function calls"
+ with assert_raises(optimize._optimize._MaxFuncCallError, match=msg):
+ func(np.asarray(i)) # exceeded maximum function call
+
+ fcalls, func = optimize._optimize.\
+ _wrap_scalar_function_maxfun_validation(func_, np.asarray(1), 5)
+
+ msg = "The user-provided objective function must return a scalar value."
+ with assert_raises(ValueError, match=msg):
+ func(np.array([1, 1]))
+
+
+def test_obj_func_returns_scalar():
+ match = ("The user-provided "
+ "objective function must "
+ "return a scalar value.")
+ with assert_raises(ValueError, match=match):
+ optimize.minimize(lambda x: x, np.array([1, 1]), method='BFGS')
+
+
+def test_neldermead_iteration_num():
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ res = optimize._minimize._minimize_neldermead(optimize.rosen, x0,
+ xatol=1e-8)
+ assert res.nit <= 339
+
+
+def test_neldermead_respect_fp():
+ # Nelder-Mead should respect the fp type of the input + function
+ x0 = np.array([5.0, 4.0]).astype(np.float32)
+ def rosen_(x):
+ assert x.dtype == np.float32
+ return optimize.rosen(x)
+
+ optimize.minimize(rosen_, x0, method='Nelder-Mead')
+
+
+def test_neldermead_xatol_fatol():
+ # gh4484
+ # test we can call with fatol, xatol specified
+ def func(x):
+ return x[0] ** 2 + x[1] ** 2
+
+ optimize._minimize._minimize_neldermead(func, [1, 1], maxiter=2,
+ xatol=1e-3, fatol=1e-3)
+
+
+def test_neldermead_adaptive():
+ def func(x):
+ return np.sum(x ** 2)
+ p0 = [0.15746215, 0.48087031, 0.44519198, 0.4223638, 0.61505159,
+ 0.32308456, 0.9692297, 0.4471682, 0.77411992, 0.80441652,
+ 0.35994957, 0.75487856, 0.99973421, 0.65063887, 0.09626474]
+
+ res = optimize.minimize(func, p0, method='Nelder-Mead')
+ assert_equal(res.success, False)
+
+ res = optimize.minimize(func, p0, method='Nelder-Mead',
+ options={'adaptive': True})
+ assert_equal(res.success, True)
+
+
+def test_bounded_powell_outsidebounds():
+ # With the bounded Powell method if you start outside the bounds the final
+ # should still be within the bounds (provided that the user doesn't make a
+ # bad choice for the `direc` argument).
+ def func(x):
+ return np.sum(x ** 2)
+ bounds = (-1, 1), (-1, 1), (-1, 1)
+ x0 = [-4, .5, -.8]
+
+ # we're starting outside the bounds, so we should get a warning
+ with pytest.warns(optimize.OptimizeWarning):
+ res = optimize.minimize(func, x0, bounds=bounds, method="Powell")
+ assert_allclose(res.x, np.array([0.] * len(x0)), atol=1e-6)
+ assert_equal(res.success, True)
+ assert_equal(res.status, 0)
+
+ # However, now if we change the `direc` argument such that the
+ # set of vectors does not span the parameter space, then we may
+ # not end up back within the bounds. Here we see that the first
+ # parameter cannot be updated!
+ direc = [[0, 0, 0], [0, 1, 0], [0, 0, 1]]
+ # we're starting outside the bounds, so we should get a warning
+ with pytest.warns(optimize.OptimizeWarning):
+ res = optimize.minimize(func, x0,
+ bounds=bounds, method="Powell",
+ options={'direc': direc})
+ assert_allclose(res.x, np.array([-4., 0, 0]), atol=1e-6)
+ assert_equal(res.success, False)
+ assert_equal(res.status, 4)
+
+
+def test_bounded_powell_vs_powell():
+ # here we test an example where the bounded Powell method
+ # will return a different result than the standard Powell
+ # method.
+
+ # first we test a simple example where the minimum is at
+ # the origin and the minimum that is within the bounds is
+ # larger than the minimum at the origin.
+ def func(x):
+ return np.sum(x ** 2)
+ bounds = (-5, -1), (-10, -0.1), (1, 9.2), (-4, 7.6), (-15.9, -2)
+ x0 = [-2.1, -5.2, 1.9, 0, -2]
+
+ options = {'ftol': 1e-10, 'xtol': 1e-10}
+
+ res_powell = optimize.minimize(func, x0, method="Powell", options=options)
+ assert_allclose(res_powell.x, 0., atol=1e-6)
+ assert_allclose(res_powell.fun, 0., atol=1e-6)
+
+ res_bounded_powell = optimize.minimize(func, x0, options=options,
+ bounds=bounds,
+ method="Powell")
+ p = np.array([-1, -0.1, 1, 0, -2])
+ assert_allclose(res_bounded_powell.x, p, atol=1e-6)
+ assert_allclose(res_bounded_powell.fun, func(p), atol=1e-6)
+
+ # now we test bounded Powell but with a mix of inf bounds.
+ bounds = (None, -1), (-np.inf, -.1), (1, np.inf), (-4, None), (-15.9, -2)
+ res_bounded_powell = optimize.minimize(func, x0, options=options,
+ bounds=bounds,
+ method="Powell")
+ p = np.array([-1, -0.1, 1, 0, -2])
+ assert_allclose(res_bounded_powell.x, p, atol=1e-6)
+ assert_allclose(res_bounded_powell.fun, func(p), atol=1e-6)
+
+ # next we test an example where the global minimum is within
+ # the bounds, but the bounded Powell method performs better
+ # than the standard Powell method.
+ def func(x):
+ t = np.sin(-x[0]) * np.cos(x[1]) * np.sin(-x[0] * x[1]) * np.cos(x[1])
+ t -= np.cos(np.sin(x[1] * x[2]) * np.cos(x[2]))
+ return t**2
+
+ bounds = [(-2, 5)] * 3
+ x0 = [-0.5, -0.5, -0.5]
+
+ res_powell = optimize.minimize(func, x0, method="Powell")
+ res_bounded_powell = optimize.minimize(func, x0,
+ bounds=bounds,
+ method="Powell")
+ assert_allclose(res_powell.fun, 0.007136253919761627, atol=1e-6)
+ assert_allclose(res_bounded_powell.fun, 0, atol=1e-6)
+
+ # next we test the previous example where the we provide Powell
+ # with (-inf, inf) bounds, and compare it to providing Powell
+ # with no bounds. They should end up the same.
+ bounds = [(-np.inf, np.inf)] * 3
+
+ res_bounded_powell = optimize.minimize(func, x0,
+ bounds=bounds,
+ method="Powell")
+ assert_allclose(res_powell.fun, res_bounded_powell.fun, atol=1e-6)
+ assert_allclose(res_powell.nfev, res_bounded_powell.nfev, atol=1e-6)
+ assert_allclose(res_powell.x, res_bounded_powell.x, atol=1e-6)
+
+ # now test when x0 starts outside of the bounds.
+ x0 = [45.46254415, -26.52351498, 31.74830248]
+ bounds = [(-2, 5)] * 3
+ # we're starting outside the bounds, so we should get a warning
+ with pytest.warns(optimize.OptimizeWarning):
+ res_bounded_powell = optimize.minimize(func, x0,
+ bounds=bounds,
+ method="Powell")
+ assert_allclose(res_bounded_powell.fun, 0, atol=1e-6)
+
+
+def test_onesided_bounded_powell_stability():
+ # When the Powell method is bounded on only one side, a
+ # np.tan transform is done in order to convert it into a
+ # completely bounded problem. Here we do some simple tests
+ # of one-sided bounded Powell where the optimal solutions
+ # are large to test the stability of the transformation.
+ kwargs = {'method': 'Powell',
+ 'bounds': [(-np.inf, 1e6)] * 3,
+ 'options': {'ftol': 1e-8, 'xtol': 1e-8}}
+ x0 = [1, 1, 1]
+
+ # df/dx is constant.
+ def f(x):
+ return -np.sum(x)
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -3e6, atol=1e-4)
+
+ # df/dx gets smaller and smaller.
+ def f(x):
+ return -np.abs(np.sum(x)) ** (0.1) * (1 if np.all(x > 0) else -1)
+
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -(3e6) ** (0.1))
+
+ # df/dx gets larger and larger.
+ def f(x):
+ return -np.abs(np.sum(x)) ** 10 * (1 if np.all(x > 0) else -1)
+
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -(3e6) ** 10, rtol=1e-7)
+
+ # df/dx gets larger for some of the variables and smaller for others.
+ def f(x):
+ t = -np.abs(np.sum(x[:2])) ** 5 - np.abs(np.sum(x[2:])) ** (0.1)
+ t *= (1 if np.all(x > 0) else -1)
+ return t
+
+ kwargs['bounds'] = [(-np.inf, 1e3)] * 3
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -(2e3) ** 5 - (1e6) ** (0.1), rtol=1e-7)
+
+
+class TestOptimizeWrapperDisp(CheckOptimizeParameterized):
+ use_wrapper = True
+ disp = True
+
+
+class TestOptimizeWrapperNoDisp(CheckOptimizeParameterized):
+ use_wrapper = True
+ disp = False
+
+
+class TestOptimizeNoWrapperDisp(CheckOptimizeParameterized):
+ use_wrapper = False
+ disp = True
+
+
+class TestOptimizeNoWrapperNoDisp(CheckOptimizeParameterized):
+ use_wrapper = False
+ disp = False
+
+
+class TestOptimizeSimple(CheckOptimize):
+
+ def test_bfgs_nan(self):
+ # Test corner case where nan is fed to optimizer. See gh-2067.
+ def func(x):
+ return x
+ def fprime(x):
+ return np.ones_like(x)
+ x0 = [np.nan]
+ with np.errstate(over='ignore', invalid='ignore'):
+ x = optimize.fmin_bfgs(func, x0, fprime, disp=False)
+ assert np.isnan(func(x))
+
+ def test_bfgs_nan_return(self):
+ # Test corner cases where fun returns NaN. See gh-4793.
+
+ # First case: NaN from first call.
+ def func(x):
+ return np.nan
+ with np.errstate(invalid='ignore'):
+ result = optimize.minimize(func, 0)
+
+ assert np.isnan(result['fun'])
+ assert result['success'] is False
+
+ # Second case: NaN from second call.
+ def func(x):
+ return 0 if x == 0 else np.nan
+ def fprime(x):
+ return np.ones_like(x) # Steer away from zero.
+ with np.errstate(invalid='ignore'):
+ result = optimize.minimize(func, 0, jac=fprime)
+
+ assert np.isnan(result['fun'])
+ assert result['success'] is False
+
+ def test_bfgs_numerical_jacobian(self):
+ # BFGS with numerical Jacobian and a vector epsilon parameter.
+ # define the epsilon parameter using a random vector
+ rng = np.random.default_rng(1234)
+ epsilon = np.sqrt(np.spacing(1.)) * rng.random(len(self.solution))
+
+ params = optimize.fmin_bfgs(self.func, self.startparams,
+ epsilon=epsilon, args=(),
+ maxiter=self.maxiter, disp=False)
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ def test_finite_differences_jac(self):
+ methods = ['BFGS', 'CG', 'TNC']
+ jacs = ['2-point', '3-point', None]
+ for method, jac in itertools.product(methods, jacs):
+ result = optimize.minimize(self.func, self.startparams,
+ method=method, jac=jac)
+ assert_allclose(self.func(result.x), self.func(self.solution),
+ atol=1e-6)
+
+ def test_finite_differences_hess(self):
+ # test that all the methods that require hess can use finite-difference
+ # For Newton-CG, trust-ncg, trust-krylov the FD estimated hessian is
+ # wrapped in a hessp function
+ # dogleg, trust-exact actually require true hessians at the moment, so
+ # they're excluded.
+ methods = ['trust-constr', 'Newton-CG', 'trust-ncg', 'trust-krylov']
+ hesses = FD_METHODS + (optimize.BFGS,)
+ for method, hess in itertools.product(methods, hesses):
+ if hess is optimize.BFGS:
+ hess = hess()
+ result = optimize.minimize(self.func, self.startparams,
+ method=method, jac=self.grad,
+ hess=hess)
+ assert result.success
+
+ # check that the methods demand some sort of Hessian specification
+ # Newton-CG creates its own hessp, and trust-constr doesn't need a hess
+ # specified either
+ methods = ['trust-ncg', 'trust-krylov', 'dogleg', 'trust-exact']
+ for method in methods:
+ with pytest.raises(ValueError):
+ optimize.minimize(self.func, self.startparams,
+ method=method, jac=self.grad,
+ hess=None)
+
+ def test_bfgs_gh_2169(self):
+ def f(x):
+ if x < 0:
+ return 1.79769313e+308
+ else:
+ return x + 1./x
+ xs = optimize.fmin_bfgs(f, [10.], disp=False)
+ assert_allclose(xs, 1.0, rtol=1e-4, atol=1e-4)
+
+ def test_bfgs_double_evaluations(self):
+ # check BFGS does not evaluate twice in a row at same point
+ def f(x):
+ xp = x[0]
+ assert xp not in seen
+ seen.add(xp)
+ return 10*x**2, 20*x
+
+ seen = set()
+ optimize.minimize(f, -100, method='bfgs', jac=True, tol=1e-7)
+
+ def test_l_bfgs_b(self):
+ # limited-memory bound-constrained BFGS algorithm
+ retval = optimize.fmin_l_bfgs_b(self.func, self.startparams,
+ self.grad, args=(),
+ maxiter=self.maxiter)
+
+ (params, fopt, d) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 7, self.funccalls.c
+ assert self.gradcalls.c == 5, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ # test fixed in gh10673
+ assert_allclose(self.trace.t[3:5],
+ [[8.117083e-16, -5.196198e-01, 4.897617e-01],
+ [0., -0.52489628, 0.48753042]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_l_bfgs_b_numjac(self):
+ # L-BFGS-B with numerical Jacobian
+ retval = optimize.fmin_l_bfgs_b(self.func, self.startparams,
+ approx_grad=True,
+ maxiter=self.maxiter)
+
+ (params, fopt, d) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ def test_l_bfgs_b_funjac(self):
+ # L-BFGS-B with combined objective function and Jacobian
+ def fun(x):
+ return self.func(x), self.grad(x)
+
+ retval = optimize.fmin_l_bfgs_b(fun, self.startparams,
+ maxiter=self.maxiter)
+
+ (params, fopt, d) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ def test_l_bfgs_b_maxiter(self):
+ # gh7854
+ # Ensure that not more than maxiters are ever run.
+ class Callback:
+ def __init__(self):
+ self.nit = 0
+ self.fun = None
+ self.x = None
+
+ def __call__(self, x):
+ self.x = x
+ self.fun = optimize.rosen(x)
+ self.nit += 1
+
+ c = Callback()
+ res = optimize.minimize(optimize.rosen, [0., 0.], method='l-bfgs-b',
+ callback=c, options={'maxiter': 5})
+
+ assert_equal(res.nit, 5)
+ assert_almost_equal(res.x, c.x)
+ assert_almost_equal(res.fun, c.fun)
+ assert_equal(res.status, 1)
+ assert res.success is False
+ assert_equal(res.message,
+ 'STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT')
+
+ def test_minimize_l_bfgs_b(self):
+ # Minimize with L-BFGS-B method
+ opts = {'maxiter': self.maxiter}
+ r = optimize.minimize(self.func, self.startparams,
+ method='L-BFGS-B', jac=self.grad,
+ options=opts)
+ assert_allclose(self.func(r.x), self.func(self.solution),
+ atol=1e-6)
+ assert self.gradcalls.c == r.njev
+
+ self.funccalls.c = self.gradcalls.c = 0
+ # approximate jacobian
+ ra = optimize.minimize(self.func, self.startparams,
+ method='L-BFGS-B', options=opts)
+ # check that function evaluations in approximate jacobian are counted
+ # assert_(ra.nfev > r.nfev)
+ assert self.funccalls.c == ra.nfev
+ assert_allclose(self.func(ra.x), self.func(self.solution),
+ atol=1e-6)
+
+ self.funccalls.c = self.gradcalls.c = 0
+ # approximate jacobian
+ ra = optimize.minimize(self.func, self.startparams, jac='3-point',
+ method='L-BFGS-B', options=opts)
+ assert self.funccalls.c == ra.nfev
+ assert_allclose(self.func(ra.x), self.func(self.solution),
+ atol=1e-6)
+
+ def test_minimize_l_bfgs_b_ftol(self):
+ # Check that the `ftol` parameter in l_bfgs_b works as expected
+ v0 = None
+ for tol in [1e-1, 1e-4, 1e-7, 1e-10]:
+ opts = {'maxiter': self.maxiter, 'ftol': tol}
+ sol = optimize.minimize(self.func, self.startparams,
+ method='L-BFGS-B', jac=self.grad,
+ options=opts)
+ v = self.func(sol.x)
+
+ if v0 is None:
+ v0 = v
+ else:
+ assert v < v0
+
+ assert_allclose(v, self.func(self.solution), rtol=tol)
+
+ def test_minimize_l_bfgs_maxls(self):
+ # check that the maxls is passed down to the Fortran routine
+ sol = optimize.minimize(optimize.rosen, np.array([-1.2, 1.0]),
+ method='L-BFGS-B', jac=optimize.rosen_der,
+ options={'maxls': 1})
+ assert not sol.success
+
+ def test_minimize_l_bfgs_b_maxfun_interruption(self):
+ # gh-6162
+ f = optimize.rosen
+ g = optimize.rosen_der
+ values = []
+ x0 = np.full(7, 1000)
+
+ def objfun(x):
+ value = f(x)
+ values.append(value)
+ return value
+
+ # Look for an interesting test case.
+ # Request a maxfun that stops at a particularly bad function
+ # evaluation somewhere between 100 and 300 evaluations.
+ low, medium, high = 30, 100, 300
+ optimize.fmin_l_bfgs_b(objfun, x0, fprime=g, maxfun=high)
+ v, k = max((y, i) for i, y in enumerate(values[medium:]))
+ maxfun = medium + k
+ # If the minimization strategy is reasonable,
+ # the minimize() result should not be worse than the best
+ # of the first 30 function evaluations.
+ target = min(values[:low])
+ xmin, fmin, d = optimize.fmin_l_bfgs_b(f, x0, fprime=g, maxfun=maxfun)
+ assert_array_less(fmin, target)
+
+ def test_custom(self):
+ # This function comes from the documentation example.
+ def custmin(fun, x0, args=(), maxfev=None, stepsize=0.1,
+ maxiter=100, callback=None, **options):
+ bestx = x0
+ besty = fun(x0)
+ funcalls = 1
+ niter = 0
+ improved = True
+ stop = False
+
+ while improved and not stop and niter < maxiter:
+ improved = False
+ niter += 1
+ for dim in range(np.size(x0)):
+ for s in [bestx[dim] - stepsize, bestx[dim] + stepsize]:
+ testx = np.copy(bestx)
+ testx[dim] = s
+ testy = fun(testx, *args)
+ funcalls += 1
+ if testy < besty:
+ besty = testy
+ bestx = testx
+ improved = True
+ if callback is not None:
+ callback(bestx)
+ if maxfev is not None and funcalls >= maxfev:
+ stop = True
+ break
+
+ return optimize.OptimizeResult(fun=besty, x=bestx, nit=niter,
+ nfev=funcalls, success=(niter > 1))
+
+ x0 = [1.35, 0.9, 0.8, 1.1, 1.2]
+ res = optimize.minimize(optimize.rosen, x0, method=custmin,
+ options=dict(stepsize=0.05))
+ assert_allclose(res.x, 1.0, rtol=1e-4, atol=1e-4)
+
+ def test_gh10771(self):
+ # check that minimize passes bounds and constraints to a custom
+ # minimizer without altering them.
+ bounds = [(-2, 2), (0, 3)]
+ constraints = 'constraints'
+
+ def custmin(fun, x0, **options):
+ assert options['bounds'] is bounds
+ assert options['constraints'] is constraints
+ return optimize.OptimizeResult()
+
+ x0 = [1, 1]
+ optimize.minimize(optimize.rosen, x0, method=custmin,
+ bounds=bounds, constraints=constraints)
+
+ def test_minimize_tol_parameter(self):
+ # Check that the minimize() tol= argument does something
+ def func(z):
+ x, y = z
+ return x**2*y**2 + x**4 + 1
+
+ def dfunc(z):
+ x, y = z
+ return np.array([2*x*y**2 + 4*x**3, 2*x**2*y])
+
+ for method in ['nelder-mead', 'powell', 'cg', 'bfgs',
+ 'newton-cg', 'l-bfgs-b', 'tnc',
+ 'cobyla', 'cobyqa', 'slsqp']:
+ if method in ('nelder-mead', 'powell', 'cobyla', 'cobyqa'):
+ jac = None
+ else:
+ jac = dfunc
+
+ sol1 = optimize.minimize(func, [2, 2], jac=jac, tol=1e-10,
+ method=method)
+ sol2 = optimize.minimize(func, [2, 2], jac=jac, tol=1.0,
+ method=method)
+ assert func(sol1.x) < func(sol2.x), \
+ f"{method}: {func(sol1.x)} vs. {func(sol2.x)}"
+
+ @pytest.mark.fail_slow(10)
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning') # See gh-18547
+ @pytest.mark.parametrize('method',
+ ['fmin', 'fmin_powell', 'fmin_cg', 'fmin_bfgs',
+ 'fmin_ncg', 'fmin_l_bfgs_b', 'fmin_tnc',
+ 'fmin_slsqp'] + MINIMIZE_METHODS)
+ def test_minimize_callback_copies_array(self, method):
+ # Check that arrays passed to callbacks are not modified
+ # inplace by the optimizer afterward
+
+ if method in ('fmin_tnc', 'fmin_l_bfgs_b'):
+ def func(x):
+ return optimize.rosen(x), optimize.rosen_der(x)
+ else:
+ func = optimize.rosen
+ jac = optimize.rosen_der
+ hess = optimize.rosen_hess
+
+ x0 = np.zeros(10)
+
+ # Set options
+ kwargs = {}
+ if method.startswith('fmin'):
+ routine = getattr(optimize, method)
+ if method == 'fmin_slsqp':
+ kwargs['iter'] = 5
+ elif method == 'fmin_tnc':
+ kwargs['maxfun'] = 100
+ elif method in ('fmin', 'fmin_powell'):
+ kwargs['maxiter'] = 3500
+ else:
+ kwargs['maxiter'] = 5
+ else:
+ def routine(*a, **kw):
+ kw['method'] = method
+ return optimize.minimize(*a, **kw)
+
+ if method == 'tnc':
+ kwargs['options'] = dict(maxfun=100)
+ elif method == 'cobyla':
+ kwargs['options'] = dict(maxiter=100)
+ else:
+ kwargs['options'] = dict(maxiter=5)
+
+ if method in ('fmin_ncg',):
+ kwargs['fprime'] = jac
+ elif method in ('newton-cg',):
+ kwargs['jac'] = jac
+ elif method in ('trust-krylov', 'trust-exact', 'trust-ncg', 'dogleg',
+ 'trust-constr'):
+ kwargs['jac'] = jac
+ kwargs['hess'] = hess
+
+ # Run with callback
+ results = []
+
+ def callback(x, *args, **kwargs):
+ assert not isinstance(x, optimize.OptimizeResult)
+ results.append((x, np.copy(x)))
+
+ routine(func, x0, callback=callback, **kwargs)
+
+ # Check returned arrays coincide with their copies
+ # and have no memory overlap
+ assert len(results) > 2
+ assert all(np.all(x == y) for x, y in results)
+ combinations = itertools.combinations(results, 2)
+ assert not any(np.may_share_memory(x[0], y[0]) for x, y in combinations)
+
+ @pytest.mark.parametrize('method', ['nelder-mead', 'powell', 'cg',
+ 'bfgs', 'newton-cg', 'l-bfgs-b',
+ 'tnc', 'cobyla', 'cobyqa', 'slsqp'])
+ def test_no_increase(self, method):
+ # Check that the solver doesn't return a value worse than the
+ # initial point.
+
+ def func(x):
+ return (x - 1)**2
+
+ def bad_grad(x):
+ # purposefully invalid gradient function, simulates a case
+ # where line searches start failing
+ return 2*(x - 1) * (-1) - 2
+
+ x0 = np.array([2.0])
+ f0 = func(x0)
+ jac = bad_grad
+ options = dict(maxfun=20) if method == 'tnc' else dict(maxiter=20)
+ if method in ['nelder-mead', 'powell', 'cobyla', 'cobyqa']:
+ jac = None
+ sol = optimize.minimize(func, x0, jac=jac, method=method,
+ options=options)
+ assert_equal(func(sol.x), sol.fun)
+
+ if method == 'slsqp':
+ pytest.xfail("SLSQP returns slightly worse")
+ assert func(sol.x) <= f0
+
+ def test_slsqp_respect_bounds(self):
+ # Regression test for gh-3108
+ def f(x):
+ return sum((x - np.array([1., 2., 3., 4.]))**2)
+
+ def cons(x):
+ a = np.array([[-1, -1, -1, -1], [-3, -3, -2, -1]])
+ return np.concatenate([np.dot(a, x) + np.array([5, 10]), x])
+
+ x0 = np.array([0.5, 1., 1.5, 2.])
+ res = optimize.minimize(f, x0, method='slsqp',
+ constraints={'type': 'ineq', 'fun': cons})
+ assert_allclose(res.x, np.array([0., 2, 5, 8])/3, atol=1e-12)
+
+ @pytest.mark.parametrize('method', ['Nelder-Mead', 'Powell', 'CG', 'BFGS',
+ 'Newton-CG', 'L-BFGS-B', 'SLSQP',
+ 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov',
+ 'cobyqa'])
+ def test_respect_maxiter(self, method):
+ # Check that the number of iterations equals max_iter, assuming
+ # convergence doesn't establish before
+ MAXITER = 4
+
+ x0 = np.zeros(10)
+
+ sf = ScalarFunction(optimize.rosen, x0, (), optimize.rosen_der,
+ optimize.rosen_hess, None, None)
+
+ # Set options
+ kwargs = {'method': method, 'options': dict(maxiter=MAXITER)}
+
+ if method in ('Newton-CG',):
+ kwargs['jac'] = sf.grad
+ elif method in ('trust-krylov', 'trust-exact', 'trust-ncg', 'dogleg',
+ 'trust-constr'):
+ kwargs['jac'] = sf.grad
+ kwargs['hess'] = sf.hess
+
+ sol = optimize.minimize(sf.fun, x0, **kwargs)
+ assert sol.nit == MAXITER
+ assert sol.nfev >= sf.nfev
+ if hasattr(sol, 'njev'):
+ assert sol.njev >= sf.ngev
+
+ # method specific tests
+ if method == 'SLSQP':
+ assert sol.status == 9 # Iteration limit reached
+ elif method == 'cobyqa':
+ assert sol.status == 6 # Iteration limit reached
+
+ @pytest.mark.parametrize('method', ['Nelder-Mead', 'Powell',
+ 'fmin', 'fmin_powell'])
+ def test_runtime_warning(self, method):
+ x0 = np.zeros(10)
+ sf = ScalarFunction(optimize.rosen, x0, (), optimize.rosen_der,
+ optimize.rosen_hess, None, None)
+ options = {"maxiter": 1, "disp": True}
+ with pytest.warns(RuntimeWarning,
+ match=r'Maximum number of iterations'):
+ if method.startswith('fmin'):
+ routine = getattr(optimize, method)
+ routine(sf.fun, x0, **options)
+ else:
+ optimize.minimize(sf.fun, x0, method=method, options=options)
+
+ def test_respect_maxiter_trust_constr_ineq_constraints(self):
+ # special case of minimization with trust-constr and inequality
+ # constraints to check maxiter limit is obeyed when using internal
+ # method 'tr_interior_point'
+ MAXITER = 4
+ f = optimize.rosen
+ jac = optimize.rosen_der
+ hess = optimize.rosen_hess
+
+ def fun(x):
+ return np.array([0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]])
+ cons = ({'type': 'ineq',
+ 'fun': fun},)
+
+ x0 = np.zeros(10)
+ sol = optimize.minimize(f, x0, constraints=cons, jac=jac, hess=hess,
+ method='trust-constr',
+ options=dict(maxiter=MAXITER))
+ assert sol.nit == MAXITER
+
+ def test_minimize_automethod(self):
+ def f(x):
+ return x**2
+
+ def cons(x):
+ return x - 2
+
+ x0 = np.array([10.])
+ sol_0 = optimize.minimize(f, x0)
+ sol_1 = optimize.minimize(f, x0, constraints=[{'type': 'ineq',
+ 'fun': cons}])
+ sol_2 = optimize.minimize(f, x0, bounds=[(5, 10)])
+ sol_3 = optimize.minimize(f, x0,
+ constraints=[{'type': 'ineq', 'fun': cons}],
+ bounds=[(5, 10)])
+ sol_4 = optimize.minimize(f, x0,
+ constraints=[{'type': 'ineq', 'fun': cons}],
+ bounds=[(1, 10)])
+ for sol in [sol_0, sol_1, sol_2, sol_3, sol_4]:
+ assert sol.success
+ assert_allclose(sol_0.x, 0, atol=1e-7)
+ assert_allclose(sol_1.x, 2, atol=1e-7)
+ assert_allclose(sol_2.x, 5, atol=1e-7)
+ assert_allclose(sol_3.x, 5, atol=1e-7)
+ assert_allclose(sol_4.x, 2, atol=1e-7)
+
+ def test_minimize_coerce_args_param(self):
+ # Regression test for gh-3503
+ def Y(x, c):
+ return np.sum((x-c)**2)
+
+ def dY_dx(x, c=None):
+ return 2*(x-c)
+
+ c = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
+ rng = np.random.default_rng(1234)
+ xinit = rng.standard_normal(len(c))
+ optimize.minimize(Y, xinit, jac=dY_dx, args=(c), method="BFGS")
+
+ def test_initial_step_scaling(self):
+ # Check that optimizer initial step is not huge even if the
+ # function and gradients are
+
+ scales = [1e-50, 1, 1e50]
+ methods = ['CG', 'BFGS', 'L-BFGS-B', 'Newton-CG']
+
+ def f(x):
+ if first_step_size[0] is None and x[0] != x0[0]:
+ first_step_size[0] = abs(x[0] - x0[0])
+ if abs(x).max() > 1e4:
+ raise AssertionError("Optimization stepped far away!")
+ return scale*(x[0] - 1)**2
+
+ def g(x):
+ return np.array([scale*(x[0] - 1)])
+
+ for scale, method in itertools.product(scales, methods):
+ if method in ('CG', 'BFGS'):
+ options = dict(gtol=scale*1e-8)
+ else:
+ options = dict()
+
+ if scale < 1e-10 and method in ('L-BFGS-B', 'Newton-CG'):
+ # XXX: return initial point if they see small gradient
+ continue
+
+ x0 = [-1.0]
+ first_step_size = [None]
+ res = optimize.minimize(f, x0, jac=g, method=method,
+ options=options)
+
+ err_msg = f"{method} {scale}: {first_step_size}: {res}"
+
+ assert res.success, err_msg
+ assert_allclose(res.x, [1.0], err_msg=err_msg)
+ assert res.nit <= 3, err_msg
+
+ if scale > 1e-10:
+ if method in ('CG', 'BFGS'):
+ assert_allclose(first_step_size[0], 1.01, err_msg=err_msg)
+ else:
+ # Newton-CG and L-BFGS-B use different logic for the first
+ # step, but are both scaling invariant with step sizes ~ 1
+ assert first_step_size[0] > 0.5 and first_step_size[0] < 3, err_msg
+ else:
+ # step size has upper bound of ||grad||, so line
+ # search makes many small steps
+ pass
+
+ @pytest.mark.parametrize('method', ['nelder-mead', 'powell', 'cg', 'bfgs',
+ 'newton-cg', 'l-bfgs-b', 'tnc',
+ 'cobyqa', 'slsqp',
+ 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov'])
+ def test_nan_values(self, method):
+
+ # Check nan values result to failed exit status
+
+ # test is dependent on exact seed
+ rng = np.random.default_rng(123122)
+
+ count = [0]
+
+ def func(x):
+ return np.nan
+
+ def func2(x):
+ count[0] += 1
+ if count[0] > 2:
+ return np.nan
+ else:
+ return rng.random()
+
+ def grad(x):
+ return np.array([1.0])
+
+ def hess(x):
+ return np.array([[1.0]])
+
+ x0 = np.array([1.0])
+
+ needs_grad = method in ('newton-cg', 'trust-krylov', 'trust-exact',
+ 'trust-ncg', 'dogleg')
+ needs_hess = method in ('trust-krylov', 'trust-exact', 'trust-ncg',
+ 'dogleg')
+
+ funcs = [func, func2]
+ grads = [grad] if needs_grad else [grad, None]
+ hesss = [hess] if needs_hess else [hess, None]
+ options = dict(maxfun=20) if method == 'tnc' else dict(maxiter=20)
+
+ with np.errstate(invalid='ignore'), warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.*", UserWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use Hessian.*", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use gradient.*", RuntimeWarning)
+
+ for f, g, h in itertools.product(funcs, grads, hesss):
+ count = [0]
+ sol = optimize.minimize(f, x0, jac=g, hess=h, method=method,
+ options=options)
+ assert_equal(sol.success, False)
+
+ @pytest.mark.parametrize('method', ['nelder-mead', 'cg', 'bfgs',
+ 'l-bfgs-b', 'tnc',
+ 'cobyla', 'cobyqa', 'slsqp',
+ 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov'])
+ def test_duplicate_evaluations(self, method):
+ # check that there are no duplicate evaluations for any methods
+ jac = hess = None
+ if method in ('newton-cg', 'trust-krylov', 'trust-exact',
+ 'trust-ncg', 'dogleg'):
+ jac = self.grad
+ if method in ('trust-krylov', 'trust-exact', 'trust-ncg',
+ 'dogleg'):
+ hess = self.hess
+
+ with np.errstate(invalid='ignore'), warnings.catch_warnings():
+ # for trust-constr
+ warnings.filterwarnings("ignore", "delta_grad == 0.*", UserWarning)
+ optimize.minimize(self.func, self.startparams,
+ method=method, jac=jac, hess=hess)
+
+ for i in range(1, len(self.trace.t)):
+ if np.array_equal(self.trace.t[i - 1], self.trace.t[i]):
+ raise RuntimeError(
+ f"Duplicate evaluations made by {method}")
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ @pytest.mark.parametrize('method', MINIMIZE_METHODS_NEW_CB)
+ @pytest.mark.parametrize('new_cb_interface', [0, 1, 2])
+ def test_callback_stopiteration(self, method, new_cb_interface):
+ # Check that if callback raises StopIteration, optimization
+ # terminates with the same result as if iterations were limited
+
+ def f(x):
+ f.flag = False # check that f isn't called after StopIteration
+ return optimize.rosen(x)
+ f.flag = False
+
+ def g(x):
+ f.flag = False
+ return optimize.rosen_der(x)
+
+ def h(x):
+ f.flag = False
+ return optimize.rosen_hess(x)
+
+ maxiter = 5
+
+ if new_cb_interface == 1:
+ def callback_interface(*, intermediate_result):
+ assert intermediate_result.fun == f(intermediate_result.x)
+ callback()
+ elif new_cb_interface == 2:
+ class Callback:
+ def __call__(self, intermediate_result: OptimizeResult):
+ assert intermediate_result.fun == f(intermediate_result.x)
+ callback()
+ callback_interface = Callback()
+ else:
+ def callback_interface(xk, *args): # type: ignore[misc]
+ callback()
+
+ def callback():
+ callback.i += 1
+ callback.flag = False
+ if callback.i == maxiter:
+ callback.flag = True
+ raise StopIteration()
+ callback.i = 0
+ callback.flag = False
+
+ kwargs = {'x0': [1.1]*5, 'method': method,
+ 'fun': f, 'jac': g, 'hess': h}
+
+ res = optimize.minimize(**kwargs, callback=callback_interface)
+ if method == 'nelder-mead':
+ maxiter = maxiter + 1 # nelder-mead counts differently
+ if method == 'cobyqa':
+ ref = optimize.minimize(**kwargs, options={'maxfev': maxiter})
+ assert res.nfev == ref.nfev == maxiter
+ elif method == 'cobyla':
+ # COBYLA calls the callback once per iteration, not once per function
+ # evaluation, so this test is not applicable. However we can test
+ # the COBYLA status to verify that res stopped back on the callback
+ # and ref stopped based on the iteration limit.
+ # COBYLA requires at least n+2 function evaluations
+ maxiter = max(maxiter, len(kwargs['x0'])+2)
+ ref = optimize.minimize(**kwargs, options={'maxiter': maxiter})
+ assert res.status == 30
+ assert res.message == ("Return from COBYLA because the callback function "
+ "requested termination")
+ assert ref.status == 3
+ assert ref.message == ("Return from COBYLA because the objective function "
+ "has been evaluated MAXFUN times.")
+ # Return early because res/ref will be unequal for COBYLA for the reasons
+ # mentioned above.
+ return
+ else:
+ ref = optimize.minimize(**kwargs, options={'maxiter': maxiter})
+ assert res.message.startswith("`callback` raised `StopIteration`")
+ assert res.nit == ref.nit == maxiter
+ if method != 'slsqp':
+ # Unlike all other methods, apparently SLSQP updates x/fun after the last
+ # call to the callback
+ assert res.fun == ref.fun
+ assert_equal(res.x, ref.x)
+ assert res.status == 3 if method in {'trust-constr', 'cobyqa'} else 99
+ if method != 'cobyqa':
+ assert not res.success
+
+ def test_ndim_error(self):
+ msg = "'x0' must only have one dimension."
+ with assert_raises(ValueError, match=msg):
+ optimize.minimize(lambda x: x, np.ones((2, 1)))
+
+ @pytest.mark.parametrize('method', ('nelder-mead', 'l-bfgs-b', 'tnc',
+ 'powell', 'cobyla', 'cobyqa',
+ 'trust-constr'))
+ def test_minimize_invalid_bounds(self, method):
+ def f(x):
+ return np.sum(x**2)
+
+ bounds = Bounds([1, 2], [3, 4])
+ msg = 'The number of bounds is not compatible with the length of `x0`.'
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize(f, x0=[1, 2, 3], method=method, bounds=bounds)
+
+ bounds = Bounds([1, 6, 1], [3, 4, 2])
+ msg = 'An upper bound is less than the corresponding lower bound.'
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize(f, x0=[1, 2, 3], method=method, bounds=bounds)
+
+ @pytest.mark.parametrize('method', ['bfgs', 'cg', 'newton-cg', 'powell'])
+ def test_minimize_warnings_gh1953(self, method):
+ # test that minimize methods produce warnings rather than just using
+ # `print`; see gh-1953.
+ kwargs = {} if method=='powell' else {'jac': optimize.rosen_der}
+ warning_type = (RuntimeWarning if method=='powell'
+ else optimize.OptimizeWarning)
+
+ options = {'disp': True, 'maxiter': 10}
+ with pytest.warns(warning_type, match='Maximum number'):
+ optimize.minimize(lambda x: optimize.rosen(x), [0, 0],
+ method=method, options=options, **kwargs)
+
+ options['disp'] = False
+ optimize.minimize(lambda x: optimize.rosen(x), [0, 0],
+ method=method, options=options, **kwargs)
+
+
+@pytest.mark.parametrize(
+ 'method',
+ ['l-bfgs-b', 'tnc', 'Powell', 'Nelder-Mead', 'cobyqa']
+)
+def test_minimize_with_scalar(method):
+ # checks that minimize works with a scalar being provided to it.
+ def f(x):
+ return np.sum(x ** 2)
+
+ res = optimize.minimize(f, 17, bounds=[(-100, 100)], method=method)
+ assert res.success
+ assert_allclose(res.x, [0.0], atol=1e-5)
+
+
+class TestLBFGSBBounds:
+ def setup_method(self):
+ self.bounds = ((1, None), (None, None))
+ self.solution = (1, 0)
+
+ def fun(self, x, p=2.0):
+ return 1.0 / p * (x[0]**p + x[1]**p)
+
+ def jac(self, x, p=2.0):
+ return x**(p - 1)
+
+ def fj(self, x, p=2.0):
+ return self.fun(x, p), self.jac(x, p)
+
+ def test_l_bfgs_b_bounds(self):
+ x, f, d = optimize.fmin_l_bfgs_b(self.fun, [0, -1],
+ fprime=self.jac,
+ bounds=self.bounds)
+ assert d['warnflag'] == 0, d['task']
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_l_bfgs_b_funjac(self):
+ # L-BFGS-B with fun and jac combined and extra arguments
+ x, f, d = optimize.fmin_l_bfgs_b(self.fj, [0, -1], args=(2.0, ),
+ bounds=self.bounds)
+ assert d['warnflag'] == 0, d['task']
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_minimize_l_bfgs_b_bounds(self):
+ # Minimize with method='L-BFGS-B' with bounds
+ res = optimize.minimize(self.fun, [0, -1], method='L-BFGS-B',
+ jac=self.jac, bounds=self.bounds)
+ assert res['success'], res['message']
+ assert_allclose(res.x, self.solution, atol=1e-6)
+
+ @pytest.mark.parametrize('bounds', [
+ ([(10, 1), (1, 10)]),
+ ([(1, 10), (10, 1)]),
+ ([(10, 1), (10, 1)])
+ ])
+ def test_minimize_l_bfgs_b_incorrect_bounds(self, bounds):
+ with pytest.raises(ValueError, match='.*bound.*'):
+ optimize.minimize(self.fun, [0, -1], method='L-BFGS-B',
+ jac=self.jac, bounds=bounds)
+
+ def test_minimize_l_bfgs_b_bounds_FD(self):
+ # test that initial starting value outside bounds doesn't raise
+ # an error (done with clipping).
+ # test all different finite differences combos, with and without args
+
+ jacs = ['2-point', '3-point', None]
+ argss = [(2.,), ()]
+ for jac, args in itertools.product(jacs, argss):
+ res = optimize.minimize(self.fun, [0, -1], args=args,
+ method='L-BFGS-B',
+ jac=jac, bounds=self.bounds,
+ options={'finite_diff_rel_step': None})
+ assert res['success'], res['message']
+ assert_allclose(res.x, self.solution, atol=1e-6)
+
+
+class TestOptimizeScalar:
+ def setup_method(self):
+ self.solution = 1.5
+
+ def fun(self, x, a=1.5):
+ """Objective function"""
+ return (x - a)**2 - 0.8
+
+ def test_brent(self):
+ x = optimize.brent(self.fun)
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.brent(self.fun, brack=(-3, -2))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.brent(self.fun, full_output=True)
+ assert_allclose(x[0], self.solution, atol=1e-6)
+
+ x = optimize.brent(self.fun, brack=(-15, -1, 15))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ message = r"\(f\(xb\) < f\(xa\)\) and \(f\(xb\) < f\(xc\)\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.brent(self.fun, brack=(-1, 0, 1))
+
+ message = r"\(xa < xb\) and \(xb < xc\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.brent(self.fun, brack=(0, -1, 1))
+
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ def test_golden(self):
+ x = optimize.golden(self.fun)
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, brack=(-3, -2))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, full_output=True)
+ assert_allclose(x[0], self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, brack=(-15, -1, 15))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, tol=0)
+ assert_allclose(x, self.solution)
+
+ maxiter_test_cases = [0, 1, 5]
+ for maxiter in maxiter_test_cases:
+ x0 = optimize.golden(self.fun, maxiter=0, full_output=True)
+ x = optimize.golden(self.fun, maxiter=maxiter, full_output=True)
+ nfev0, nfev = x0[2], x[2]
+ assert_equal(nfev - nfev0, maxiter)
+
+ message = r"\(f\(xb\) < f\(xa\)\) and \(f\(xb\) < f\(xc\)\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.golden(self.fun, brack=(-1, 0, 1))
+
+ message = r"\(xa < xb\) and \(xb < xc\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.golden(self.fun, brack=(0, -1, 1))
+
+ def test_fminbound(self):
+ x = optimize.fminbound(self.fun, 0, 1)
+ assert_allclose(x, 1, atol=1e-4)
+
+ x = optimize.fminbound(self.fun, 1, 5)
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.fminbound(self.fun, np.array([1]), np.array([5]))
+ assert_allclose(x, self.solution, atol=1e-6)
+ assert_raises(ValueError, optimize.fminbound, self.fun, 5, 1)
+
+ def test_fminbound_scalar(self):
+ with pytest.raises(ValueError, match='.*must be finite scalars.*'):
+ optimize.fminbound(self.fun, np.zeros((1, 2)), 1)
+
+ x = optimize.fminbound(self.fun, 1, np.array(5))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_gh11207(self):
+ def fun(x):
+ return x**2
+ optimize.fminbound(fun, 0, 0)
+
+ def test_minimize_scalar(self):
+ # combine all tests above for the minimize_scalar wrapper
+ x = optimize.minimize_scalar(self.fun).x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, method='Brent')
+ assert x.success
+
+ x = optimize.minimize_scalar(self.fun, method='Brent',
+ options=dict(maxiter=3))
+ assert not x.success
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-3, -2),
+ args=(1.5, ), method='Brent').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, method='Brent',
+ args=(1.5,)).x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-15, -1, 15),
+ args=(1.5, ), method='Brent').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-3, -2),
+ args=(1.5, ), method='golden').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, method='golden',
+ args=(1.5,)).x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-15, -1, 15),
+ args=(1.5, ), method='golden').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bounds=(0, 1), args=(1.5,),
+ method='Bounded').x
+ assert_allclose(x, 1, atol=1e-4)
+
+ x = optimize.minimize_scalar(self.fun, bounds=(1, 5), args=(1.5, ),
+ method='bounded').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bounds=(np.array([1]),
+ np.array([5])),
+ args=(np.array([1.5]), ),
+ method='bounded').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ assert_raises(ValueError, optimize.minimize_scalar, self.fun,
+ bounds=(5, 1), method='bounded', args=(1.5, ))
+
+ assert_raises(ValueError, optimize.minimize_scalar, self.fun,
+ bounds=(np.zeros(2), 1), method='bounded', args=(1.5, ))
+
+ x = optimize.minimize_scalar(self.fun, bounds=(1, np.array(5)),
+ method='bounded').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_minimize_scalar_custom(self):
+ # This function comes from the documentation example.
+ def custmin(fun, bracket, args=(), maxfev=None, stepsize=0.1,
+ maxiter=100, callback=None, **options):
+ bestx = (bracket[1] + bracket[0]) / 2.0
+ besty = fun(bestx)
+ funcalls = 1
+ niter = 0
+ improved = True
+ stop = False
+
+ while improved and not stop and niter < maxiter:
+ improved = False
+ niter += 1
+ for testx in [bestx - stepsize, bestx + stepsize]:
+ testy = fun(testx, *args)
+ funcalls += 1
+ if testy < besty:
+ besty = testy
+ bestx = testx
+ improved = True
+ if callback is not None:
+ callback(bestx)
+ if maxfev is not None and funcalls >= maxfev:
+ stop = True
+ break
+
+ return optimize.OptimizeResult(fun=besty, x=bestx, nit=niter,
+ nfev=funcalls, success=(niter > 1))
+
+ res = optimize.minimize_scalar(self.fun, bracket=(0, 4),
+ method=custmin,
+ options=dict(stepsize=0.05))
+ assert_allclose(res.x, self.solution, atol=1e-6)
+
+ def test_minimize_scalar_coerce_args_param(self):
+ # Regression test for gh-3503
+ optimize.minimize_scalar(self.fun, args=1.5)
+
+ @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden'])
+ def test_disp(self, method):
+ # test that all minimize_scalar methods accept a disp option.
+ for disp in [0, 1, 2, 3]:
+ optimize.minimize_scalar(self.fun, options={"disp": disp})
+
+ @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden'])
+ def test_result_attributes(self, method):
+ kwargs = {"bounds": [-10, 10]} if method == 'bounded' else {}
+ result = optimize.minimize_scalar(self.fun, method=method, **kwargs)
+ assert hasattr(result, "x")
+ assert hasattr(result, "success")
+ assert hasattr(result, "message")
+ assert hasattr(result, "fun")
+ assert hasattr(result, "nfev")
+ assert hasattr(result, "nit")
+
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden'])
+ def test_nan_values(self, method):
+ # Check nan values result to failed exit status
+
+ count = [0]
+
+ def func(x):
+ count[0] += 1
+ if count[0] > 4:
+ return np.nan
+ else:
+ return x**2 + 0.1 * np.sin(x)
+
+ bracket = (-1, 0, 1)
+ bounds = (-1, 1)
+
+ with np.errstate(invalid='ignore'), warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.*", UserWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use Hessian.*", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use gradient.*", RuntimeWarning)
+
+ count = [0]
+
+ kwargs = {"bounds": bounds} if method == 'bounded' else {}
+ sol = optimize.minimize_scalar(func, bracket=bracket,
+ **kwargs, method=method,
+ options=dict(maxiter=20))
+ assert_equal(sol.success, False)
+
+ def test_minimize_scalar_defaults_gh10911(self):
+ # Previously, bounds were silently ignored unless `method='bounds'`
+ # was chosen. See gh-10911. Check that this is no longer the case.
+ def f(x):
+ return x**2
+
+ res = optimize.minimize_scalar(f)
+ assert_allclose(res.x, 0, atol=1e-8)
+
+ res = optimize.minimize_scalar(f, bounds=(1, 100),
+ options={'xatol': 1e-10})
+ assert_allclose(res.x, 1)
+
+ def test_minimize_non_finite_bounds_gh10911(self):
+ # Previously, minimize_scalar misbehaved with infinite bounds.
+ # See gh-10911. Check that it now raises an error, instead.
+ msg = "Optimization bounds must be finite scalars."
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize_scalar(np.sin, bounds=(1, np.inf))
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize_scalar(np.sin, bounds=(np.nan, 1))
+
+ @pytest.mark.parametrize("method", ['brent', 'golden'])
+ def test_minimize_unbounded_method_with_bounds_gh10911(self, method):
+ # Previously, `bounds` were silently ignored when `method='brent'` or
+ # `method='golden'`. See gh-10911. Check that error is now raised.
+ msg = "Use of `bounds` is incompatible with..."
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize_scalar(np.sin, method=method, bounds=(1, 2))
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ @pytest.mark.parametrize("method", MINIMIZE_SCALAR_METHODS)
+ @pytest.mark.parametrize("tol", [1, 1e-6])
+ @pytest.mark.parametrize("fshape", [(), (1,), (1, 1)])
+ def test_minimize_scalar_dimensionality_gh16196(self, method, tol, fshape):
+ # gh-16196 reported that the output shape of `minimize_scalar` was not
+ # consistent when an objective function returned an array. Check that
+ # `res.fun` and `res.x` are now consistent.
+ def f(x):
+ return np.array(x**4).reshape(fshape)
+
+ a, b = -0.1, 0.2
+ kwargs = (dict(bracket=(a, b)) if method != "bounded"
+ else dict(bounds=(a, b)))
+ kwargs.update(dict(method=method, tol=tol))
+
+ res = optimize.minimize_scalar(f, **kwargs)
+ assert res.x.shape == res.fun.shape == f(res.x).shape == fshape
+
+ @pytest.mark.parametrize('method', ['bounded', 'brent', 'golden'])
+ def test_minimize_scalar_warnings_gh1953(self, method):
+ # test that minimize_scalar methods produce warnings rather than just
+ # using `print`; see gh-1953.
+ def f(x):
+ return (x - 1)**2
+
+ kwargs = {}
+ kwd = 'bounds' if method == 'bounded' else 'bracket'
+ kwargs[kwd] = [-2, 10]
+
+ options = {'disp': True, 'maxiter': 3}
+ with pytest.warns(optimize.OptimizeWarning, match='Maximum number'):
+ optimize.minimize_scalar(f, method=method, options=options,
+ **kwargs)
+
+ options['disp'] = False
+ optimize.minimize_scalar(f, method=method, options=options, **kwargs)
+
+
+class TestBracket:
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ def test_errors_and_status_false(self):
+ # Check that `bracket` raises the errors it is supposed to
+ def f(x): # gh-14858
+ return x**2 if ((-1 < x) & (x < 1)) else 100.0
+
+ message = "The algorithm terminated without finding a valid bracket."
+ with pytest.raises(RuntimeError, match=message):
+ optimize.bracket(f, -1, 1)
+ with pytest.raises(RuntimeError, match=message):
+ optimize.bracket(f, -1, np.inf)
+ with pytest.raises(RuntimeError, match=message):
+ optimize.brent(f, brack=(-1, 1))
+ with pytest.raises(RuntimeError, match=message):
+ optimize.golden(f, brack=(-1, 1))
+
+ def f(x): # gh-5899
+ return -5 * x**5 + 4 * x**4 - 12 * x**3 + 11 * x**2 - 2 * x + 1
+
+ message = "No valid bracket was found before the iteration limit..."
+ with pytest.raises(RuntimeError, match=message):
+ optimize.bracket(f, -0.5, 0.5, maxiter=10)
+
+ @pytest.mark.parametrize('method', ('brent', 'golden'))
+ def test_minimize_scalar_success_false(self, method):
+ # Check that status information from `bracket` gets to minimize_scalar
+ def f(x): # gh-14858
+ return x**2 if ((-1 < x) & (x < 1)) else 100.0
+
+ message = "The algorithm terminated without finding a valid bracket."
+
+ res = optimize.minimize_scalar(f, bracket=(-1, 1), method=method)
+ assert not res.success
+ assert message in res.message
+ assert res.nfev == 3
+ assert res.nit == 0
+ assert res.fun == 100
+
+
+def test_brent_negative_tolerance():
+ assert_raises(ValueError, optimize.brent, np.cos, tol=-.01)
+
+
+class TestNewtonCg:
+ def test_rosenbrock(self):
+ x0 = np.array([-1.2, 1.0])
+ sol = optimize.minimize(optimize.rosen, x0,
+ jac=optimize.rosen_der,
+ hess=optimize.rosen_hess,
+ tol=1e-5,
+ method='Newton-CG')
+ assert sol.success, sol.message
+ assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4)
+
+ def test_himmelblau(self):
+ x0 = np.array(himmelblau_x0)
+ sol = optimize.minimize(himmelblau,
+ x0,
+ jac=himmelblau_grad,
+ hess=himmelblau_hess,
+ method='Newton-CG',
+ tol=1e-6)
+ assert sol.success, sol.message
+ assert_allclose(sol.x, himmelblau_xopt, rtol=1e-4)
+ assert_allclose(sol.fun, himmelblau_min, atol=1e-4)
+
+ def test_finite_difference(self):
+ x0 = np.array([-1.2, 1.0])
+ sol = optimize.minimize(optimize.rosen, x0,
+ jac=optimize.rosen_der,
+ hess='2-point',
+ tol=1e-5,
+ method='Newton-CG')
+ assert sol.success, sol.message
+ assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4)
+
+ def test_hessian_update_strategy(self):
+ x0 = np.array([-1.2, 1.0])
+ sol = optimize.minimize(optimize.rosen, x0,
+ jac=optimize.rosen_der,
+ hess=optimize.BFGS(),
+ tol=1e-5,
+ method='Newton-CG')
+ assert sol.success, sol.message
+ assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4)
+
+
+def test_line_for_search():
+ # _line_for_search is only used in _linesearch_powell, which is also
+ # tested below. Thus there are more tests of _line_for_search in the
+ # test_linesearch_powell_bounded function.
+
+ line_for_search = optimize._optimize._line_for_search
+ # args are x0, alpha, lower_bound, upper_bound
+ # returns lmin, lmax
+
+ lower_bound = np.array([-5.3, -1, -1.5, -3])
+ upper_bound = np.array([1.9, 1, 2.8, 3])
+
+ # test when starting in the bounds
+ x0 = np.array([0., 0, 0, 0])
+ # and when starting outside of the bounds
+ x1 = np.array([0., 2, -3, 0])
+
+ all_tests = (
+ (x0, np.array([1., 0, 0, 0]), -5.3, 1.9),
+ (x0, np.array([0., 1, 0, 0]), -1, 1),
+ (x0, np.array([0., 0, 1, 0]), -1.5, 2.8),
+ (x0, np.array([0., 0, 0, 1]), -3, 3),
+ (x0, np.array([1., 1, 0, 0]), -1, 1),
+ (x0, np.array([1., 0, -1, 2]), -1.5, 1.5),
+ (x0, np.array([2., 0, -1, 2]), -1.5, 0.95),
+ (x1, np.array([1., 0, 0, 0]), -5.3, 1.9),
+ (x1, np.array([0., 1, 0, 0]), -3, -1),
+ (x1, np.array([0., 0, 1, 0]), 1.5, 5.8),
+ (x1, np.array([0., 0, 0, 1]), -3, 3),
+ (x1, np.array([1., 1, 0, 0]), -3, -1),
+ (x1, np.array([1., 0, -1, 0]), -5.3, -1.5),
+ )
+
+ for x, alpha, lmin, lmax in all_tests:
+ mi, ma = line_for_search(x, alpha, lower_bound, upper_bound)
+ assert_allclose(mi, lmin, atol=1e-6)
+ assert_allclose(ma, lmax, atol=1e-6)
+
+ # now with infinite bounds
+ lower_bound = np.array([-np.inf, -1, -np.inf, -3])
+ upper_bound = np.array([np.inf, 1, 2.8, np.inf])
+
+ all_tests = (
+ (x0, np.array([1., 0, 0, 0]), -np.inf, np.inf),
+ (x0, np.array([0., 1, 0, 0]), -1, 1),
+ (x0, np.array([0., 0, 1, 0]), -np.inf, 2.8),
+ (x0, np.array([0., 0, 0, 1]), -3, np.inf),
+ (x0, np.array([1., 1, 0, 0]), -1, 1),
+ (x0, np.array([1., 0, -1, 2]), -1.5, np.inf),
+ (x1, np.array([1., 0, 0, 0]), -np.inf, np.inf),
+ (x1, np.array([0., 1, 0, 0]), -3, -1),
+ (x1, np.array([0., 0, 1, 0]), -np.inf, 5.8),
+ (x1, np.array([0., 0, 0, 1]), -3, np.inf),
+ (x1, np.array([1., 1, 0, 0]), -3, -1),
+ (x1, np.array([1., 0, -1, 0]), -5.8, np.inf),
+ )
+
+ for x, alpha, lmin, lmax in all_tests:
+ mi, ma = line_for_search(x, alpha, lower_bound, upper_bound)
+ assert_allclose(mi, lmin, atol=1e-6)
+ assert_allclose(ma, lmax, atol=1e-6)
+
+
+def test_linesearch_powell():
+ # helper function in optimize.py, not a public function.
+ linesearch_powell = optimize._optimize._linesearch_powell
+ # args are func, p, xi, fval, lower_bound=None, upper_bound=None, tol=1e-3
+ # returns new_fval, p + direction, direction
+ def func(x):
+ return np.sum((x - np.array([-1.0, 2.0, 1.5, -0.4])) ** 2)
+ p0 = np.array([0., 0, 0, 0])
+ fval = func(p0)
+ lower_bound = np.array([-np.inf] * 4)
+ upper_bound = np.array([np.inf] * 4)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -1),
+ (np.array([0., 1, 0, 0]), 2),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), 1.25),
+ (np.array([0., 0, 1, 1]), .55),
+ (np.array([2., 0, -1, 1]), -.65),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi,
+ fval=fval, tol=1e-5)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+
+def test_linesearch_powell_bounded():
+ # helper function in optimize.py, not a public function.
+ linesearch_powell = optimize._optimize._linesearch_powell
+ # args are func, p, xi, fval, lower_bound=None, upper_bound=None, tol=1e-3
+ # returns new_fval, p+direction, direction
+ def func(x):
+ return np.sum((x - np.array([-1.0, 2.0, 1.5, -0.4])) ** 2)
+ p0 = np.array([0., 0, 0, 0])
+ fval = func(p0)
+
+ # first choose bounds such that the same tests from
+ # test_linesearch_powell should pass.
+ lower_bound = np.array([-2.]*4)
+ upper_bound = np.array([2.]*4)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -1),
+ (np.array([0., 1, 0, 0]), 2),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), 1.25),
+ (np.array([0., 0, 1, 1]), .55),
+ (np.array([2., 0, -1, 1]), -.65),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now choose bounds such that unbounded vs bounded gives different results
+ lower_bound = np.array([-.3]*3 + [-1])
+ upper_bound = np.array([.45]*3 + [.9])
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -.3),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), .45),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), .3),
+ (np.array([0., 0, 1, 1]), .45),
+ (np.array([2., 0, -1, 1]), -.15),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now choose as above but start outside the bounds
+ p0 = np.array([-1., 0, 0, 2])
+ fval = func(p0)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), .7),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), .45),
+ (np.array([0., 0, 0, 1]), -2.4),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(p0 + l * xi), atol=1e-6)
+ assert_allclose(p, p0 + l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now mix in inf
+ p0 = np.array([0., 0, 0, 0])
+ fval = func(p0)
+
+ # now choose bounds that mix inf
+ lower_bound = np.array([-.3, -np.inf, -np.inf, -1])
+ upper_bound = np.array([np.inf, .45, np.inf, .9])
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -.3),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), .3),
+ (np.array([0., 0, 1, 1]), .55),
+ (np.array([2., 0, -1, 1]), -.15),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now choose as above but start outside the bounds
+ p0 = np.array([-1., 0, 0, 2])
+ fval = func(p0)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), .7),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -2.4),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(p0 + l * xi), atol=1e-6)
+ assert_allclose(p, p0 + l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+
+def test_powell_limits():
+ # gh15342 - powell was going outside bounds for some function evaluations.
+ bounds = optimize.Bounds([0, 0], [0.6, 20])
+
+ def fun(x):
+ a, b = x
+ assert (x >= bounds.lb).all() and (x <= bounds.ub).all()
+ return a ** 2 + b ** 2
+
+ optimize.minimize(fun, x0=[0.6, 20], method='Powell', bounds=bounds)
+
+ # Another test from the original report - gh-13411
+ bounds = optimize.Bounds(lb=[0,], ub=[1,], keep_feasible=[True,])
+
+ def func(x):
+ assert x >= 0 and x <= 1
+ return np.exp(x)
+
+ optimize.minimize(fun=func, x0=[0.5], method='powell', bounds=bounds)
+
+
+def test_powell_output():
+ funs = [rosen, lambda x: np.array(rosen(x)), lambda x: np.array([rosen(x)])]
+ for fun in funs:
+ res = optimize.minimize(fun, x0=[0.6, 20], method='Powell')
+ assert np.isscalar(res.fun)
+
+
+class TestRosen:
+ @make_xp_test_case(optimize.rosen)
+ def test_rosen(self, xp):
+ # integer input should be promoted to the default floating type
+ x = xp.asarray([1, 1, 1])
+ xp_assert_equal(optimize.rosen(x),
+ xp.asarray(0.))
+
+ @make_xp_test_case(optimize.rosen_der)
+ def test_rosen_der(self, xp):
+ x = xp.asarray([1, 1, 1, 1])
+ xp_assert_equal(optimize.rosen_der(x),
+ xp.zeros_like(x, dtype=xp.asarray(1.).dtype))
+
+ @make_xp_test_case(optimize.rosen_hess, optimize.rosen_hess_prod)
+ def test_hess_prod(self, xp):
+ one = xp.asarray(1.)
+
+ # Compare rosen_hess(x) times p with rosen_hess_prod(x,p). See gh-1775.
+ x = xp.asarray([3, 4, 5])
+ p = xp.asarray([2, 2, 2])
+ hp = optimize.rosen_hess_prod(x, p)
+ p = xp.astype(p, one.dtype)
+ dothp = optimize.rosen_hess(x) @ p
+ xp_assert_equal(hp, dothp)
+
+
+def himmelblau(p):
+ """
+ R^2 -> R^1 test function for optimization. The function has four local
+ minima where himmelblau(xopt) == 0.
+ """
+ x, y = p
+ a = x*x + y - 11
+ b = x + y*y - 7
+ return a*a + b*b
+
+
+def himmelblau_grad(p):
+ x, y = p
+ return np.array([4*x**3 + 4*x*y - 42*x + 2*y**2 - 14,
+ 2*x**2 + 4*x*y + 4*y**3 - 26*y - 22])
+
+
+def himmelblau_hess(p):
+ x, y = p
+ return np.array([[12*x**2 + 4*y - 42, 4*x + 4*y],
+ [4*x + 4*y, 4*x + 12*y**2 - 26]])
+
+
+himmelblau_x0 = [-0.27, -0.9]
+himmelblau_xopt = [3, 2]
+himmelblau_min = 0.0
+
+
+def test_minimize_multiple_constraints():
+ # Regression test for gh-4240.
+ def func(x):
+ return np.array([25 - 0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]])
+
+ def func1(x):
+ return np.array([x[1]])
+
+ def func2(x):
+ return np.array([x[2]])
+
+ cons = ({'type': 'ineq', 'fun': func},
+ {'type': 'ineq', 'fun': func1},
+ {'type': 'ineq', 'fun': func2})
+
+ def f(x):
+ return -1 * (x[0] + x[1] + x[2])
+
+ res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons)
+ assert_allclose(res.x, [125, 0, 0], atol=1e-10)
+
+
+class TestOptimizeResultAttributes:
+ # Test that all minimizers return an OptimizeResult containing
+ # all the OptimizeResult attributes
+ def setup_method(self):
+ self.x0 = [5, 5]
+ self.func = optimize.rosen
+ self.jac = optimize.rosen_der
+ self.hess = optimize.rosen_hess
+ self.hessp = optimize.rosen_hess_prod
+ self.bounds = [(0., 10.), (0., 10.)]
+
+ @pytest.mark.fail_slow(2)
+ def test_attributes_present(self):
+ attributes = ['nit', 'nfev', 'x', 'success', 'status', 'fun',
+ 'message']
+ skip = {'cobyla': ['nit']}
+ for method in MINIMIZE_METHODS:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ ("Method .+ does not use (gradient|Hessian.*)"
+ " information"), RuntimeWarning)
+ res = optimize.minimize(self.func, self.x0, method=method,
+ jac=self.jac, hess=self.hess,
+ hessp=self.hessp)
+ for attribute in attributes:
+ if method in skip and attribute in skip[method]:
+ continue
+
+ assert hasattr(res, attribute)
+ assert attribute in dir(res)
+
+ # gh13001, OptimizeResult.message should be a str
+ assert isinstance(res.message, str)
+
+
+def f1(z, *params):
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
+
+
+def f2(z, *params):
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale))
+
+
+def f3(z, *params):
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale))
+
+
+def brute_func(z, *params):
+ return f1(z, *params) + f2(z, *params) + f3(z, *params)
+
+
+class TestBrute:
+ # Test the "brute force" method
+ def setup_method(self):
+ self.params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
+ self.rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
+ self.solution = np.array([-1.05665192, 1.80834843])
+
+ def brute_func(self, z, *params):
+ # an instance method optimizing
+ return brute_func(z, *params)
+
+ def test_brute(self):
+ # test fmin
+ resbrute = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True, finish=optimize.fmin)
+ assert_allclose(resbrute[0], self.solution, atol=1e-3)
+ assert_allclose(resbrute[1], brute_func(self.solution, *self.params),
+ atol=1e-3)
+
+ # test minimize
+ resbrute = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True,
+ finish=optimize.minimize)
+ assert_allclose(resbrute[0], self.solution, atol=1e-3)
+ assert_allclose(resbrute[1], brute_func(self.solution, *self.params),
+ atol=1e-3)
+
+ # test that brute can optimize an instance method (the other tests use
+ # a non-class based function
+ resbrute = optimize.brute(self.brute_func, self.rranges,
+ args=self.params, full_output=True,
+ finish=optimize.minimize)
+ assert_allclose(resbrute[0], self.solution, atol=1e-3)
+
+ def test_1D(self):
+ # test that for a 1-D problem the test function is passed an array,
+ # not a scalar.
+ def f(x):
+ assert len(x.shape) == 1
+ assert x.shape[0] == 1
+ return x ** 2
+
+ optimize.brute(f, [(-1, 1)], Ns=3, finish=None)
+
+ @pytest.mark.fail_slow(10)
+ def test_workers(self):
+ # check that parallel evaluation works
+ resbrute = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True, finish=None)
+
+ resbrute1 = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True, finish=None, workers=2)
+
+ assert_allclose(resbrute1[-1], resbrute[-1])
+ assert_allclose(resbrute1[0], resbrute[0])
+
+ def test_runtime_warning(self, capsys):
+ rng = np.random.default_rng(1234)
+
+ def func(z, *params):
+ return rng.random(1) * 1000 # never converged problem
+
+ msg = "final optimization did not succeed.*|Maximum number of function eval.*"
+ with pytest.warns(RuntimeWarning, match=msg):
+ optimize.brute(func, self.rranges, args=self.params, disp=True)
+
+ def test_coerce_args_param(self):
+ # optimize.brute should coerce non-iterable args to a tuple.
+ def f(x, *args):
+ return x ** args[0]
+
+ resbrute = optimize.brute(f, (slice(-4, 4, .25),), args=2)
+ assert_allclose(resbrute, 0)
+
+
+@pytest.mark.fail_slow(20)
+def test_cobyla_threadsafe():
+
+ # Verify that cobyla is threadsafe. Will segfault if it is not.
+
+ import concurrent.futures
+ import time
+
+ def objective1(x):
+ time.sleep(0.1)
+ return x[0]**2
+
+ def objective2(x):
+ time.sleep(0.1)
+ return (x[0]-1)**2
+
+ min_method = "COBYLA"
+
+ def minimizer1():
+ return optimize.minimize(objective1,
+ [0.0],
+ method=min_method)
+
+ def minimizer2():
+ return optimize.minimize(objective2,
+ [0.0],
+ method=min_method)
+
+ with concurrent.futures.ThreadPoolExecutor() as pool:
+ tasks = []
+ tasks.append(pool.submit(minimizer1))
+ tasks.append(pool.submit(minimizer2))
+ for t in tasks:
+ t.result()
+
+
+class TestIterationLimits:
+ # Tests that optimisation does not give up before trying requested
+ # number of iterations or evaluations. And that it does not succeed
+ # by exceeding the limits.
+ def setup_method(self):
+ self.funcalls = threading.local()
+
+ def slow_func(self, v):
+ if not hasattr(self.funcalls, 'c'):
+ self.funcalls.c = 0
+ self.funcalls.c += 1
+ r, t = np.sqrt(v[0]**2+v[1]**2), np.arctan2(v[0], v[1])
+ return np.sin(r*20 + t)+r*0.5
+
+ @pytest.mark.fail_slow(10)
+ def test_neldermead_limit(self):
+ self.check_limits("Nelder-Mead", 200)
+
+ def test_powell_limit(self):
+ self.check_limits("powell", 1000)
+
+ def check_limits(self, method, default_iters):
+ for start_v in [[0.1, 0.1], [1, 1], [2, 2]]:
+ for mfev in [50, 500, 5000]:
+ self.funcalls.c = 0
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxfev": mfev})
+ assert self.funcalls.c == res["nfev"]
+ if res["success"]:
+ assert res["nfev"] < mfev
+ else:
+ assert res["nfev"] >= mfev
+ for mit in [50, 500, 5000]:
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxiter": mit})
+ if res["success"]:
+ assert res["nit"] <= mit
+ else:
+ assert res["nit"] >= mit
+ for mfev, mit in [[50, 50], [5000, 5000], [5000, np.inf]]:
+ self.funcalls.c = 0
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxiter": mit,
+ "maxfev": mfev})
+ assert self.funcalls.c == res["nfev"]
+ if res["success"]:
+ assert res["nfev"] < mfev and res["nit"] <= mit
+ else:
+ assert res["nfev"] >= mfev or res["nit"] >= mit
+ for mfev, mit in [[np.inf, None], [None, np.inf]]:
+ self.funcalls.c = 0
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxiter": mit,
+ "maxfev": mfev})
+ assert self.funcalls.c == res["nfev"]
+ if res["success"]:
+ if mfev is None:
+ assert res["nfev"] < default_iters*2
+ else:
+ assert res["nit"] <= default_iters*2
+ else:
+ assert (res["nfev"] >= default_iters*2
+ or res["nit"] >= default_iters*2)
+
+
+def test_result_x_shape_when_len_x_is_one():
+ def fun(x):
+ return x * x
+
+ def jac(x):
+ return 2. * x
+
+ def hess(x):
+ return np.array([[2.]])
+
+ methods = ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'L-BFGS-B', 'TNC',
+ 'COBYLA', 'COBYQA', 'SLSQP']
+ for method in methods:
+ res = optimize.minimize(fun, np.array([0.1]), method=method)
+ assert res.x.shape == (1,)
+
+ # use jac + hess
+ methods = ['trust-constr', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov', 'Newton-CG']
+ for method in methods:
+ res = optimize.minimize(fun, np.array([0.1]), method=method, jac=jac,
+ hess=hess)
+ assert res.x.shape == (1,)
+
+
+class FunctionWithGradient:
+ def __init__(self):
+ self.number_of_calls = threading.local()
+
+ def __call__(self, x):
+ if not hasattr(self.number_of_calls, 'c'):
+ self.number_of_calls.c = 0
+ self.number_of_calls.c += 1
+ return np.sum(x**2), 2 * x
+
+
+@pytest.fixture
+def function_with_gradient():
+ return FunctionWithGradient()
+
+
+def test_memoize_jac_function_before_gradient(function_with_gradient):
+ memoized_function = MemoizeJac(function_with_gradient)
+
+ x0 = np.array([1.0, 2.0])
+ assert_allclose(memoized_function(x0), 5.0)
+ assert function_with_gradient.number_of_calls.c == 1
+
+ assert_allclose(memoized_function.derivative(x0), 2 * x0)
+ assert function_with_gradient.number_of_calls.c == 1, \
+ "function is not recomputed " \
+ "if gradient is requested after function value"
+
+ assert_allclose(
+ memoized_function(2 * x0), 20.0,
+ err_msg="different input triggers new computation")
+ assert function_with_gradient.number_of_calls.c == 2, \
+ "different input triggers new computation"
+
+
+def test_memoize_jac_gradient_before_function(function_with_gradient):
+ memoized_function = MemoizeJac(function_with_gradient)
+
+ x0 = np.array([1.0, 2.0])
+ assert_allclose(memoized_function.derivative(x0), 2 * x0)
+ assert function_with_gradient.number_of_calls.c == 1
+
+ assert_allclose(memoized_function(x0), 5.0)
+ assert function_with_gradient.number_of_calls.c == 1, \
+ "function is not recomputed " \
+ "if function value is requested after gradient"
+
+ assert_allclose(
+ memoized_function.derivative(2 * x0), 4 * x0,
+ err_msg="different input triggers new computation")
+ assert function_with_gradient.number_of_calls.c == 2, \
+ "different input triggers new computation"
+
+
+def test_memoize_jac_with_bfgs(function_with_gradient):
+ """ Tests that using MemoizedJac in combination with ScalarFunction
+ and BFGS does not lead to repeated function evaluations.
+ Tests changes made in response to GH11868.
+ """
+ memoized_function = MemoizeJac(function_with_gradient)
+ jac = memoized_function.derivative
+ hess = optimize.BFGS()
+
+ x0 = np.array([1.0, 0.5])
+ scalar_function = ScalarFunction(
+ memoized_function, x0, (), jac, hess, None, None)
+ assert function_with_gradient.number_of_calls.c == 1
+
+ scalar_function.fun(x0 + 0.1)
+ assert function_with_gradient.number_of_calls.c == 2
+
+ scalar_function.fun(x0 + 0.2)
+ assert function_with_gradient.number_of_calls.c == 3
+
+
+def test_gh12696():
+ # Test that optimize doesn't throw warning gh-12696
+ with assert_no_warnings():
+ optimize.fminbound(
+ lambda x: np.array([x**2]), -np.pi, np.pi, disp=False)
+
+
+# --- Test minimize with equal upper and lower bounds --- #
+
+def setup_test_equal_bounds():
+ # the success of test_equal_bounds depends on the exact seed
+ rng = np.random.default_rng(12223)
+ x0 = rng.random(4)
+ lb = np.array([0, 2, -1, -1.0])
+ ub = np.array([3, 2, 2, -1.0])
+ i_eb = (lb == ub)
+
+ def check_x(x, check_size=True, check_values=True):
+ if check_size:
+ assert x.size == 4
+ if check_values:
+ assert_allclose(x[i_eb], lb[i_eb])
+
+ def func(x):
+ check_x(x)
+ return optimize.rosen(x)
+
+ def grad(x):
+ check_x(x)
+ return optimize.rosen_der(x)
+
+ def callback(x, *args):
+ check_x(x)
+
+ def callback2(intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ check_x(intermediate_result.x)
+
+ def constraint1(x):
+ check_x(x, check_values=False)
+ return x[0:1] - 1
+
+ def jacobian1(x):
+ check_x(x, check_values=False)
+ dc = np.zeros_like(x)
+ dc[0] = 1
+ return dc
+
+ def constraint2(x):
+ check_x(x, check_values=False)
+ return x[2:3] - 0.5
+
+ def jacobian2(x):
+ check_x(x, check_values=False)
+ dc = np.zeros_like(x)
+ dc[2] = 1
+ return dc
+
+ c1a = NonlinearConstraint(constraint1, -np.inf, 0)
+ c1b = NonlinearConstraint(constraint1, -np.inf, 0, jacobian1)
+ c2a = NonlinearConstraint(constraint2, -np.inf, 0)
+ c2b = NonlinearConstraint(constraint2, -np.inf, 0, jacobian2)
+
+ # test using the three methods that accept bounds, use derivatives, and
+ # have some trouble when bounds fix variables
+ methods = ('L-BFGS-B', 'SLSQP', 'TNC')
+
+ # test w/out gradient, w/ gradient, and w/ combined objective/gradient
+ kwds = ({"fun": func, "jac": False},
+ {"fun": func, "jac": grad},
+ {"fun": (lambda x: (func(x), grad(x))),
+ "jac": True})
+
+ # test with both old- and new-style bounds
+ bound_types = (lambda lb, ub: list(zip(lb, ub)),
+ Bounds)
+
+ # Test for many combinations of constraints w/ and w/out jacobian
+ # Pairs in format: (test constraints, reference constraints)
+ # (always use analytical jacobian in reference)
+ constraints = ((None, None), ([], []),
+ (c1a, c1b), (c2b, c2b),
+ ([c1b], [c1b]), ([c2a], [c2b]),
+ ([c1a, c2a], [c1b, c2b]),
+ ([c1a, c2b], [c1b, c2b]),
+ ([c1b, c2b], [c1b, c2b]))
+
+ # test with and without callback function
+ callbacks = (None, callback, callback2)
+
+ data = {"methods": methods, "kwds": kwds, "bound_types": bound_types,
+ "constraints": constraints, "callbacks": callbacks,
+ "lb": lb, "ub": ub, "x0": x0, "i_eb": i_eb}
+
+ return data
+
+
+eb_data = setup_test_equal_bounds()
+
+
+# This test is about handling fixed variables, not the accuracy of the solvers
+@pytest.mark.xfail_on_32bit("Failures due to floating point issues, not logic")
+@pytest.mark.xfail(scipy.show_config(mode='dicts')['Compilers']['fortran']['name'] ==
+ "intel-llvm",
+ reason="Failures due to floating point issues, not logic")
+@pytest.mark.parametrize('method', eb_data["methods"])
+@pytest.mark.parametrize('kwds', eb_data["kwds"])
+@pytest.mark.parametrize('bound_type', eb_data["bound_types"])
+@pytest.mark.parametrize('constraints', eb_data["constraints"])
+@pytest.mark.parametrize('callback', eb_data["callbacks"])
+def test_equal_bounds(method, kwds, bound_type, constraints, callback):
+ """
+ Tests that minimizers still work if (bounds.lb == bounds.ub).any()
+ gh12502 - Divide by zero in Jacobian numerical differentiation when
+ equality bounds constraints are used
+ """
+ # GH-15051; slightly more skips than necessary; hopefully fixed by GH-14882
+ if (platform.machine() == 'aarch64' and method == "TNC"
+ and kwds["jac"] is False and callback is not None):
+ pytest.skip('Tolerance violation on aarch')
+
+ lb, ub = eb_data["lb"], eb_data["ub"]
+ x0, i_eb = eb_data["x0"], eb_data["i_eb"]
+
+ test_constraints, reference_constraints = constraints
+ if test_constraints and not method == 'SLSQP':
+ pytest.skip('Only SLSQP supports nonlinear constraints')
+
+ if method in ['SLSQP', 'TNC'] and callable(callback):
+ sig = inspect.signature(callback)
+ if 'intermediate_result' in set(sig.parameters):
+ pytest.skip("SLSQP, TNC don't support intermediate_result")
+
+ # reference constraints always have analytical jacobian
+ # if test constraints are not the same, we'll need finite differences
+ fd_needed = (test_constraints != reference_constraints)
+
+ bounds = bound_type(lb, ub) # old- or new-style
+
+ kwds.update({"x0": x0, "method": method, "bounds": bounds,
+ "constraints": test_constraints, "callback": callback})
+ res = optimize.minimize(**kwds)
+
+ expected = optimize.minimize(optimize.rosen, x0, method=method,
+ jac=optimize.rosen_der, bounds=bounds,
+ constraints=reference_constraints)
+
+ # compare the output of a solution with FD vs that of an analytic grad
+ assert res.success
+ assert_allclose(res.fun, expected.fun, rtol=5.0e-6)
+ assert_allclose(res.x, expected.x, rtol=5e-4)
+
+ if fd_needed or kwds['jac'] is False:
+ expected.jac[i_eb] = np.nan
+ assert res.jac.shape[0] == 4
+ assert_allclose(res.jac[i_eb], expected.jac[i_eb], rtol=1e-6)
+
+ if not (kwds['jac'] or test_constraints or isinstance(bounds, Bounds)):
+ # compare the output to an equivalent FD minimization that doesn't
+ # need factorization
+ def fun(x):
+ new_x = np.array([np.nan, 2, np.nan, -1])
+ new_x[[0, 2]] = x
+ return optimize.rosen(new_x)
+
+ fd_res = optimize.minimize(fun,
+ x0[[0, 2]],
+ method=method,
+ bounds=bounds[::2])
+ assert_allclose(res.fun, fd_res.fun)
+ # TODO this test should really be equivalent to factorized version
+ # above, down to res.nfev. However, testing found that when TNC is
+ # called with or without a callback the output is different. The two
+ # should be the same! This indicates that the TNC callback may be
+ # mutating something when it shouldn't.
+ assert_allclose(res.x[[0, 2]], fd_res.x, rtol=2e-6)
+
+
+@pytest.mark.parametrize('method', eb_data["methods"])
+def test_all_bounds_equal(method):
+ # this only tests methods that have parameters factored out when lb==ub
+ # it does not test other methods that work with bounds
+ def f(x, p1=1):
+ return np.linalg.norm(x) + p1
+
+ bounds = [(1, 1), (2, 2)]
+ x0 = (1.0, 3.0)
+ res = optimize.minimize(f, x0, bounds=bounds, method=method)
+ assert res.success
+ assert_allclose(res.fun, f([1.0, 2.0]))
+ assert res.nfev == 1
+ assert res.message == 'All independent variables were fixed by bounds.'
+
+ args = (2,)
+ res = optimize.minimize(f, x0, bounds=bounds, method=method, args=args)
+ assert res.success
+ assert_allclose(res.fun, f([1.0, 2.0], 2))
+
+ if method.upper() == 'SLSQP':
+ def con(x):
+ return np.sum(x)
+ nlc = NonlinearConstraint(con, -np.inf, 0.0)
+ res = optimize.minimize(
+ f, x0, bounds=bounds, method=method, constraints=[nlc]
+ )
+ assert res.success is False
+ assert_allclose(res.fun, f([1.0, 2.0]))
+ assert res.nfev == 1
+ message = "All independent variables were fixed by bounds, but"
+ assert res.message.startswith(message)
+
+ nlc = NonlinearConstraint(con, -np.inf, 4)
+ res = optimize.minimize(
+ f, x0, bounds=bounds, method=method, constraints=[nlc]
+ )
+ assert res.success is True
+ assert_allclose(res.fun, f([1.0, 2.0]))
+ assert res.nfev == 1
+ message = "All independent variables were fixed by bounds at values"
+ assert res.message.startswith(message)
+
+
+def test_eb_constraints():
+ # make sure constraint functions aren't overwritten when equal bounds
+ # are employed, and a parameter is factored out. GH14859
+ def f(x):
+ return x[0]**3 + x[1]**2 + x[2]*x[3]
+
+ def cfun(x):
+ return x[0] + x[1] + x[2] + x[3] - 40
+
+ constraints = [{'type': 'ineq', 'fun': cfun}]
+
+ bounds = [(0, 20)] * 4
+ bounds[1] = (5, 5)
+ optimize.minimize(
+ f,
+ x0=[1, 2, 3, 4],
+ method='SLSQP',
+ bounds=bounds,
+ constraints=constraints,
+ )
+ assert constraints[0]['fun'] == cfun
+
+
+def test_show_options():
+ solver_methods = {
+ 'minimize': MINIMIZE_METHODS,
+ 'minimize_scalar': MINIMIZE_SCALAR_METHODS,
+ 'root': ROOT_METHODS,
+ 'root_scalar': ROOT_SCALAR_METHODS,
+ 'linprog': LINPROG_METHODS,
+ 'quadratic_assignment': QUADRATIC_ASSIGNMENT_METHODS,
+ }
+ for solver, methods in solver_methods.items():
+ for method in methods:
+ # testing that `show_options` works without error
+ show_options(solver, method)
+
+ unknown_solver_method = {
+ 'minimize': "ekki", # unknown method
+ 'maximize': "cg", # unknown solver
+ 'maximize_scalar': "ekki", # unknown solver and method
+ }
+ for solver, method in unknown_solver_method.items():
+ # testing that `show_options` raises ValueError
+ assert_raises(ValueError, show_options, solver, method)
+
+
+def test_bounds_with_list():
+ # gh13501. Bounds created with lists weren't working for Powell.
+ bounds = optimize.Bounds(lb=[5., 5.], ub=[10., 10.])
+ optimize.minimize(
+ optimize.rosen, x0=np.array([9, 9]), method='Powell', bounds=bounds
+ )
+
+
+@pytest.mark.parametrize('method', (
+ 'slsqp', 'cg', 'cobyqa', 'powell','nelder-mead', 'bfgs', 'l-bfgs-b',
+ 'trust-constr'))
+def test_minimize_maxiter_noninteger(method):
+ # Regression test for gh-23430
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ optimize.minimize(rosen, x0, method=method, options={'maxiter': 100.1})
+
+
+def test_x_overwritten_user_function():
+ # if the user overwrites the x-array in the user function it's likely
+ # that the minimizer stops working properly.
+ # gh13740
+ def fquad(x):
+ a = np.arange(np.size(x))
+ x -= a
+ x *= x
+ return np.sum(x)
+
+ def fquad_jac(x):
+ a = np.arange(np.size(x))
+ x *= 2
+ x -= 2 * a
+ return x
+
+ def fquad_hess(x):
+ return np.eye(np.size(x)) * 2.0
+
+ meth_jac = [
+ 'newton-cg', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov', 'trust-constr'
+ ]
+ meth_hess = [
+ 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov', 'trust-constr'
+ ]
+
+ x0 = np.ones(5) * 1.5
+
+ for meth in MINIMIZE_METHODS:
+ jac = None
+ hess = None
+ if meth in meth_jac:
+ jac = fquad_jac
+ if meth in meth_hess:
+ hess = fquad_hess
+ res = optimize.minimize(fquad, x0, method=meth, jac=jac, hess=hess)
+ assert_allclose(res.x, np.arange(np.size(x0)), atol=2e-4)
+
+
+class TestGlobalOptimization:
+
+ def test_optimize_result_attributes(self):
+ def func(x):
+ return x ** 2
+
+ # Note that `brute` solver does not return `OptimizeResult`
+ results = [optimize.basinhopping(func, x0=1),
+ optimize.differential_evolution(func, [(-4, 4)]),
+ optimize.shgo(func, [(-4, 4)]),
+ optimize.dual_annealing(func, [(-4, 4)]),
+ optimize.direct(func, [(-4, 4)]),
+ ]
+
+ for result in results:
+ assert isinstance(result, optimize.OptimizeResult)
+ assert hasattr(result, "x")
+ assert hasattr(result, "success")
+ assert hasattr(result, "message")
+ assert hasattr(result, "fun")
+ assert hasattr(result, "nfev")
+ assert hasattr(result, "nit")
+
+
+def test_approx_fprime():
+ # check that approx_fprime (serviced by approx_derivative) works for
+ # jac and hess
+ g = optimize.approx_fprime(himmelblau_x0, himmelblau)
+ assert_allclose(g, himmelblau_grad(himmelblau_x0), rtol=5e-6)
+
+ h = optimize.approx_fprime(himmelblau_x0, himmelblau_grad)
+ assert_allclose(h, himmelblau_hess(himmelblau_x0), rtol=5e-6)
+
+
+def test_gh12594():
+ # gh-12594 reported an error in `_linesearch_powell` and
+ # `_line_for_search` when `Bounds` was passed lists instead of arrays.
+ # Check that results are the same whether the inputs are lists or arrays.
+
+ def f(x):
+ return x[0]**2 + (x[1] - 1)**2
+
+ bounds = Bounds(lb=[-10, -10], ub=[10, 10])
+ res = optimize.minimize(f, x0=(0, 0), method='Powell', bounds=bounds)
+ bounds = Bounds(lb=np.array([-10, -10]), ub=np.array([10, 10]))
+ ref = optimize.minimize(f, x0=(0, 0), method='Powell', bounds=bounds)
+
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x)
+
+def test_gh12513_trustregion_exact_infinite_loop():
+ # gh-12513 reported that optimize.minimize might hang when
+ # method='trust-exact', using the option ``subproblem_maxiter``,
+ # this can be avoided.
+ H = np.array(
+ [[3.67335930e01, -2.52334820e02, 1.15477558e01, -1.19933725e-03,
+ -2.06408851e03, -2.05821411e00, -2.52334820e02, -6.52076924e02,
+ -2.71362566e-01, -1.98885126e00, 1.22085415e00, 2.30220713e00,
+ -9.71278532e-02, -5.11210123e-01, -1.00399562e00, 1.43319679e-01,
+ 6.03815471e00, -6.38719934e-02, 1.65623929e-01],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [1.15477558e01, -9.92814996e01, 3.63872363e03, -4.40007197e-01,
+ -9.55435081e02, -1.13985105e00, -9.92814996e01, -2.58307255e02,
+ -5.21335218e01, -3.77485107e02, -6.75338369e01, -1.89457169e02,
+ 5.67828623e00, 5.82402681e00, 1.72734354e01, -4.29114840e00,
+ -7.84885258e01, 3.17594634e00, 2.45242852e00],
+ [-1.19933725e-03, 1.06533600e-02, -4.40007197e-01, 5.73576663e-05,
+ 1.01563710e-01, 1.18838745e-04, 1.06533600e-02, 2.76535767e-02,
+ 6.25788669e-03, 4.50699620e-02, 8.64152333e-03, 2.27772377e-02,
+ -8.51026855e-04, 1.65316383e-04, 1.38977551e-03, 5.51629259e-04,
+ 1.38447755e-02, -5.17956723e-04, -1.29260347e-04],
+ [-2.06408851e03, 1.44442941e04, -9.55435081e02, 1.01563710e-01,
+ 1.23101825e05, 1.26467259e02, 1.44442941e04, 3.74590279e04,
+ 2.18498571e01, 1.60254460e02, -7.52977260e01, -1.17989623e02,
+ 6.58253160e00, 3.14949206e01, 4.98527190e01, -9.33338661e00,
+ -3.80465752e02, 4.33872213e00, -1.14768816e01],
+ [-2.05821411e00, 1.43811694e01, -1.13985105e00, 1.18838745e-04,
+ 1.26467259e02, 1.46226198e-01, 1.43811694e01, 3.74509252e01,
+ 2.76928748e-02, 2.03023837e-01, -8.84279903e-02, -1.29523344e-01,
+ 8.06424434e-03, 3.83330661e-02, 5.81579023e-02, -1.12874980e-02,
+ -4.48118297e-01, 5.15022284e-03, -1.41501894e-02],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [-6.52076924e02, 4.56694461e03, -2.58307255e02, 2.76535767e-02,
+ 3.74590279e04, 3.74509252e01, 4.56694461e03, 1.18278398e04,
+ 5.82242837e00, 4.26867612e01, -2.03167952e01, -3.22894255e01,
+ 1.75705078e00, 8.37153730e00, 1.32246076e01, -2.49238529e00,
+ -1.01316422e02, 1.16165466e00, -3.09390862e00],
+ [-2.71362566e-01, 2.22263363e00, -5.21335218e01, 6.25788669e-03,
+ 2.18498571e01, 2.76928748e-02, 2.22263363e00, 5.82242837e00,
+ 4.36278066e01, 3.14836583e02, -2.04747938e01, -3.05535101e01,
+ -1.24881456e-01, 1.15775394e01, 4.06907410e01, -1.39317748e00,
+ -3.90902798e01, -9.71716488e-02, 1.06851340e-01],
+ [-1.98885126e00, 1.62977318e01, -3.77485107e02, 4.50699620e-02,
+ 1.60254460e02, 2.03023837e-01, 1.62977318e01, 4.26867612e01,
+ 3.14836583e02, 2.27255216e03, -1.47029712e02, -2.19649109e02,
+ -8.83963155e-01, 8.28571708e01, 2.91399776e02, -9.97382920e00,
+ -2.81069124e02, -6.94946614e-01, 7.38151960e-01],
+ [1.22085415e00, -7.81539315e00, -6.75338369e01, 8.64152333e-03,
+ -7.52977260e01, -8.84279903e-02, -7.81539315e00, -2.03167952e01,
+ -2.04747938e01, -1.47029712e02, 7.83372613e01, 1.64416651e02,
+ -4.30243758e00, -2.59579610e01, -6.25644064e01, 6.69974667e00,
+ 2.31011701e02, -2.68540084e00, 5.44531151e00],
+ [2.30220713e00, -1.24938012e01, -1.89457169e02, 2.27772377e-02,
+ -1.17989623e02, -1.29523344e-01, -1.24938012e01, -3.22894255e01,
+ -3.05535101e01, -2.19649109e02, 1.64416651e02, 3.75893031e02,
+ -7.42084715e00, -4.56437599e01, -1.11071032e02, 1.18761368e01,
+ 4.78724142e02, -5.06804139e00, 8.81448081e00],
+ [-9.71278532e-02, 6.74029088e-01, 5.67828623e00, -8.51026855e-04,
+ 6.58253160e00, 8.06424434e-03, 6.74029088e-01, 1.75705078e00,
+ -1.24881456e-01, -8.83963155e-01, -4.30243758e00, -7.42084715e00,
+ 9.62009425e-01, 1.53836355e00, 2.23939458e00, -8.01872920e-01,
+ -1.92191084e01, 3.77713908e-01, -8.32946970e-01],
+ [-5.11210123e-01, 3.22802671e00, 5.82402681e00, 1.65316383e-04,
+ 3.14949206e01, 3.83330661e-02, 3.22802671e00, 8.37153730e00,
+ 1.15775394e01, 8.28571708e01, -2.59579610e01, -4.56437599e01,
+ 1.53836355e00, 2.63851056e01, 7.34859767e01, -4.39975402e00,
+ -1.12015747e02, 5.11542219e-01, -2.64962727e00],
+ [-1.00399562e00, 5.14978971e00, 1.72734354e01, 1.38977551e-03,
+ 4.98527190e01, 5.81579023e-02, 5.14978971e00, 1.32246076e01,
+ 4.06907410e01, 2.91399776e02, -6.25644064e01, -1.11071032e02,
+ 2.23939458e00, 7.34859767e01, 2.36535458e02, -1.09636675e01,
+ -2.72152068e02, 6.65888059e-01, -6.29295273e00],
+ [1.43319679e-01, -9.58561209e-01, -4.29114840e00, 5.51629259e-04,
+ -9.33338661e00, -1.12874980e-02, -9.58561209e-01, -2.49238529e00,
+ -1.39317748e00, -9.97382920e00, 6.69974667e00, 1.18761368e01,
+ -8.01872920e-01, -4.39975402e00, -1.09636675e01, 1.16820748e00,
+ 3.00817252e01, -4.51359819e-01, 9.82625204e-01],
+ [6.03815471e00, -3.92199895e01, -7.84885258e01, 1.38447755e-02,
+ -3.80465752e02, -4.48118297e-01, -3.92199895e01, -1.01316422e02,
+ -3.90902798e01, -2.81069124e02, 2.31011701e02, 4.78724142e02,
+ -1.92191084e01, -1.12015747e02, -2.72152068e02, 3.00817252e01,
+ 1.13232557e03, -1.33695932e01, 2.22934659e01],
+ [-6.38719934e-02, 4.47201278e-01, 3.17594634e00, -5.17956723e-04,
+ 4.33872213e00, 5.15022284e-03, 4.47201278e-01, 1.16165466e00,
+ -9.71716488e-02, -6.94946614e-01, -2.68540084e00, -5.06804139e00,
+ 3.77713908e-01, 5.11542219e-01, 6.65888059e-01, -4.51359819e-01,
+ -1.33695932e01, 4.27994168e-01, -5.09020820e-01],
+ [1.65623929e-01, -1.17866744e00, 2.45242852e00, -1.29260347e-04,
+ -1.14768816e01, -1.41501894e-02, -1.17866744e00, -3.09390862e00,
+ 1.06851340e-01, 7.38151960e-01, 5.44531151e00, 8.81448081e00,
+ -8.32946970e-01, -2.64962727e00, -6.29295273e00, 9.82625204e-01,
+ 2.22934659e01, -5.09020820e-01, 4.09964606e00]]
+ )
+ J = np.array([
+ -2.53298102e-07, 1.76392040e-06, 1.74776130e-06, -4.19479903e-10,
+ 1.44167498e-05, 1.41703911e-08, 1.76392030e-06, 4.96030153e-06,
+ -2.35771675e-07, -1.68844985e-06, 4.29218258e-07, 6.65445159e-07,
+ -3.87045830e-08, -3.17236594e-07, -1.21120169e-06, 4.59717313e-08,
+ 1.67123246e-06, 1.46624675e-08, 4.22723383e-08
+ ])
+
+ def fun(x):
+ return np.dot(np.dot(x, H), x) / 2 + np.dot(x, J)
+
+ def jac(x):
+ return np.dot(x, H) + J
+
+ def hess(x):
+ return H
+
+ x0 = np.zeros(19)
+
+ res = optimize.minimize(
+ fun,
+ x0,
+ jac=jac,
+ hess=hess,
+ method="trust-exact",
+ options={"gtol": 1e-6, "subproblem_maxiter": 10},
+ )
+ assert res.success
+ assert abs(fun(res.x)) < 1e-5
+
+
+@pytest.mark.parametrize('method', ['Newton-CG', 'trust-constr'])
+@pytest.mark.parametrize('sparse_type', [coo_matrix, csc_matrix, csr_matrix,
+ coo_array, csr_array, csc_array])
+def test_sparse_hessian(method, sparse_type):
+ # gh-8792 reported an error for minimization with `newton_cg` when `hess`
+ # returns a sparse array. Check that results are the same whether `hess`
+ # returns a dense or sparse array for optimization methods that accept
+ # sparse Hessian matrices.
+
+ def sparse_rosen_hess(x):
+ return sparse_type(rosen_hess(x))
+
+ x0 = [2., 2.]
+
+ res_sparse = optimize.minimize(rosen, x0, method=method,
+ jac=rosen_der, hess=sparse_rosen_hess)
+ res_dense = optimize.minimize(rosen, x0, method=method,
+ jac=rosen_der, hess=rosen_hess)
+
+ assert_allclose(res_dense.fun, res_sparse.fun)
+ assert_allclose(res_dense.x, res_sparse.x)
+ assert res_dense.nfev == res_sparse.nfev
+ assert res_dense.njev == res_sparse.njev
+ assert res_dense.nhev == res_sparse.nhev
+
+
+@pytest.mark.parametrize('workers', [None, 2])
+@pytest.mark.parametrize(
+ 'method',
+ ['l-bfgs-b',
+ 'bfgs',
+ 'slsqp',
+ 'trust-constr',
+ 'Newton-CG',
+ 'CG',
+ 'tnc',
+ 'trust-ncg',
+ 'trust-krylov'])
+class TestWorkers:
+
+ def setup_method(self):
+ self.x0 = np.array([1.0, 2.0, 3.0])
+
+ def test_smoke(self, workers, method):
+ # checks parallelised optimization output is same as serial
+ workers = workers or map
+
+ kwds = {'jac': None, 'hess': None}
+ if method in ['Newton-CG', 'trust-ncg', 'trust-krylov']:
+ # methods that require a callable jac
+ kwds['jac'] = rosen_der
+ kwds['hess'] = '2-point'
+
+ with MapWrapper(workers) as mf:
+ res = optimize.minimize(
+ rosen, self.x0, options={"workers":mf}, method=method, **kwds
+ )
+ res_default = optimize.minimize(
+ rosen, self.x0, method=method, **kwds
+ )
+ assert_equal(res.x, res_default.x)
+ assert_equal(res.nfev, res_default.nfev)
+
+ def test_equal_bounds(self, workers, method):
+ workers = workers or map
+ if method not in ['l-bfgs-b', 'slsqp', 'trust-constr', 'tnc']:
+ pytest.skip(f"{method} cannot use bounds")
+
+ bounds = Bounds([0, 2.0, 0.], [10., 2.0, 10.])
+ with MapWrapper(workers) as mf:
+ res = optimize.minimize(
+ rosen, self.x0, bounds=bounds, options={"workers": mf}, method=method
+ )
+ assert res.success
+ assert_allclose(res.x[1], 2.0)
+
+
+# Tests for PEP 649/749 style annotations in callback and objective functions
+if sys.version_info < (3, 14):
+ from typing import Any
+ _DUMMY_TYPE = Any
+else:
+ import typing
+ if typing.TYPE_CHECKING:
+ _DUMMY_TYPE = typing.Any
+
+def rosen_annotated(x: _DUMMY_TYPE) -> float:
+ return rosen(x) + 1
+
+def rosen_der_annotated(x: _DUMMY_TYPE) -> _DUMMY_TYPE:
+ return rosen_der(x)
+
+def rosen_hess_annotated(x: _DUMMY_TYPE) -> _DUMMY_TYPE:
+ return rosen_hess(x)
+
+def callable_annotated(intermediate_result: _DUMMY_TYPE) -> None:
+ pass
+
+@pytest.mark.skipif(sys.version_info < (3, 14),
+ reason="Requires PEP 649/749 from Python 3.14+.")
+class TestAnnotations:
+
+ def setup_method(self):
+ self.x0 = np.array([1.0, 1.01])
+ self.brute_params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
+
+ @pytest.mark.parametrize("method", [
+ 'Nelder-Mead',
+ 'Powell',
+ 'CG',
+ 'bfgs',
+ 'Newton-CG',
+ 'l-bfgs-b',
+ 'tnc',
+ 'COBYLA',
+ # 'COBYQA', # External module. Will trigger NameError, skip for now
+ 'slsqp',
+ 'trust-constr',
+ 'dogleg',
+ 'trust-ncg',
+ 'trust-exact',
+ 'trust-krylov'
+ ])
+ def test_callable_annotations(self, method):
+ kwds = {'jac': None, 'hess': None, 'callback': callable_annotated}
+ if method in ['CG', 'BFGS', 'Newton-CG', "L-BFGS-B", 'TNC', 'SLSQP', 'dogleg',
+ 'trust-ncg', 'trust-krylov', 'trust-exact', 'trust-constr']:
+ # methods that require a callable jac
+ kwds['jac'] = rosen_der_annotated
+ if method in ['Newton-CG', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov', 'trust-constr']:
+ kwds['hess'] = rosen_hess_annotated
+ optimize.minimize(rosen_annotated, self.x0, method=method, **kwds)
+
+ def test_differential_evolution_annotations(self):
+ bounds = [(-5, 5), (-5, 5)]
+ res = optimize.differential_evolution(rosen_annotated, bounds, seed=1,
+ callback=callable_annotated)
+ assert res.success, f"Unexpected error: {res.message}"
+
+ def test_curve_fit_annotations(self):
+
+ def model_func(x: _DUMMY_TYPE, a: float, b, c) -> _DUMMY_TYPE:
+ return a * np.exp(-b * x) + c
+
+ def model_jac(x: _DUMMY_TYPE, a: float, b, c) -> _DUMMY_TYPE:
+ return np.array([
+ np.exp(-b * x),
+ -a * x * np.exp(-b * x),
+ np.ones_like(x)
+ ]).T
+
+ xdata = np.linspace(0, 4, 10)
+ ydata = model_func(xdata, 2.5, 1.3, 0.5)
+
+ _,_,_,_,res = optimize.curve_fit(model_func, xdata, ydata, jac=model_jac,
+ full_output=True)
+ assert (res in [1, 2, 3, 4]), f"Unexpected error: {res.message}"
+
+ def test_brute_annotations(self):
+ def f1(z: _DUMMY_TYPE, *params: float) -> float:
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
+
+ def annotated_fmin(callable: _DUMMY_TYPE, x0: _DUMMY_TYPE,
+ *args, **kwargs) -> _DUMMY_TYPE:
+ return optimize.fmin(callable, x0, *args, **kwargs)
+
+ rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
+ optimize.brute(f1, rranges, args=self.brute_params, finish=annotated_fmin)
+
+ def test_basinhopping_annotations(self):
+ # NOTE: basinhopping callback does not match
+ # callback(intermediate_result: OptimizeResult)
+ # signature. Consider adding when updated.
+ def acceptable_test(f_new: float, x_new: _DUMMY_TYPE,
+ f_old: float,x_old: _DUMMY_TYPE) -> bool:
+ return True
+
+ res = optimize.basinhopping(rosen_annotated, self.x0, niter=2, seed=1,
+ accept_test=acceptable_test)
+
+ assert res.success, f"Unexpected error: {res.message}"
+
+
+def test_multiprocessing_too_many_open_files_23080():
+ # https://github.com/scipy/scipy/issues/23080
+ x0 = np.array([0.9, 0.9])
+ # check that ScalarHessWrapper doesn't keep pool object alive
+ with assert_deallocated(multiprocessing.Pool, 2) as pool_obj:
+ with pool_obj as p:
+ _minimize_bfgs(rosen, x0, workers=p.map)
+ del p
+ del pool_obj
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_quadratic_assignment.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_quadratic_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..840724e1818efec6eccecd4eb13458a4d7fb9a50
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_quadratic_assignment.py
@@ -0,0 +1,431 @@
+import pytest
+import numpy as np
+from numpy.random import default_rng
+from scipy.optimize import quadratic_assignment, OptimizeWarning
+from scipy.optimize._qap import _calc_score as _score
+from numpy.testing import assert_equal, assert_
+
+
+################
+# Common Tests #
+################
+
+def chr12c():
+ A = [
+ [0, 90, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [90, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0],
+ [10, 0, 0, 0, 43, 0, 0, 0, 0, 0, 0, 0],
+ [0, 23, 0, 0, 0, 88, 0, 0, 0, 0, 0, 0],
+ [0, 0, 43, 0, 0, 0, 26, 0, 0, 0, 0, 0],
+ [0, 0, 0, 88, 0, 0, 0, 16, 0, 0, 0, 0],
+ [0, 0, 0, 0, 26, 0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 16, 0, 0, 0, 96, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 29, 0],
+ [0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 37],
+ [0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0],
+ ]
+ B = [
+ [0, 36, 54, 26, 59, 72, 9, 34, 79, 17, 46, 95],
+ [36, 0, 73, 35, 90, 58, 30, 78, 35, 44, 79, 36],
+ [54, 73, 0, 21, 10, 97, 58, 66, 69, 61, 54, 63],
+ [26, 35, 21, 0, 93, 12, 46, 40, 37, 48, 68, 85],
+ [59, 90, 10, 93, 0, 64, 5, 29, 76, 16, 5, 76],
+ [72, 58, 97, 12, 64, 0, 96, 55, 38, 54, 0, 34],
+ [9, 30, 58, 46, 5, 96, 0, 83, 35, 11, 56, 37],
+ [34, 78, 66, 40, 29, 55, 83, 0, 44, 12, 15, 80],
+ [79, 35, 69, 37, 76, 38, 35, 44, 0, 64, 39, 33],
+ [17, 44, 61, 48, 16, 54, 11, 12, 64, 0, 70, 86],
+ [46, 79, 54, 68, 5, 0, 56, 15, 39, 70, 0, 18],
+ [95, 36, 63, 85, 76, 34, 37, 80, 33, 86, 18, 0],
+ ]
+ A, B = np.array(A), np.array(B)
+ n = A.shape[0]
+
+ opt_perm = np.array([7, 5, 1, 3, 10, 4, 8, 6, 9, 11, 2, 12]) - [1] * n
+
+ return A, B, opt_perm
+
+
+class QAPCommonTests:
+ """
+ Base class for `quadratic_assignment` tests.
+ """
+ # Test global optima of problem from Umeyama IVB
+ # https://pcl.sitehost.iu.edu/rgoldsto/papers/weighted%20graph%20match2.pdf
+ # Graph matching maximum is in the paper
+ # QAP minimum determined by brute force
+ def test_accuracy_1(self):
+ # besides testing accuracy, check that A and B can be lists
+ rng = np.random.default_rng(4358764578823597324)
+
+ A = [[0, 3, 4, 2],
+ [0, 0, 1, 2],
+ [1, 0, 0, 1],
+ [0, 0, 1, 0]]
+
+ B = [[0, 4, 2, 4],
+ [0, 0, 1, 0],
+ [0, 2, 0, 2],
+ [0, 1, 2, 0]]
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": False})
+
+ assert_equal(res.fun, 10)
+ assert_equal(res.col_ind, np.array([1, 2, 3, 0]))
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": True})
+
+ if self.method == 'faq':
+ # Global optimum is 40, but FAQ gets 37
+ assert_equal(res.fun, 37)
+ assert_equal(res.col_ind, np.array([0, 2, 3, 1]))
+ else:
+ assert_equal(res.fun, 40)
+ assert_equal(res.col_ind, np.array([0, 3, 1, 2]))
+
+ quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": True})
+
+ # Test global optima of problem from Umeyama IIIB
+ # https://pcl.sitehost.iu.edu/rgoldsto/papers/weighted%20graph%20match2.pdf
+ # Graph matching maximum is in the paper
+ # QAP minimum determined by brute force
+ def test_accuracy_2(self):
+ rng = np.random.default_rng(4358764578823597324)
+
+ A = np.array([[0, 5, 8, 6],
+ [5, 0, 5, 1],
+ [8, 5, 0, 2],
+ [6, 1, 2, 0]])
+
+ B = np.array([[0, 1, 8, 4],
+ [1, 0, 5, 2],
+ [8, 5, 0, 5],
+ [4, 2, 5, 0]])
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": False})
+
+ if self.method == 'faq':
+ # Global optimum is 176, but FAQ gets 178
+ assert_equal(res.fun, 178)
+ assert_equal(res.col_ind, np.array([1, 0, 3, 2]))
+ else:
+ assert_equal(res.fun, 176)
+ assert_equal(res.col_ind, np.array([1, 2, 3, 0]))
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": True})
+
+ assert_equal(res.fun, 286)
+ assert_equal(res.col_ind, np.array([2, 3, 0, 1]))
+
+ def test_accuracy_3(self):
+ rng = np.random.default_rng(4358764578823597324)
+ A, B, opt_perm = chr12c()
+
+ # basic minimization
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng})
+ assert_(11156 <= res.fun < 21000)
+ assert_equal(res.fun, _score(A, B, res.col_ind))
+
+ # basic maximization
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, 'maximize': True})
+ assert_(74000 <= res.fun < 85000)
+ assert_equal(res.fun, _score(A, B, res.col_ind))
+
+ # check ofv with strictly partial match
+ seed_cost = np.array([4, 8, 10])
+ seed = np.asarray([seed_cost, opt_perm[seed_cost]]).T
+ res = quadratic_assignment(A, B, method=self.method,
+ options={'partial_match': seed, "rng": rng})
+ assert_(11156 <= res.fun < 21000)
+ assert_equal(res.col_ind[seed_cost], opt_perm[seed_cost])
+
+ # check performance when partial match is the global optimum
+ seed = np.asarray([np.arange(len(A)), opt_perm]).T
+ res = quadratic_assignment(A, B, method=self.method,
+ options={'partial_match': seed, "rng": rng})
+ assert_equal(res.col_ind, seed[:, 1].T)
+ assert_equal(res.fun, 11156)
+ assert_equal(res.nit, 0)
+
+ # check performance with zero sized matrix inputs
+ empty = np.empty((0, 0))
+ res = quadratic_assignment(empty, empty, method=self.method,
+ options={"rng": rng})
+ assert_equal(res.nit, 0)
+ assert_equal(res.fun, 0)
+
+ def test_unknown_options(self):
+ A, B, opt_perm = chr12c()
+
+ with pytest.warns(OptimizeWarning):
+ quadratic_assignment(A, B, method=self.method,
+ options={"ekki-ekki": True})
+
+
+class TestFAQ(QAPCommonTests):
+ method = "faq"
+
+ def test_options(self):
+ # cost and distance matrices of QAPLIB instance chr12c
+ rng = np.random.default_rng(4358764578823597324)
+
+ A, B, opt_perm = chr12c()
+ n = len(A)
+
+ # check that max_iter is obeying with low input value
+ res = quadratic_assignment(A, B, options={'maxiter': 5})
+ assert_equal(res.nit, 5)
+
+ # test with shuffle
+ res = quadratic_assignment(A, B, options={'shuffle_input': True})
+ assert_(11156 <= res.fun < 21000)
+
+ # test with randomized init
+ res = quadratic_assignment(A, B, options={'rng': rng, 'P0': "randomized"})
+ assert_(11156 <= res.fun < 21000)
+
+ # check with specified P0
+ K = np.ones((n, n)) / float(n)
+ K = _doubly_stochastic(K)
+ res = quadratic_assignment(A, B, options={'P0': K})
+ assert_(11156 <= res.fun < 21000)
+
+ def test_specific_input_validation(self):
+
+ A = np.identity(2)
+ B = A
+
+ # method is implicitly faq
+
+ # ValueError Checks: making sure single value parameters are of
+ # correct value
+ with pytest.raises(ValueError, match="Invalid 'P0' parameter"):
+ quadratic_assignment(A, B, options={'P0': "random"})
+ with pytest.raises(
+ ValueError, match="'maxiter' must be a positive integer"):
+ quadratic_assignment(A, B, options={'maxiter': -1})
+ with pytest.raises(ValueError, match="'tol' must be a positive float"):
+ quadratic_assignment(A, B, options={'tol': -1})
+
+ # TypeError Checks: making sure single value parameters are of
+ # correct type
+ with pytest.raises(TypeError):
+ quadratic_assignment(A, B, options={'maxiter': 1.5})
+
+ # test P0 matrix input
+ with pytest.raises(
+ ValueError,
+ match="`P0` matrix must have shape m' x m', where m'=n-m"):
+ quadratic_assignment(
+ np.identity(4), np.identity(4),
+ options={'P0': np.ones((3, 3))}
+ )
+
+ K = [[0.4, 0.2, 0.3],
+ [0.3, 0.6, 0.2],
+ [0.2, 0.2, 0.7]]
+ # matrix that isn't quite doubly stochastic
+ with pytest.raises(
+ ValueError, match="`P0` matrix must be doubly stochastic"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), options={'P0': K}
+ )
+
+
+class Test2opt(QAPCommonTests):
+ method = "2opt"
+
+ def test_deterministic(self):
+ n = 20
+ rng = default_rng(51982908)
+ A = rng.random(size=(n, n))
+ B = rng.random(size=(n, n))
+ res1 = quadratic_assignment(A, B, method=self.method, options={'rng': rng})
+
+ rng = default_rng(51982908)
+ A = rng.random(size=(n, n))
+ B = rng.random(size=(n, n))
+ res2 = quadratic_assignment(A, B, method=self.method, options={'rng': rng})
+
+ assert_equal(res1.nit, res2.nit)
+
+ def test_partial_guess(self):
+ n = 5
+ rng = np.random.default_rng(4358764578823597324)
+
+ A = rng.random(size=(n, n))
+ B = rng.random(size=(n, n))
+
+ res1 = quadratic_assignment(A, B, method=self.method,
+ options={'rng': rng})
+ guess = np.array([np.arange(5), res1.col_ind]).T
+ res2 = quadratic_assignment(A, B, method=self.method,
+ options={'rng': rng, 'partial_guess': guess})
+ fix = [2, 4]
+ match = np.array([np.arange(5)[fix], res1.col_ind[fix]]).T
+ res3 = quadratic_assignment(A, B, method=self.method,
+ options={'rng': rng, 'partial_guess': guess,
+ 'partial_match': match})
+ assert_(res1.nit != n*(n+1)/2)
+ assert_equal(res2.nit, n*(n+1)/2) # tests each swap exactly once
+ assert_equal(res3.nit, (n-2)*(n-1)/2) # tests free swaps exactly once
+
+ def test_specific_input_validation(self):
+ # can't have more seed nodes than cost/dist nodes
+ _rm = _range_matrix
+ with pytest.raises(
+ ValueError,
+ match="`partial_guess` can have only as many entries as"):
+ quadratic_assignment(np.identity(3), np.identity(3),
+ method=self.method,
+ options={'partial_guess': _rm(5, 2)})
+ # test for only two seed columns
+ with pytest.raises(
+ ValueError, match="`partial_guess` must have two columns"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': _range_matrix(2, 3)}
+ )
+ # test that seed has no more than two dimensions
+ with pytest.raises(
+ ValueError, match="`partial_guess` must have exactly two"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': np.random.rand(3, 2, 2)}
+ )
+ # seeds cannot be negative valued
+ with pytest.raises(
+ ValueError, match="`partial_guess` must contain only pos"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': -1 * _range_matrix(2, 2)}
+ )
+ # seeds can't have values greater than number of nodes
+ with pytest.raises(
+ ValueError,
+ match="`partial_guess` entries must be less than number"):
+ quadratic_assignment(
+ np.identity(5), np.identity(5), method=self.method,
+ options={'partial_guess': 2 * _range_matrix(4, 2)}
+ )
+ # columns of seed matrix must be unique
+ with pytest.raises(
+ ValueError,
+ match="`partial_guess` column entries must be unique"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': np.ones((2, 2))}
+ )
+
+
+class TestQAPOnce:
+
+ # these don't need to be repeated for each method
+ def test_common_input_validation(self):
+ rng = default_rng(12349038)
+ # test that non square matrices return error
+ with pytest.raises(ValueError, match="`A` must be square"):
+ quadratic_assignment(
+ rng.random((3, 4)),
+ rng.random((3, 3)),
+ )
+ with pytest.raises(ValueError, match="`B` must be square"):
+ quadratic_assignment(
+ rng.random((3, 3)),
+ rng.random((3, 4)),
+ )
+ # test that cost and dist matrices have no more than two dimensions
+ with pytest.raises(
+ ValueError, match="`A` and `B` must have exactly two"):
+ quadratic_assignment(
+ rng.random((3, 3, 3)),
+ rng.random((3, 3, 3)),
+ )
+ # test that cost and dist matrices of different sizes return error
+ with pytest.raises(
+ ValueError,
+ match="`A` and `B` matrices must be of equal size"):
+ quadratic_assignment(
+ rng.random((3, 3)),
+ rng.random((4, 4)),
+ )
+ # can't have more seed nodes than cost/dist nodes
+ _rm = _range_matrix
+ with pytest.raises(
+ ValueError,
+ match="`partial_match` can have only as many seeds as"):
+ quadratic_assignment(np.identity(3), np.identity(3),
+ options={'partial_match': _rm(5, 2)})
+ # test for only two seed columns
+ with pytest.raises(
+ ValueError, match="`partial_match` must have two columns"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': _range_matrix(2, 3)}
+ )
+ # test that seed has no more than two dimensions
+ with pytest.raises(
+ ValueError, match="`partial_match` must have exactly two"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': np.random.rand(3, 2, 2)}
+ )
+ # seeds cannot be negative valued
+ with pytest.raises(
+ ValueError, match="`partial_match` must contain only pos"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': -1 * _range_matrix(2, 2)}
+ )
+ # seeds can't have values greater than number of nodes
+ with pytest.raises(
+ ValueError,
+ match="`partial_match` entries must be less than number"):
+ quadratic_assignment(
+ np.identity(5), np.identity(5),
+ options={'partial_match': 2 * _range_matrix(4, 2)}
+ )
+ # columns of seed matrix must be unique
+ with pytest.raises(
+ ValueError,
+ match="`partial_match` column entries must be unique"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': np.ones((2, 2))}
+ )
+
+
+def _range_matrix(a, b):
+ mat = np.zeros((a, b))
+ for i in range(b):
+ mat[:, i] = np.arange(a)
+ return mat
+
+
+def _doubly_stochastic(P, tol=1e-3):
+ # cleaner implementation of btaba/sinkhorn_knopp
+
+ max_iter = 1000
+ c = 1 / P.sum(axis=0)
+ r = 1 / (P @ c)
+ P_eps = P
+
+ for it in range(max_iter):
+ if ((np.abs(P_eps.sum(axis=1) - 1) < tol).all() and
+ (np.abs(P_eps.sum(axis=0) - 1) < tol).all()):
+ # All column/row sums ~= 1 within threshold
+ break
+
+ c = 1 / (r @ P)
+ r = 1 / (P @ c)
+ P_eps = r[:, None] * P * c
+
+ return P_eps
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_regression.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..44916ba96293db19756b8222422e76945aa48ebb
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_regression.py
@@ -0,0 +1,40 @@
+"""Regression tests for optimize.
+
+"""
+import numpy as np
+from numpy.testing import assert_almost_equal
+from pytest import raises as assert_raises
+
+import scipy.optimize
+
+
+class TestRegression:
+
+ def test_newton_x0_is_0(self):
+ # Regression test for gh-1601
+ tgt = 1
+ res = scipy.optimize.newton(lambda x: x - 1, 0)
+ assert_almost_equal(res, tgt)
+
+ def test_newton_integers(self):
+ # Regression test for gh-1741
+ root = scipy.optimize.newton(lambda x: x**2 - 1, x0=2,
+ fprime=lambda x: 2*x)
+ assert_almost_equal(root, 1.0)
+
+ def test_lmdif_errmsg(self):
+ # This shouldn't cause a crash on Python 3
+ class SomeError(Exception):
+ pass
+ counter = [0]
+
+ def func(x):
+ counter[0] += 1
+ if counter[0] < 3:
+ return x**2 - np.array([9, 10, 11])
+ else:
+ raise SomeError()
+ assert_raises(SomeError,
+ scipy.optimize.leastsq,
+ func, [1, 2, 3])
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_slsqp.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..43cb377dab41b734f59a5f600794beefd6e9c00b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_slsqp.py
@@ -0,0 +1,679 @@
+"""
+Unit test for SLSQP optimization.
+"""
+from numpy.testing import (assert_, assert_array_almost_equal,
+ assert_allclose, assert_equal)
+from pytest import raises as assert_raises
+import pytest
+import numpy as np
+import scipy
+
+from scipy.optimize import (fmin_slsqp, minimize, Bounds, NonlinearConstraint,
+ OptimizeResult)
+
+
+class MyCallBack:
+ """pass a custom callback function
+
+ This makes sure it's being used.
+ """
+ def __init__(self):
+ self.been_called = False
+ self.ncalls = 0
+
+ def __call__(self, x):
+ assert not isinstance(x, OptimizeResult)
+ self.been_called = True
+ self.ncalls += 1
+
+ def callback2(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ self.been_called = True
+ self.ncalls += 1
+
+ def callback3(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ raise StopIteration
+
+
+class TestSLSQP:
+ """
+ Test SLSQP algorithm using Example 14.4 from Numerical Methods for
+ Engineers by Steven Chapra and Raymond Canale.
+ This example maximizes the function f(x) = 2*x*y + 2*x - x**2 - 2*y**2,
+ which has a maximum at x=2, y=1.
+ """
+ def setup_method(self):
+ self.opts = {'disp': False}
+
+ def fun(self, d, sign=1.0):
+ """
+ Arguments:
+ d - A list of two elements, where d[0] represents x and d[1] represents y
+ in the following equation.
+ sign - A multiplier for f. Since we want to optimize it, and the SciPy
+ optimizers can only minimize functions, we need to multiply it by
+ -1 to achieve the desired solution
+ Returns:
+ 2*x*y + 2*x - x**2 - 2*y**2
+
+ """
+ x = d[0]
+ y = d[1]
+ return sign*(2*x*y + 2*x - x**2 - 2*y**2)
+
+ def jac(self, d, sign=1.0):
+ """
+ This is the derivative of fun, returning a NumPy array
+ representing df/dx and df/dy.
+
+ """
+ x = d[0]
+ y = d[1]
+ dfdx = sign*(-2*x + 2*y + 2)
+ dfdy = sign*(2*x - 4*y)
+ return np.array([dfdx, dfdy], float)
+
+ def fun_and_jac(self, d, sign=1.0):
+ return self.fun(d, sign), self.jac(d, sign)
+
+ def f_eqcon(self, x, sign=1.0):
+ """ Equality constraint """
+ return np.array([x[0] - x[1]])
+
+ def fprime_eqcon(self, x, sign=1.0):
+ """ Equality constraint, derivative """
+ return np.array([[1, -1]])
+
+ def f_eqcon_scalar(self, x, sign=1.0):
+ """ Scalar equality constraint """
+ return self.f_eqcon(x, sign)[0]
+
+ def fprime_eqcon_scalar(self, x, sign=1.0):
+ """ Scalar equality constraint, derivative """
+ return self.fprime_eqcon(x, sign)[0].tolist()
+
+ def f_ieqcon(self, x, sign=1.0):
+ """ Inequality constraint """
+ return np.array([x[0] - x[1] - 1.0])
+
+ def fprime_ieqcon(self, x, sign=1.0):
+ """ Inequality constraint, derivative """
+ return np.array([[1, -1]])
+
+ def f_ieqcon2(self, x):
+ """ Vector inequality constraint """
+ return np.asarray(x)
+
+ def fprime_ieqcon2(self, x):
+ """ Vector inequality constraint, derivative """
+ return np.identity(x.shape[0])
+
+ # minimize
+ def test_minimize_unbounded_approximated(self):
+ # Minimize, method='SLSQP': unbounded, approximated jacobian.
+ jacs = [None, False, '2-point', '3-point']
+ for jac in jacs:
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=jac, method='SLSQP',
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_unbounded_given(self):
+ # Minimize, method='SLSQP': unbounded, given Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=self.jac, method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_bounded_approximated(self):
+ # Minimize, method='SLSQP': bounded, approximated jacobian.
+ jacs = [None, False, '2-point', '3-point']
+ for jac in jacs:
+ with np.errstate(invalid='ignore'):
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=jac,
+ bounds=((2.5, None), (None, 0.5)),
+ method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2.5, 0.5])
+ assert_(2.5 <= res.x[0])
+ assert_(res.x[1] <= 0.5)
+
+ def test_minimize_unbounded_combined(self):
+ # Minimize, method='SLSQP': unbounded, combined function and Jacobian.
+ res = minimize(self.fun_and_jac, [-1.0, 1.0], args=(-1.0, ),
+ jac=True, method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_equality_approximated(self):
+ # Minimize with method='SLSQP': equality constraint, approx. jacobian.
+ jacs = [None, False, '2-point', '3-point']
+ for jac in jacs:
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=jac,
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon,
+ 'args': (-1.0, )},
+ method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_equality_given(self):
+ # Minimize with method='SLSQP': equality constraint, given Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], jac=self.jac,
+ method='SLSQP', args=(-1.0,),
+ constraints={'type': 'eq', 'fun':self.f_eqcon,
+ 'args': (-1.0, )},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_equality_given2(self):
+ # Minimize with method='SLSQP': equality constraint, given Jacobian
+ # for fun and const.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0,),
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon,
+ 'args': (-1.0, ),
+ 'jac': self.fprime_eqcon},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_equality_given_cons_scalar(self):
+ # Minimize with method='SLSQP': scalar equality constraint, given
+ # Jacobian for fun and const.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0,),
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon_scalar,
+ 'args': (-1.0, ),
+ 'jac': self.fprime_eqcon_scalar},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_inequality_given(self):
+ # Minimize with method='SLSQP': inequality constraint, given Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0, ),
+ constraints={'type': 'ineq',
+ 'fun': self.f_ieqcon,
+ 'args': (-1.0, )},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1], atol=1e-3)
+
+ def test_minimize_inequality_given_vector_constraints(self):
+ # Minimize with method='SLSQP': vector inequality constraint, given
+ # Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], jac=self.jac,
+ method='SLSQP', args=(-1.0,),
+ constraints={'type': 'ineq',
+ 'fun': self.f_ieqcon2,
+ 'jac': self.fprime_ieqcon2},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_bounded_constraint(self):
+ # when the constraint makes the solver go up against a parameter
+ # bound make sure that the numerical differentiation of the
+ # jacobian doesn't try to exceed that bound using a finite difference.
+ # gh11403
+ def c(x):
+ assert 0 <= x[0] <= 1 and 0 <= x[1] <= 1, x
+ return x[0] ** 0.5 + x[1]
+
+ def f(x):
+ assert 0 <= x[0] <= 1 and 0 <= x[1] <= 1, x
+ return -x[0] ** 2 + x[1] ** 2
+
+ cns = [NonlinearConstraint(c, 0, 1.5)]
+ x0 = np.asarray([0.9, 0.5])
+ bnd = Bounds([0., 0.], [1.0, 1.0])
+ minimize(f, x0, method='SLSQP', bounds=bnd, constraints=cns)
+
+ def test_minimize_bound_equality_given2(self):
+ # Minimize with method='SLSQP': bounds, eq. const., given jac. for
+ # fun. and const.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0, ),
+ bounds=[(-0.8, 1.), (-1, 0.8)],
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon,
+ 'args': (-1.0, ),
+ 'jac': self.fprime_eqcon},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [0.8, 0.8], atol=1e-3)
+ assert_(-0.8 <= res.x[0] <= 1)
+ assert_(-1 <= res.x[1] <= 0.8)
+
+ # fmin_slsqp
+ def test_unbounded_approximated(self):
+ # SLSQP: unbounded, approximated Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [2, 1])
+
+ def test_unbounded_given(self):
+ # SLSQP: unbounded, given Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ fprime = self.jac, iprint = 0,
+ full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [2, 1])
+
+ def test_equality_approximated(self):
+ # SLSQP: equality constraint, approximated Jacobian.
+ res = fmin_slsqp(self.fun,[-1.0,1.0], args=(-1.0,),
+ eqcons = [self.f_eqcon],
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [1, 1])
+
+ def test_equality_given(self):
+ # SLSQP: equality constraint, given Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0,),
+ eqcons = [self.f_eqcon], iprint = 0,
+ full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [1, 1])
+
+ def test_equality_given2(self):
+ # SLSQP: equality constraint, given Jacobian for fun and const.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0,),
+ f_eqcons = self.f_eqcon,
+ fprime_eqcons = self.fprime_eqcon,
+ iprint = 0,
+ full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [1, 1])
+
+ def test_inequality_given(self):
+ # SLSQP: inequality constraint, given Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0, ),
+ ieqcons = [self.f_ieqcon],
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [2, 1], decimal=3)
+
+ def test_bound_equality_given2(self):
+ # SLSQP: bounds, eq. const., given jac. for fun. and const.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0, ),
+ bounds = [(-0.8, 1.), (-1, 0.8)],
+ f_eqcons = self.f_eqcon,
+ fprime_eqcons = self.fprime_eqcon,
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [0.8, 0.8], decimal=3)
+ assert_(-0.8 <= x[0] <= 1)
+ assert_(-1 <= x[1] <= 0.8)
+
+ def test_scalar_constraints(self):
+ # Regression test for gh-2182
+ x = fmin_slsqp(lambda z: z**2, [3.],
+ ieqcons=[lambda z: z[0] - 1],
+ iprint=0)
+ assert_array_almost_equal(x, [1.])
+
+ x = fmin_slsqp(lambda z: z**2, [3.],
+ f_ieqcons=lambda z: [z[0] - 1],
+ iprint=0)
+ assert_array_almost_equal(x, [1.])
+
+ def test_integer_bounds(self):
+ # This should not raise an exception
+ fmin_slsqp(lambda z: z**2 - 1, [0], bounds=[[0, 1]], iprint=0)
+
+ def test_array_bounds(self):
+ # NumPy used to treat n-dimensional 1-element arrays as scalars
+ # in some cases. The handling of `bounds` by `fmin_slsqp` still
+ # supports this behavior.
+ bounds = [(-np.inf, np.inf), (np.array([2]), np.array([3]))]
+ x = fmin_slsqp(lambda z: np.sum(z**2 - 1), [2.5, 2.5], bounds=bounds,
+ iprint=0)
+ assert_array_almost_equal(x, [0, 2])
+
+ def test_obj_must_return_scalar(self):
+ # Regression test for Github Issue #5433
+ # If objective function does not return a scalar, raises ValueError
+ with assert_raises(ValueError):
+ fmin_slsqp(lambda x: [0, 1], [1, 2, 3])
+
+ def test_obj_returns_scalar_in_list(self):
+ # Test for Github Issue #5433 and PR #6691
+ # Objective function should be able to return length-1 Python list
+ # containing the scalar
+ fmin_slsqp(lambda x: [0], [1, 2, 3], iprint=0)
+
+ def test_callback(self):
+ # Minimize, method='SLSQP': unbounded, approximated jacobian. Check for callback
+ callback = MyCallBack()
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ method='SLSQP', callback=callback, options=self.opts)
+ assert res.success
+ assert res.message
+ assert callback.been_called
+ assert_equal(callback.ncalls, res['nit'])
+
+ res = minimize(
+ self.fun,
+ [-1.0, 1.0],
+ args=(-1.0, ),
+ method='SLSQP',
+ callback=callback.callback2,
+ options=self.opts
+ )
+ assert res.success
+ assert callback.been_called
+
+ res = minimize(
+ self.fun,
+ [-1.0, 1.0],
+ args=(-1.0, ),
+ method='SLSQP',
+ callback=callback.callback3,
+ options=self.opts
+ )
+ assert not res.success
+ assert res.message.startswith("`callback` raised `StopIteration`")
+
+ def test_inconsistent_linearization(self):
+ # SLSQP must be able to solve this problem, even if the
+ # linearized problem at the starting point is infeasible.
+
+ # Linearized constraints are
+ #
+ # 2*x0[0]*x[0] >= 1
+ #
+ # At x0 = [0, 1], the second constraint is clearly infeasible.
+ # This triggers a call with n2==1 in the LSQ subroutine.
+ x = [0, 1]
+ def f1(x):
+ return x[0] + x[1] - 2
+ def f2(x):
+ return x[0] ** 2 - 1
+ sol = minimize(
+ lambda x: x[0]**2 + x[1]**2,
+ x,
+ constraints=({'type':'eq','fun': f1},
+ {'type':'ineq','fun': f2}),
+ bounds=((0,None), (0,None)),
+ method='SLSQP')
+ x = sol.x
+
+ assert_allclose(f1(x), 0, atol=1e-8)
+ assert_(f2(x) >= -1e-8)
+ assert_(sol.success, sol)
+
+ def test_regression_5743(self):
+ # SLSQP must not indicate success for this problem,
+ # which is infeasible.
+ x = [1, 2]
+ sol = minimize(
+ lambda x: x[0]**2 + x[1]**2,
+ x,
+ constraints=({'type':'eq','fun': lambda x: x[0]+x[1]-1},
+ {'type':'ineq','fun': lambda x: x[0]-2}),
+ bounds=((0,None), (0,None)),
+ method='SLSQP')
+ assert_(not sol.success, sol)
+
+ def test_gh_6676(self):
+ def func(x):
+ return (x[0] - 1)**2 + 2*(x[1] - 1)**2 + 0.5*(x[2] - 1)**2
+
+ sol = minimize(func, [0, 0, 0], method='SLSQP')
+ assert_(sol.jac.shape == (3,))
+
+ def test_invalid_bounds(self):
+ # Raise correct error when lower bound is greater than upper bound.
+ # See Github issue 6875.
+ bounds_list = [
+ ((1, 2), (2, 1)),
+ ((2, 1), (1, 2)),
+ ((2, 1), (2, 1)),
+ ((np.inf, 0), (np.inf, 0)),
+ ((1, -np.inf), (0, 1)),
+ ]
+ for bounds in bounds_list:
+ with assert_raises(ValueError):
+ minimize(self.fun, [-1.0, 1.0], bounds=bounds, method='SLSQP')
+
+ def test_bounds_clipping(self):
+ #
+ # SLSQP returns bogus results for initial guess out of bounds, gh-6859
+ #
+ def f(x):
+ return (x[0] - 1)**2
+
+ sol = minimize(f, [10], method='slsqp', bounds=[(None, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', bounds=[(2, None)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', bounds=[(None, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', bounds=[(2, None)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-0.5], method='slsqp', bounds=[(-1, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', bounds=[(-1, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ def test_infeasible_initial(self):
+ # Check SLSQP behavior with infeasible initial point
+ def f(x):
+ x, = x
+ return x*x - 2*x + 1
+
+ cons_u = [{'type': 'ineq', 'fun': lambda x: 0 - x}]
+ cons_l = [{'type': 'ineq', 'fun': lambda x: x - 2}]
+ cons_ul = [{'type': 'ineq', 'fun': lambda x: 0 - x},
+ {'type': 'ineq', 'fun': lambda x: x + 1}]
+
+ sol = minimize(f, [10], method='slsqp', constraints=cons_u)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', constraints=cons_l)
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', constraints=cons_u)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', constraints=cons_l)
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-0.5], method='slsqp', constraints=cons_ul)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', constraints=cons_ul)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ @pytest.mark.xfail(scipy.show_config(mode='dicts')['Compilers']['fortran']['name']
+ == "intel-llvm",
+ reason="Runtime warning due to floating point issues, not logic")
+ def test_inconsistent_inequalities(self):
+ # gh-7618
+
+ def cost(x):
+ return -1 * x[0] + 4 * x[1]
+
+ def ineqcons1(x):
+ return x[1] - x[0] - 1
+
+ def ineqcons2(x):
+ return x[0] - x[1]
+
+ # The inequalities are inconsistent, so no solution can exist:
+ #
+ # x1 >= x0 + 1
+ # x0 >= x1
+
+ x0 = (1,5)
+ bounds = ((-5, 5), (-5, 5))
+ cons = (dict(type='ineq', fun=ineqcons1), dict(type='ineq', fun=ineqcons2))
+ res = minimize(cost, x0, method='SLSQP', bounds=bounds, constraints=cons)
+
+ assert_(not res.success)
+
+ def test_new_bounds_type(self):
+ def f(x):
+ return x[0] ** 2 + x[1] ** 2
+ bounds = Bounds([1, 0], [np.inf, np.inf])
+ sol = minimize(f, [0, 0], method='slsqp', bounds=bounds)
+ assert_(sol.success)
+ assert_allclose(sol.x, [1, 0])
+
+ def test_nested_minimization(self):
+
+ class NestedProblem:
+
+ def __init__(self):
+ self.F_outer_count = 0
+
+ def F_outer(self, x):
+ self.F_outer_count += 1
+ if self.F_outer_count > 1000:
+ raise Exception("Nested minimization failed to terminate.")
+ inner_res = minimize(self.F_inner, (3, 4), method="SLSQP")
+ assert_(inner_res.success)
+ assert_allclose(inner_res.x, [1, 1])
+ return x[0]**2 + x[1]**2 + x[2]**2
+
+ def F_inner(self, x):
+ return (x[0] - 1)**2 + (x[1] - 1)**2
+
+ def solve(self):
+ outer_res = minimize(self.F_outer, (5, 5, 5), method="SLSQP")
+ assert_(outer_res.success)
+ assert_allclose(outer_res.x, [0, 0, 0])
+
+ problem = NestedProblem()
+ problem.solve()
+
+ def test_gh1758(self):
+ # the test suggested in gh1758
+ # https://nlopt.readthedocs.io/en/latest/NLopt_Tutorial/
+ # implement two equality constraints, in R^2.
+ def fun(x):
+ return np.sqrt(x[1])
+
+ def f_eqcon(x):
+ """ Equality constraint """
+ return x[1] - (2 * x[0]) ** 3
+
+ def f_eqcon2(x):
+ """ Equality constraint """
+ return x[1] - (-x[0] + 1) ** 3
+
+ c1 = {'type': 'eq', 'fun': f_eqcon}
+ c2 = {'type': 'eq', 'fun': f_eqcon2}
+
+ res = minimize(fun, [8, 0.25], method='SLSQP',
+ constraints=[c1, c2], bounds=[(-0.5, 1), (0, 8)])
+
+ np.testing.assert_allclose(res.fun, 0.5443310539518)
+ np.testing.assert_allclose(res.x, [0.33333333, 0.2962963])
+ assert res.success
+
+ def test_gh9640(self):
+ cons = ({'type': 'ineq', 'fun': lambda x: -x[0] - x[1] - 3},
+ {'type': 'ineq', 'fun': lambda x: x[1] + x[2] - 2})
+ bnds = ((-2, 2), (-2, 2), (-2, 2))
+
+ def target(x):
+ return 1
+ x0 = [-1.8869783504471584, -0.640096352696244, -0.8174212253407696]
+ res = minimize(target, x0, method='SLSQP', bounds=bnds, constraints=cons,
+ options={'disp':False, 'maxiter':10000})
+
+ # The problem is infeasible, so it cannot succeed
+ assert not res.success
+
+ def test_parameters_stay_within_bounds(self):
+ # gh11403. For some problems the SLSQP Fortran code suggests a step
+ # outside one of the lower/upper bounds. When this happens
+ # approx_derivative complains because it's being asked to evaluate
+ # a gradient outside its domain.
+
+ # gh21872, removal of random initial position, replacing with specific
+ # starting point, because success/fail depends on the seed used.
+ bounds = Bounds(np.array([0.1]), np.array([1.0]))
+ x0 = np.array(bounds.lb + (bounds.ub - bounds.lb) *
+ 0.417022004702574)
+
+ def f(x):
+ assert (x >= bounds.lb).all()
+ return np.linalg.norm(x)
+ # The following should not raise any warnings which was the case, with the
+ # old Fortran code.
+ res = minimize(f, x0, method='SLSQP', bounds=bounds)
+ assert res.success
+
+
+def test_slsqp_segfault_wrong_workspace_computation():
+ # See gh-14915
+ # This problem is not well-defined, however should not cause a segfault.
+ # The previous F77 workspace computation did not handle only equality-
+ # constrained problems correctly.
+ rng = np.random.default_rng(1742651087222879)
+ x = rng.uniform(size=[22,365])
+ target = np.linspace(0.9, 4.0, 50)
+
+ def metric(v, weights):
+ return [[0, 0],[1, 1]]
+
+ def efficient_metric(v, target):
+ def metric_a(weights):
+ return metric(v, weights)[1][0]
+
+ def metric_b(weights, v):
+ return metric(v, weights)[0][0]
+
+ constraints = ({'type': 'eq', 'fun': lambda x: metric_a(x) - target},
+ {'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
+ weights = np.array([len(v)*[1./len(v)]])[0]
+ result = minimize(metric_b,
+ weights,
+ args=(v,),
+ method='SLSQP',
+ constraints=constraints)
+ return result
+
+ efficient_metric(x, target)
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_tnc.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cde9837bfd08e62916660a9750d833629b6b547
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_tnc.py
@@ -0,0 +1,345 @@
+"""
+Unit tests for TNC optimization routine from tnc.py
+"""
+import pytest
+from numpy.testing import assert_allclose, assert_equal
+
+import numpy as np
+from math import pow
+
+from scipy import optimize
+
+
+class TestTnc:
+ """TNC non-linear optimization.
+
+ These tests are taken from Prof. K. Schittkowski's test examples
+ for constrained non-linear programming.
+
+ http://www.uni-bayreuth.de/departments/math/~kschittkowski/home.htm
+
+ """
+ def setup_method(self):
+ # options for minimize
+ self.opts = {'disp': False, 'maxfun': 200}
+
+ # objective functions and Jacobian for each test
+ def f1(self, x, a=100.0):
+ return a * pow((x[1] - pow(x[0], 2)), 2) + pow(1.0 - x[0], 2)
+
+ def g1(self, x, a=100.0):
+ dif = [0, 0]
+ dif[1] = 2 * a * (x[1] - pow(x[0], 2))
+ dif[0] = -2.0 * (x[0] * (dif[1] - 1.0) + 1.0)
+ return dif
+
+ def fg1(self, x, a=100.0):
+ return self.f1(x, a), self.g1(x, a)
+
+ def f3(self, x):
+ return x[1] + pow(x[1] - x[0], 2) * 1.0e-5
+
+ def g3(self, x):
+ dif = [0, 0]
+ dif[0] = -2.0 * (x[1] - x[0]) * 1.0e-5
+ dif[1] = 1.0 - dif[0]
+ return dif
+
+ def fg3(self, x):
+ return self.f3(x), self.g3(x)
+
+ def f4(self, x):
+ return pow(x[0] + 1.0, 3) / 3.0 + x[1]
+
+ def g4(self, x):
+ dif = [0, 0]
+ dif[0] = pow(x[0] + 1.0, 2)
+ dif[1] = 1.0
+ return dif
+
+ def fg4(self, x):
+ return self.f4(x), self.g4(x)
+
+ def f5(self, x):
+ return np.sin(x[0] + x[1]) + pow(x[0] - x[1], 2) - \
+ 1.5 * x[0] + 2.5 * x[1] + 1.0
+
+ def g5(self, x):
+ dif = [0, 0]
+ v1 = np.cos(x[0] + x[1])
+ v2 = 2.0*(x[0] - x[1])
+
+ dif[0] = v1 + v2 - 1.5
+ dif[1] = v1 - v2 + 2.5
+ return dif
+
+ def fg5(self, x):
+ return self.f5(x), self.g5(x)
+
+ def f38(self, x):
+ return (100.0 * pow(x[1] - pow(x[0], 2), 2) +
+ pow(1.0 - x[0], 2) + 90.0 * pow(x[3] - pow(x[2], 2), 2) +
+ pow(1.0 - x[2], 2) + 10.1 * (pow(x[1] - 1.0, 2) +
+ pow(x[3] - 1.0, 2)) +
+ 19.8 * (x[1] - 1.0) * (x[3] - 1.0)) * 1.0e-5
+
+ def g38(self, x):
+ dif = [0, 0, 0, 0]
+ dif[0] = (-400.0 * x[0] * (x[1] - pow(x[0], 2)) -
+ 2.0 * (1.0 - x[0])) * 1.0e-5
+ dif[1] = (200.0 * (x[1] - pow(x[0], 2)) + 20.2 * (x[1] - 1.0) +
+ 19.8 * (x[3] - 1.0)) * 1.0e-5
+ dif[2] = (- 360.0 * x[2] * (x[3] - pow(x[2], 2)) -
+ 2.0 * (1.0 - x[2])) * 1.0e-5
+ dif[3] = (180.0 * (x[3] - pow(x[2], 2)) + 20.2 * (x[3] - 1.0) +
+ 19.8 * (x[1] - 1.0)) * 1.0e-5
+ return dif
+
+ def fg38(self, x):
+ return self.f38(x), self.g38(x)
+
+ def f45(self, x):
+ return 2.0 - x[0] * x[1] * x[2] * x[3] * x[4] / 120.0
+
+ def g45(self, x):
+ dif = [0] * 5
+ dif[0] = - x[1] * x[2] * x[3] * x[4] / 120.0
+ dif[1] = - x[0] * x[2] * x[3] * x[4] / 120.0
+ dif[2] = - x[0] * x[1] * x[3] * x[4] / 120.0
+ dif[3] = - x[0] * x[1] * x[2] * x[4] / 120.0
+ dif[4] = - x[0] * x[1] * x[2] * x[3] / 120.0
+ return dif
+
+ def fg45(self, x):
+ return self.f45(x), self.g45(x)
+
+ # tests
+ # minimize with method=TNC
+ def test_minimize_tnc1(self):
+ x0, bnds = [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+ iterx = [] # to test callback
+
+ res = optimize.minimize(self.f1, x0, method='TNC', jac=self.g1,
+ bounds=bnds, options=self.opts,
+ callback=iterx.append)
+ assert_allclose(res.fun, self.f1(xopt), atol=1e-8)
+ assert_equal(len(iterx), res.nit)
+
+ def test_minimize_tnc1b(self):
+ x0, bnds = np.array([-2, 1]), ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+ x = optimize.minimize(self.f1, x0, method='TNC',
+ bounds=bnds, options=self.opts).x
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-4)
+
+ def test_minimize_tnc1c(self):
+ x0, bnds = [-2, 1], ([-np.inf, None],[-1.5, None])
+ xopt = [1, 1]
+ x = optimize.minimize(self.fg1, x0, method='TNC',
+ jac=True, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8)
+
+ def test_minimize_tnc2(self):
+ x0, bnds = [-2, 1], ([-np.inf, None], [1.5, None])
+ xopt = [-1.2210262419616387, 1.5]
+ x = optimize.minimize(self.f1, x0, method='TNC',
+ jac=self.g1, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8)
+
+ def test_minimize_tnc3(self):
+ x0, bnds = [10, 1], ([-np.inf, None], [0.0, None])
+ xopt = [0, 0]
+ x = optimize.minimize(self.f3, x0, method='TNC',
+ jac=self.g3, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f3(x), self.f3(xopt), atol=1e-8)
+
+ def test_minimize_tnc4(self):
+ x0,bnds = [1.125, 0.125], [(1, None), (0, None)]
+ xopt = [1, 0]
+ x = optimize.minimize(self.f4, x0, method='TNC',
+ jac=self.g4, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f4(x), self.f4(xopt), atol=1e-8)
+
+ def test_minimize_tnc5(self):
+ x0, bnds = [0, 0], [(-1.5, 4),(-3, 3)]
+ xopt = [-0.54719755119659763, -1.5471975511965976]
+ x = optimize.minimize(self.f5, x0, method='TNC',
+ jac=self.g5, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f5(x), self.f5(xopt), atol=1e-8)
+
+ def test_minimize_tnc38(self):
+ x0, bnds = np.array([-3, -1, -3, -1]), [(-10, 10)]*4
+ xopt = [1]*4
+ x = optimize.minimize(self.f38, x0, method='TNC',
+ jac=self.g38, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f38(x), self.f38(xopt), atol=1e-8)
+
+ def test_minimize_tnc45(self):
+ x0, bnds = [2] * 5, [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
+ xopt = [1, 2, 3, 4, 5]
+ x = optimize.minimize(self.f45, x0, method='TNC',
+ jac=self.g45, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f45(x), self.f45(xopt), atol=1e-8)
+
+ # fmin_tnc
+ def test_tnc1(self):
+ fg, x, bounds = self.fg1, [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, args=(100.0, ),
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc1b(self):
+ x, bounds = [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+
+ x, nf, rc = optimize.fmin_tnc(self.f1, x, approx_grad=True,
+ bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-4,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc1c(self):
+ x, bounds = [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+
+ x, nf, rc = optimize.fmin_tnc(self.f1, x, fprime=self.g1,
+ bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc2(self):
+ fg, x, bounds = self.fg1, [-2, 1], ([-np.inf, None], [1.5, None])
+ xopt = [-1.2210262419616387, 1.5]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc3(self):
+ fg, x, bounds = self.fg3, [10, 1], ([-np.inf, None], [0.0, None])
+ xopt = [0, 0]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f3(x), self.f3(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc4(self):
+ fg, x, bounds = self.fg4, [1.125, 0.125], [(1, None), (0, None)]
+ xopt = [1, 0]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f4(x), self.f4(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc5(self):
+ fg, x, bounds = self.fg5, [0, 0], [(-1.5, 4),(-3, 3)]
+ xopt = [-0.54719755119659763, -1.5471975511965976]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f5(x), self.f5(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc38(self):
+ fg, x, bounds = self.fg38, np.array([-3, -1, -3, -1]), [(-10, 10)]*4
+ xopt = [1]*4
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f38(x), self.f38(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc45(self):
+ fg, x, bounds = self.fg45, [2] * 5, [(0, 1), (0, 2), (0, 3),
+ (0, 4), (0, 5)]
+ xopt = [1, 2, 3, 4, 5]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f45(x), self.f45(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_raising_exceptions(self):
+ # tnc was ported to cython from hand-crafted cpython code
+ # check that Exception handling works.
+ def myfunc(x):
+ raise RuntimeError("myfunc")
+
+ def myfunc1(x):
+ return optimize.rosen(x)
+
+ def callback(x):
+ raise ValueError("callback")
+
+ with pytest.raises(RuntimeError):
+ optimize.minimize(myfunc, [0, 1], method="TNC")
+
+ with pytest.raises(ValueError):
+ optimize.minimize(
+ myfunc1, [0, 1], method="TNC", callback=callback
+ )
+
+ def test_callback_shouldnt_affect_minimization(self):
+ # gh14879. The output of a TNC minimization was different depending
+ # on whether a callback was used or not. The two should be equivalent.
+ # The issue was that TNC was unscaling/scaling x, and this process was
+ # altering x in the process. Now the callback uses an unscaled
+ # temporary copy of x.
+ def callback(x):
+ pass
+
+ fun = optimize.rosen
+ bounds = [(0, 10)] * 4
+ x0 = [1, 2, 3, 4.]
+ res = optimize.minimize(
+ fun, x0, bounds=bounds, method="TNC", options={"maxfun": 1000}
+ )
+ res2 = optimize.minimize(
+ fun, x0, bounds=bounds, method="TNC", options={"maxfun": 1000},
+ callback=callback
+ )
+ assert_allclose(res2.x, res.x)
+ assert_allclose(res2.fun, res.fun)
+ assert_equal(res2.nfev, res.nfev)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..e62d1045e73b7107fbd530e86dd2578de4d51c3f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion.py
@@ -0,0 +1,109 @@
+"""
+Unit tests for trust-region optimization routines.
+
+"""
+import pytest
+import numpy as np
+from numpy.testing import assert_, assert_equal, assert_allclose
+from scipy.optimize import (minimize, rosen, rosen_der, rosen_hess,
+ rosen_hess_prod)
+
+
+class Accumulator:
+ """ This is for testing callbacks."""
+ def __init__(self):
+ self.count = 0
+ self.accum = None
+
+ def __call__(self, x):
+ self.count += 1
+ if self.accum is None:
+ self.accum = np.array(x)
+ else:
+ self.accum += x
+
+
+class TestTrustRegionSolvers:
+
+ def setup_method(self):
+ self.x_opt = [1.0, 1.0]
+ self.easy_guess = [2.0, 2.0]
+ self.hard_guess = [-1.2, 1.0]
+
+ def test_dogleg_accuracy(self):
+ # test the accuracy and the return_all option
+ x0 = self.hard_guess
+ r = minimize(rosen, x0, jac=rosen_der, hess=rosen_hess, tol=1e-8,
+ method='dogleg', options={'return_all': True},)
+ assert_allclose(x0, r['allvecs'][0])
+ assert_allclose(r['x'], r['allvecs'][-1])
+ assert_allclose(r['x'], self.x_opt)
+
+ def test_dogleg_callback(self):
+ # test the callback mechanism and the maxiter and return_all options
+ accumulator = Accumulator()
+ maxiter = 5
+ r = minimize(rosen, self.hard_guess, jac=rosen_der, hess=rosen_hess,
+ callback=accumulator, method='dogleg',
+ options={'return_all': True, 'maxiter': maxiter},)
+ assert_equal(accumulator.count, maxiter)
+ assert_equal(len(r['allvecs']), maxiter+1)
+ assert_allclose(r['x'], r['allvecs'][-1])
+ assert_allclose(sum(r['allvecs'][1:]), accumulator.accum)
+
+ def test_dogleg_user_warning(self):
+ with pytest.warns(RuntimeWarning,
+ match=r'Maximum number of iterations'):
+ minimize(rosen, self.hard_guess, jac=rosen_der,
+ hess=rosen_hess, method='dogleg',
+ options={'disp': True, 'maxiter': 1}, )
+
+ def test_solver_concordance(self):
+ # Assert that dogleg uses fewer iterations than ncg on the Rosenbrock
+ # test function, although this does not necessarily mean
+ # that dogleg is faster or better than ncg even for this function
+ # and especially not for other test functions.
+ f = rosen
+ g = rosen_der
+ h = rosen_hess
+ for x0 in (self.easy_guess, self.hard_guess):
+ r_dogleg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='dogleg', options={'return_all': True})
+ r_trust_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='trust-ncg',
+ options={'return_all': True})
+ r_trust_krylov = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='trust-krylov',
+ options={'return_all': True})
+ r_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='newton-cg', options={'return_all': True})
+ r_iterative = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='trust-exact',
+ options={'return_all': True})
+ assert_allclose(self.x_opt, r_dogleg['x'])
+ assert_allclose(self.x_opt, r_trust_ncg['x'])
+ assert_allclose(self.x_opt, r_trust_krylov['x'])
+ assert_allclose(self.x_opt, r_ncg['x'])
+ assert_allclose(self.x_opt, r_iterative['x'])
+ assert_(len(r_dogleg['allvecs']) < len(r_ncg['allvecs']))
+
+ def test_trust_ncg_hessp(self):
+ for x0 in (self.easy_guess, self.hard_guess, self.x_opt):
+ r = minimize(rosen, x0, jac=rosen_der, hessp=rosen_hess_prod,
+ tol=1e-8, method='trust-ncg')
+ assert_allclose(self.x_opt, r['x'])
+
+ def test_trust_ncg_start_in_optimum(self):
+ r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
+ tol=1e-8, method='trust-ncg')
+ assert_allclose(self.x_opt, r['x'])
+
+ def test_trust_krylov_start_in_optimum(self):
+ r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
+ tol=1e-8, method='trust-krylov')
+ assert_allclose(self.x_opt, r['x'])
+
+ def test_trust_exact_start_in_optimum(self):
+ r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
+ tol=1e-8, method='trust-exact')
+ assert_allclose(self.x_opt, r['x'])
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_exact.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a871a250b3a63ff6a6e10ad1f188580256b9447
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_exact.py
@@ -0,0 +1,492 @@
+"""
+Unit tests for trust-region iterative subproblem.
+
+"""
+import pytest
+import numpy as np
+from scipy.optimize._trustregion_exact import (
+ estimate_smallest_singular_value,
+ singular_leading_submatrix,
+ IterativeSubproblem)
+from scipy.linalg import (svd, get_lapack_funcs, det, qr, norm)
+from numpy.testing import (assert_allclose, assert_array_equal,
+ assert_equal, assert_array_almost_equal)
+
+
+def random_entry(n, min_eig, max_eig, case, rng=None):
+ rng = np.random.default_rng(rng)
+
+ # Generate random matrix
+ rand = rng.uniform(low=-1, high=1, size=(n, n))
+
+ # QR decomposition
+ Q, _, _ = qr(rand, pivoting='True')
+
+ # Generate random eigenvalues
+ eigvalues = rng.uniform(low=min_eig, high=max_eig, size=n)
+ eigvalues = np.sort(eigvalues)[::-1]
+
+ # Generate matrix
+ Qaux = np.multiply(eigvalues, Q)
+ A = np.dot(Qaux, Q.T)
+
+ # Generate gradient vector accordingly
+ # to the case is being tested.
+ if case == 'hard':
+ g = np.zeros(n)
+ g[:-1] = rng.uniform(low=-1, high=1, size=n-1)
+ g = np.dot(Q, g)
+ elif case == 'jac_equal_zero':
+ g = np.zeros(n)
+ else:
+ g = rng.uniform(low=-1, high=1, size=n)
+
+ return A, g
+
+
+class TestEstimateSmallestSingularValue:
+
+ def test_for_ill_condiotioned_matrix(self):
+
+ # Ill-conditioned triangular matrix
+ C = np.array([[1, 2, 3, 4],
+ [0, 0.05, 60, 7],
+ [0, 0, 0.8, 9],
+ [0, 0, 0, 10]])
+
+ # Get svd decomposition
+ U, s, Vt = svd(C)
+
+ # Get smallest singular value and correspondent right singular vector.
+ smin_svd = s[-1]
+ zmin_svd = Vt[-1, :]
+
+ # Estimate smallest singular value
+ smin, zmin = estimate_smallest_singular_value(C)
+
+ # Check the estimation
+ assert_array_almost_equal(smin, smin_svd, decimal=8)
+ assert_array_almost_equal(abs(zmin), abs(zmin_svd), decimal=8)
+
+
+class TestSingularLeadingSubmatrix:
+
+ def test_for_already_singular_leading_submatrix(self):
+
+ # Define test matrix A.
+ # Note that the leading 2x2 submatrix is singular.
+ A = np.array([[1, 2, 3],
+ [2, 4, 5],
+ [3, 5, 6]])
+
+ # Get Cholesky from lapack functions
+ cholesky, = get_lapack_funcs(('potrf',), (A,))
+
+ # Compute Cholesky Decomposition
+ c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)
+
+ delta, v = singular_leading_submatrix(A, c, k)
+
+ A[k-1, k-1] += delta
+
+ # Check if the leading submatrix is singular.
+ assert_array_almost_equal(det(A[:k, :k]), 0)
+
+ # Check if `v` fulfil the specified properties
+ quadratic_term = np.dot(v, np.dot(A, v))
+ assert_array_almost_equal(quadratic_term, 0)
+
+ def test_for_simetric_indefinite_matrix(self):
+
+ # Define test matrix A.
+ # Note that the leading 5x5 submatrix is indefinite.
+ A = np.asarray([[1, 2, 3, 7, 8],
+ [2, 5, 5, 9, 0],
+ [3, 5, 11, 1, 2],
+ [7, 9, 1, 7, 5],
+ [8, 0, 2, 5, 8]])
+
+ # Get Cholesky from lapack functions
+ cholesky, = get_lapack_funcs(('potrf',), (A,))
+
+ # Compute Cholesky Decomposition
+ c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)
+
+ delta, v = singular_leading_submatrix(A, c, k)
+
+ A[k-1, k-1] += delta
+
+ # Check if the leading submatrix is singular.
+ assert_array_almost_equal(det(A[:k, :k]), 0)
+
+ # Check if `v` fulfil the specified properties
+ quadratic_term = np.dot(v, np.dot(A, v))
+ assert_array_almost_equal(quadratic_term, 0)
+
+ def test_for_first_element_equal_to_zero(self):
+
+ # Define test matrix A.
+ # Note that the leading 2x2 submatrix is singular.
+ A = np.array([[0, 3, 11],
+ [3, 12, 5],
+ [11, 5, 6]])
+
+ # Get Cholesky from lapack functions
+ cholesky, = get_lapack_funcs(('potrf',), (A,))
+
+ # Compute Cholesky Decomposition
+ c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)
+
+ delta, v = singular_leading_submatrix(A, c, k)
+
+ A[k-1, k-1] += delta
+
+ # Check if the leading submatrix is singular
+ assert_array_almost_equal(det(A[:k, :k]), 0)
+
+ # Check if `v` fulfil the specified properties
+ quadratic_term = np.dot(v, np.dot(A, v))
+ assert_array_almost_equal(quadratic_term, 0)
+
+
+class TestIterativeSubproblem:
+
+ def test_for_the_easy_case(self):
+
+ # `H` is chosen such that `g` is not orthogonal to the
+ # eigenvector associated with the smallest eigenvalue `s`.
+ H = [[10, 2, 3, 4],
+ [2, 1, 7, 1],
+ [3, 7, 1, 7],
+ [4, 1, 7, 2]]
+ g = [1, 1, 1, 1]
+
+ # Trust Radius
+ trust_radius = 1
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, [0.00393332, -0.55260862,
+ 0.67065477, -0.49480341])
+ assert_array_almost_equal(hits_boundary, True)
+
+ def test_for_the_hard_case(self):
+
+ # `H` is chosen such that `g` is orthogonal to the
+ # eigenvector associated with the smallest eigenvalue `s`.
+ H = [[10, 2, 3, 4],
+ [2, 1, 7, 1],
+ [3, 7, 1, 7],
+ [4, 1, 7, 2]]
+ g = [6.4852641521327437, 1, 1, 1]
+ s = -8.2151519874416614
+
+ # Trust Radius
+ trust_radius = 1
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(-s, subprob.lambda_current)
+
+ def test_gh20244(self):
+ g = [20, -10]
+ H = [[15, 0], [0, 5]]
+
+ subprob = IterativeSubproblem(x=np.zeros(2), fun=lambda _: 0,
+ jac=lambda _: np.array(g),
+ hess=lambda _: np.array(H), k_easy=1e-6,
+ k_hard=1e-9)
+ p, hits_boundary = subprob.solve(1.0)
+
+ assert_allclose(p, [-0.77472957, 0.63229272])
+ assert hits_boundary
+
+ def test_for_interior_convergence(self):
+
+ H = [[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988],
+ [0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588],
+ [0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867],
+ [-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166],
+ [0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]]
+
+ g = [0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534]
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H))
+ p, hits_boundary = subprob.solve(1.1)
+
+ assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999,
+ -0.67005053, 0.31586769])
+ assert_array_almost_equal(hits_boundary, False)
+ assert_array_almost_equal(subprob.lambda_current, 0)
+ assert_array_almost_equal(subprob.niter, 1)
+
+ def test_for_jac_equal_zero(self):
+
+ H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
+ [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
+ [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
+ [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
+ [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]]
+
+ g = [0, 0, 0, 0, 0]
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(1.1)
+
+ assert_array_almost_equal(p, [0.06910534, -0.01432721,
+ -0.65311947, -0.23815972,
+ -0.84954934])
+ assert_array_almost_equal(hits_boundary, True)
+
+ def test_for_jac_very_close_to_zero(self):
+
+ H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
+ [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
+ [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
+ [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
+ [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]]
+
+ g = [0, 0, 0, 0, 1e-15]
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(1.1)
+
+ assert_array_almost_equal(p, [0.06910534, -0.01432721,
+ -0.65311947, -0.23815972,
+ -0.84954934])
+ assert_array_almost_equal(hits_boundary, True)
+
+ @pytest.mark.thread_unsafe(reason="fails in parallel")
+ @pytest.mark.fail_slow(10)
+ def test_for_random_entries(self):
+ rng = np.random.default_rng(1)
+
+ # Dimension
+ n = 5
+
+ for case in ('easy', 'hard', 'jac_equal_zero'):
+
+ eig_limits = [(-20, -15),
+ (-10, -5),
+ (-10, 0),
+ (-5, 5),
+ (-10, 10),
+ (0, 10),
+ (5, 10),
+ (15, 20)]
+
+ for min_eig, max_eig in eig_limits:
+ # Generate random symmetric matrix H with
+ # eigenvalues between min_eig and max_eig.
+ H, g = random_entry(n, min_eig, max_eig, case, rng=rng)
+
+ # Trust radius
+ trust_radius_list = [0.1, 0.3, 0.6, 0.8, 1, 1.2, 3.3, 5.5, 10]
+
+ for trust_radius in trust_radius_list:
+ # Solve subproblem with very high accuracy
+ subprob_ac = IterativeSubproblem(0,
+ lambda x: 0,
+ lambda x: g,
+ lambda x: H,
+ k_easy=1e-10,
+ k_hard=1e-10)
+
+ p_ac, hits_boundary_ac = subprob_ac.solve(trust_radius)
+
+ # Compute objective function value
+ J_ac = 1/2*np.dot(p_ac, np.dot(H, p_ac))+np.dot(g, p_ac)
+
+ stop_criteria = [(0.1, 2),
+ (0.5, 1.1),
+ (0.9, 1.01)]
+
+ for k_opt, k_trf in stop_criteria:
+
+ # k_easy and k_hard computed in function
+ # of k_opt and k_trf accordingly to
+ # Conn, A. R., Gould, N. I., & Toint, P. L. (2000).
+ # "Trust region methods". Siam. p. 197.
+ k_easy = min(k_trf-1,
+ 1-np.sqrt(k_opt))
+ k_hard = 1-k_opt
+
+ # Solve subproblem
+ subprob = IterativeSubproblem(0,
+ lambda x: 0,
+ lambda x: g,
+ lambda x: H,
+ k_easy=k_easy,
+ k_hard=k_hard)
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ # Compute objective function value
+ J = 1/2*np.dot(p, np.dot(H, p))+np.dot(g, p)
+
+ # Check if it respect k_trf
+ if hits_boundary:
+ assert_array_equal(np.abs(norm(p)-trust_radius) <=
+ (k_trf-1)*trust_radius, True)
+ else:
+ assert_equal(norm(p) <= trust_radius, True)
+
+ # Check if it respect k_opt
+ assert_equal(J <= k_opt*J_ac, True)
+
+
+ def test_for_finite_number_of_iterations(self):
+ """Regression test for gh-12513"""
+ H = np.array(
+ [[3.67335930e01, -2.52334820e02, 1.15477558e01, -1.19933725e-03,
+ -2.06408851e03, -2.05821411e00, -2.52334820e02, -6.52076924e02,
+ -2.71362566e-01, -1.98885126e00, 1.22085415e00, 2.30220713e00,
+ -9.71278532e-02, -5.11210123e-01, -1.00399562e00, 1.43319679e-01,
+ 6.03815471e00, -6.38719934e-02, 1.65623929e-01],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [1.15477558e01, -9.92814996e01, 3.63872363e03, -4.40007197e-01,
+ -9.55435081e02, -1.13985105e00, -9.92814996e01, -2.58307255e02,
+ -5.21335218e01, -3.77485107e02, -6.75338369e01, -1.89457169e02,
+ 5.67828623e00, 5.82402681e00, 1.72734354e01, -4.29114840e00,
+ -7.84885258e01, 3.17594634e00, 2.45242852e00],
+ [-1.19933725e-03, 1.06533600e-02, -4.40007197e-01, 5.73576663e-05,
+ 1.01563710e-01, 1.18838745e-04, 1.06533600e-02, 2.76535767e-02,
+ 6.25788669e-03, 4.50699620e-02, 8.64152333e-03, 2.27772377e-02,
+ -8.51026855e-04, 1.65316383e-04, 1.38977551e-03, 5.51629259e-04,
+ 1.38447755e-02, -5.17956723e-04, -1.29260347e-04],
+ [-2.06408851e03, 1.44442941e04, -9.55435081e02, 1.01563710e-01,
+ 1.23101825e05, 1.26467259e02, 1.44442941e04, 3.74590279e04,
+ 2.18498571e01, 1.60254460e02, -7.52977260e01, -1.17989623e02,
+ 6.58253160e00, 3.14949206e01, 4.98527190e01, -9.33338661e00,
+ -3.80465752e02, 4.33872213e00, -1.14768816e01],
+ [-2.05821411e00, 1.43811694e01, -1.13985105e00, 1.18838745e-04,
+ 1.26467259e02, 1.46226198e-01, 1.43811694e01, 3.74509252e01,
+ 2.76928748e-02, 2.03023837e-01, -8.84279903e-02, -1.29523344e-01,
+ 8.06424434e-03, 3.83330661e-02, 5.81579023e-02, -1.12874980e-02,
+ -4.48118297e-01, 5.15022284e-03, -1.41501894e-02],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [-6.52076924e02, 4.56694461e03, -2.58307255e02, 2.76535767e-02,
+ 3.74590279e04, 3.74509252e01, 4.56694461e03, 1.18278398e04,
+ 5.82242837e00, 4.26867612e01, -2.03167952e01, -3.22894255e01,
+ 1.75705078e00, 8.37153730e00, 1.32246076e01, -2.49238529e00,
+ -1.01316422e02, 1.16165466e00, -3.09390862e00],
+ [-2.71362566e-01, 2.22263363e00, -5.21335218e01, 6.25788669e-03,
+ 2.18498571e01, 2.76928748e-02, 2.22263363e00, 5.82242837e00,
+ 4.36278066e01, 3.14836583e02, -2.04747938e01, -3.05535101e01,
+ -1.24881456e-01, 1.15775394e01, 4.06907410e01, -1.39317748e00,
+ -3.90902798e01, -9.71716488e-02, 1.06851340e-01],
+ [-1.98885126e00, 1.62977318e01, -3.77485107e02, 4.50699620e-02,
+ 1.60254460e02, 2.03023837e-01, 1.62977318e01, 4.26867612e01,
+ 3.14836583e02, 2.27255216e03, -1.47029712e02, -2.19649109e02,
+ -8.83963155e-01, 8.28571708e01, 2.91399776e02, -9.97382920e00,
+ -2.81069124e02, -6.94946614e-01, 7.38151960e-01],
+ [1.22085415e00, -7.81539315e00, -6.75338369e01, 8.64152333e-03,
+ -7.52977260e01, -8.84279903e-02, -7.81539315e00, -2.03167952e01,
+ -2.04747938e01, -1.47029712e02, 7.83372613e01, 1.64416651e02,
+ -4.30243758e00, -2.59579610e01, -6.25644064e01, 6.69974667e00,
+ 2.31011701e02, -2.68540084e00, 5.44531151e00],
+ [2.30220713e00, -1.24938012e01, -1.89457169e02, 2.27772377e-02,
+ -1.17989623e02, -1.29523344e-01, -1.24938012e01, -3.22894255e01,
+ -3.05535101e01, -2.19649109e02, 1.64416651e02, 3.75893031e02,
+ -7.42084715e00, -4.56437599e01, -1.11071032e02, 1.18761368e01,
+ 4.78724142e02, -5.06804139e00, 8.81448081e00],
+ [-9.71278532e-02, 6.74029088e-01, 5.67828623e00, -8.51026855e-04,
+ 6.58253160e00, 8.06424434e-03, 6.74029088e-01, 1.75705078e00,
+ -1.24881456e-01, -8.83963155e-01, -4.30243758e00, -7.42084715e00,
+ 9.62009425e-01, 1.53836355e00, 2.23939458e00, -8.01872920e-01,
+ -1.92191084e01, 3.77713908e-01, -8.32946970e-01],
+ [-5.11210123e-01, 3.22802671e00, 5.82402681e00, 1.65316383e-04,
+ 3.14949206e01, 3.83330661e-02, 3.22802671e00, 8.37153730e00,
+ 1.15775394e01, 8.28571708e01, -2.59579610e01, -4.56437599e01,
+ 1.53836355e00, 2.63851056e01, 7.34859767e01, -4.39975402e00,
+ -1.12015747e02, 5.11542219e-01, -2.64962727e00],
+ [-1.00399562e00, 5.14978971e00, 1.72734354e01, 1.38977551e-03,
+ 4.98527190e01, 5.81579023e-02, 5.14978971e00, 1.32246076e01,
+ 4.06907410e01, 2.91399776e02, -6.25644064e01, -1.11071032e02,
+ 2.23939458e00, 7.34859767e01, 2.36535458e02, -1.09636675e01,
+ -2.72152068e02, 6.65888059e-01, -6.29295273e00],
+ [1.43319679e-01, -9.58561209e-01, -4.29114840e00, 5.51629259e-04,
+ -9.33338661e00, -1.12874980e-02, -9.58561209e-01, -2.49238529e00,
+ -1.39317748e00, -9.97382920e00, 6.69974667e00, 1.18761368e01,
+ -8.01872920e-01, -4.39975402e00, -1.09636675e01, 1.16820748e00,
+ 3.00817252e01, -4.51359819e-01, 9.82625204e-01],
+ [6.03815471e00, -3.92199895e01, -7.84885258e01, 1.38447755e-02,
+ -3.80465752e02, -4.48118297e-01, -3.92199895e01, -1.01316422e02,
+ -3.90902798e01, -2.81069124e02, 2.31011701e02, 4.78724142e02,
+ -1.92191084e01, -1.12015747e02, -2.72152068e02, 3.00817252e01,
+ 1.13232557e03, -1.33695932e01, 2.22934659e01],
+ [-6.38719934e-02, 4.47201278e-01, 3.17594634e00, -5.17956723e-04,
+ 4.33872213e00, 5.15022284e-03, 4.47201278e-01, 1.16165466e00,
+ -9.71716488e-02, -6.94946614e-01, -2.68540084e00, -5.06804139e00,
+ 3.77713908e-01, 5.11542219e-01, 6.65888059e-01, -4.51359819e-01,
+ -1.33695932e01, 4.27994168e-01, -5.09020820e-01],
+ [1.65623929e-01, -1.17866744e00, 2.45242852e00, -1.29260347e-04,
+ -1.14768816e01, -1.41501894e-02, -1.17866744e00, -3.09390862e00,
+ 1.06851340e-01, 7.38151960e-01, 5.44531151e00, 8.81448081e00,
+ -8.32946970e-01, -2.64962727e00, -6.29295273e00, 9.82625204e-01,
+ 2.22934659e01, -5.09020820e-01, 4.09964606e00]]
+ )
+ J = np.array([
+ -2.53298102e-07, 1.76392040e-06, 1.74776130e-06, -4.19479903e-10,
+ 1.44167498e-05, 1.41703911e-08, 1.76392030e-06, 4.96030153e-06,
+ -2.35771675e-07, -1.68844985e-06, 4.29218258e-07, 6.65445159e-07,
+ -3.87045830e-08, -3.17236594e-07, -1.21120169e-06, 4.59717313e-08,
+ 1.67123246e-06, 1.46624675e-08, 4.22723383e-08
+ ])
+
+ subproblem_maxiter = [None, 10]
+ for maxiter in subproblem_maxiter:
+ # Solve Subproblem
+ subprob = IterativeSubproblem(
+ x=0,
+ fun=lambda x: 0,
+ jac=lambda x: J,
+ hess=lambda x: H,
+ k_easy=0.1,
+ k_hard=0.2,
+ maxiter=maxiter,
+ )
+ trust_radius = 1
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ if maxiter is None:
+ assert subprob.niter <= IterativeSubproblem.MAXITER_DEFAULT
+ else:
+ assert subprob.niter <= maxiter
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_krylov.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_krylov.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2c18f931ab3e938ca7fc039dd9fa21783830aee
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_krylov.py
@@ -0,0 +1,168 @@
+"""
+Unit tests for Krylov space trust-region subproblem solver.
+
+"""
+import numpy as np
+from scipy.optimize._trlib import (get_trlib_quadratic_subproblem)
+from numpy.testing import (assert_,
+ assert_almost_equal,
+ assert_equal, assert_array_almost_equal)
+
+KrylovQP = get_trlib_quadratic_subproblem(tol_rel_i=1e-8, tol_rel_b=1e-6)
+KrylovQP_disp = get_trlib_quadratic_subproblem(tol_rel_i=1e-8, tol_rel_b=1e-6,
+ disp=True)
+
+class TestKrylovQuadraticSubproblem:
+
+ def test_for_the_easy_case(self):
+
+ # `H` is chosen such that `g` is not orthogonal to the
+ # eigenvector associated with the smallest eigenvalue.
+ H = np.array([[1.0, 0.0, 4.0],
+ [0.0, 2.0, 0.0],
+ [4.0, 0.0, 3.0]])
+ g = np.array([5.0, 0.0, 4.0])
+
+ # Trust Radius
+ trust_radius = 1.0
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, np.array([-1.0, 0.0, 0.0]))
+ assert_equal(hits_boundary, True)
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ trust_radius = 0.5
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p,
+ np.array([-0.46125446, 0., -0.19298788]))
+ assert_equal(hits_boundary, True)
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ def test_for_the_hard_case(self):
+
+ # `H` is chosen such that `g` is orthogonal to the
+ # eigenvector associated with the smallest eigenvalue.
+ H = np.array([[1.0, 0.0, 4.0],
+ [0.0, 2.0, 0.0],
+ [4.0, 0.0, 3.0]])
+ g = np.array([0.0, 2.0, 0.0])
+
+ # Trust Radius
+ trust_radius = 1.0
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, np.array([0.0, -1.0, 0.0]))
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ trust_radius = 0.5
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, np.array([0.0, -0.5, 0.0]))
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ def test_for_interior_convergence(self):
+
+ H = np.array([[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988],
+ [0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588],
+ [0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867],
+ [-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166],
+ [0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]])
+ g = np.array([0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534])
+ trust_radius = 1.1
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+
+ assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999,
+ -0.67005053, 0.31586769])
+ assert_array_almost_equal(hits_boundary, False)
+
+ def test_for_very_close_to_zero(self):
+
+ H = np.array([[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
+ [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
+ [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
+ [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
+ [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]])
+ g = np.array([0, 0, 0, 0, 1e-6])
+ trust_radius = 1.1
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ assert_array_almost_equal(p, [0.06910534, -0.01432721,
+ -0.65311947, -0.23815972,
+ -0.84954934])
+ assert_array_almost_equal(hits_boundary, True)
+
+ def test_disp(self, capsys):
+ H = -np.eye(5)
+ g = np.array([0, 0, 0, 0, 1e-6])
+ trust_radius = 1.1
+
+ subprob = KrylovQP_disp(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+ out, err = capsys.readouterr()
+ assert_(out.startswith(' TR Solving trust region problem'), repr(out))
+
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_zeros.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf2132dd8768441f04c60b28db2a449081ff3118
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tests/test_zeros.py
@@ -0,0 +1,1033 @@
+import warnings
+
+from functools import lru_cache
+
+import pytest
+
+from numpy.testing import (assert_,
+ assert_allclose,
+ assert_equal,
+ assert_array_equal)
+import numpy as np
+from numpy import finfo, power, nan, isclose, sqrt, exp, sin, cos
+
+from scipy import optimize
+from scipy.optimize import (_zeros_py as zeros, newton, root_scalar,
+ OptimizeResult)
+
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+
+# Import testing parameters
+from scipy.optimize._tstutils import get_tests, functions as tstutils_functions
+
+TOL = 4*np.finfo(float).eps # tolerance
+
+_FLOAT_EPS = finfo(float).eps
+
+bracket_methods = [zeros.bisect, zeros.ridder, zeros.brentq, zeros.brenth,
+ zeros.toms748]
+gradient_methods = [zeros.newton]
+all_methods = bracket_methods + gradient_methods
+
+# A few test functions used frequently:
+# # A simple quadratic, (x-1)^2 - 1
+def f1(x):
+ return x ** 2 - 2 * x - 1
+
+
+def f1_1(x):
+ return 2 * x - 2
+
+
+def f1_2(x):
+ return 2.0 + 0 * x
+
+
+def f1_and_p_and_pp(x):
+ return f1(x), f1_1(x), f1_2(x)
+
+
+# Simple transcendental function
+def f2(x):
+ return exp(x) - cos(x)
+
+
+def f2_1(x):
+ return exp(x) + sin(x)
+
+
+def f2_2(x):
+ return exp(x) + cos(x)
+
+
+# lru cached function
+@lru_cache
+def f_lrucached(x):
+ return x
+
+
+class TestScalarRootFinders:
+ # Basic tests for all scalar root finders
+
+ xtol = 4 * np.finfo(float).eps
+ rtol = 4 * np.finfo(float).eps
+
+ def _run_one_test(self, tc, method, sig_args_keys=None,
+ sig_kwargs_keys=None, **kwargs):
+ method_args = []
+ for k in sig_args_keys or []:
+ if k not in tc:
+ # If a,b not present use x0, x1. Similarly for f and func
+ k = {'a': 'x0', 'b': 'x1', 'func': 'f'}.get(k, k)
+ method_args.append(tc[k])
+
+ method_kwargs = dict(**kwargs)
+ method_kwargs.update({'full_output': True, 'disp': False})
+ for k in sig_kwargs_keys or []:
+ method_kwargs[k] = tc[k]
+
+ root = tc.get('root')
+ func_args = tc.get('args', ())
+
+ try:
+ r, rr = method(*method_args, args=func_args, **method_kwargs)
+ return root, rr, tc
+ except Exception:
+ return root, zeros.RootResults(nan, -1, -1, zeros._EVALUEERR, method), tc
+
+ def run_tests(self, tests, method, name, known_fail=None, **kwargs):
+ r"""Run test-cases using the specified method and the supplied signature.
+
+ Extract the arguments for the method call from the test case
+ dictionary using the supplied keys for the method's signature."""
+ # The methods have one of two base signatures:
+ # (f, a, b, **kwargs) # newton
+ # (func, x0, **kwargs) # bisect/brentq/...
+
+ # FullArgSpec with args, varargs, varkw, defaults, ...
+ sig = _getfullargspec(method)
+ assert_(not sig.kwonlyargs)
+ nDefaults = len(sig.defaults)
+ nRequired = len(sig.args) - nDefaults
+ sig_args_keys = sig.args[:nRequired]
+ sig_kwargs_keys = []
+ if name in ['secant', 'newton', 'halley']:
+ if name in ['newton', 'halley']:
+ sig_kwargs_keys.append('fprime')
+ if name in ['halley']:
+ sig_kwargs_keys.append('fprime2')
+ kwargs['tol'] = self.xtol
+ else:
+ kwargs['xtol'] = self.xtol
+ kwargs['rtol'] = self.rtol
+
+ results = [list(self._run_one_test(
+ tc, method, sig_args_keys=sig_args_keys,
+ sig_kwargs_keys=sig_kwargs_keys, **kwargs)) for tc in tests]
+ # results= [[true root, full output, tc], ...]
+
+ known_fail = known_fail or []
+ notcvgd = [elt for elt in results if not elt[1].converged]
+ notcvgd = [elt for elt in notcvgd if elt[-1]['ID'] not in known_fail]
+ notcvged_IDS = [elt[-1]['ID'] for elt in notcvgd]
+ assert_equal([len(notcvged_IDS), notcvged_IDS], [0, []])
+
+ # The usable xtol and rtol depend on the test
+ tols = {'xtol': self.xtol, 'rtol': self.rtol}
+ tols.update(**kwargs)
+ rtol = tols['rtol']
+ atol = tols.get('tol', tols['xtol'])
+
+ cvgd = [elt for elt in results if elt[1].converged]
+ approx = [elt[1].root for elt in cvgd]
+ correct = [elt[0] for elt in cvgd]
+ # See if the root matches the reference value
+ notclose = [[a] + elt for a, c, elt in zip(approx, correct, cvgd) if
+ not isclose(a, c, rtol=rtol, atol=atol)
+ and elt[-1]['ID'] not in known_fail]
+ # If not, evaluate the function and see if is 0 at the purported root
+ fvs = [tc['f'](aroot, *tc.get('args', tuple()))
+ for aroot, c, fullout, tc in notclose]
+ notclose = [[fv] + elt for fv, elt in zip(fvs, notclose) if fv != 0]
+ assert_equal([notclose, len(notclose)], [[], 0])
+ method_from_result = [result[1].method for result in results]
+ expected_method = [name for _ in results]
+ assert_equal(method_from_result, expected_method)
+
+ def run_collection(self, collection, method, name, smoothness=None,
+ known_fail=None, **kwargs):
+ r"""Run a collection of tests using the specified method.
+
+ The name is used to determine some optional arguments."""
+ tests = get_tests(collection, smoothness=smoothness)
+ self.run_tests(tests, method, name, known_fail=known_fail, **kwargs)
+
+
+class TestBracketMethods(TestScalarRootFinders):
+ @pytest.mark.parametrize('method', bracket_methods)
+ @pytest.mark.parametrize('function', tstutils_functions)
+ def test_basic_root_scalar(self, method, function):
+ # Tests bracketing root finders called via `root_scalar` on a small
+ # set of simple problems, each of which has a root at `x=1`. Checks for
+ # converged status and that the root was found.
+ a, b = .5, sqrt(3)
+
+ r = root_scalar(function, method=method.__name__, bracket=[a, b], x0=a,
+ xtol=self.xtol, rtol=self.rtol)
+ assert r.converged
+ assert_allclose(r.root, 1.0, atol=self.xtol, rtol=self.rtol)
+ assert r.method == method.__name__
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ @pytest.mark.parametrize('function', tstutils_functions)
+ def test_basic_individual(self, method, function):
+ # Tests individual bracketing root finders on a small set of simple
+ # problems, each of which has a root at `x=1`. Checks for converged
+ # status and that the root was found.
+ a, b = .5, sqrt(3)
+ root, r = method(function, a, b, xtol=self.xtol, rtol=self.rtol,
+ full_output=True)
+
+ assert r.converged
+ assert_allclose(root, 1.0, atol=self.xtol, rtol=self.rtol)
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ @pytest.mark.parametrize('function', tstutils_functions)
+ def test_bracket_is_array(self, method, function):
+ # Test bracketing root finders called via `root_scalar` on a small set
+ # of simple problems, each of which has a root at `x=1`. Check that
+ # passing `bracket` as a `ndarray` is accepted and leads to finding the
+ # correct root.
+ a, b = .5, sqrt(3)
+ r = root_scalar(function, method=method.__name__,
+ bracket=np.array([a, b]), x0=a, xtol=self.xtol,
+ rtol=self.rtol)
+ assert r.converged
+ assert_allclose(r.root, 1.0, atol=self.xtol, rtol=self.rtol)
+ assert r.method == method.__name__
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ def test_aps_collection(self, method):
+ self.run_collection('aps', method, method.__name__, smoothness=1)
+
+ @pytest.mark.parametrize('method', [zeros.bisect, zeros.ridder,
+ zeros.toms748])
+ def test_chandrupatla_collection(self, method):
+ self.run_collection('chandrupatla', method, method.__name__)
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ def test_lru_cached_individual(self, method):
+ # check that https://github.com/scipy/scipy/issues/10846 is fixed
+ # (`root_scalar` failed when passed a function that was `@lru_cache`d)
+ a, b = -1, 1
+ root, r = method(f_lrucached, a, b, full_output=True)
+ assert r.converged
+ assert_allclose(root, 0)
+
+ def test_gh_22934(self):
+ with pytest.raises(ValueError, match="maxiter must be >= 0"):
+ zeros.brentq(lambda x: x**2 - 1, -2, 0, maxiter=-1)
+
+
+class TestNewton(TestScalarRootFinders):
+ def test_newton_collections(self):
+ known_fail = ['aps.13.00']
+ known_fail += ['aps.12.05', 'aps.12.17'] # fails under Windows Py27
+ for collection in ['aps', 'complex']:
+ self.run_collection(collection, zeros.newton, 'newton',
+ smoothness=2, known_fail=known_fail)
+
+ def test_halley_collections(self):
+ known_fail = ['aps.12.06', 'aps.12.07', 'aps.12.08', 'aps.12.09',
+ 'aps.12.10', 'aps.12.11', 'aps.12.12', 'aps.12.13',
+ 'aps.12.14', 'aps.12.15', 'aps.12.16', 'aps.12.17',
+ 'aps.12.18', 'aps.13.00']
+ for collection in ['aps', 'complex']:
+ self.run_collection(collection, zeros.newton, 'halley',
+ smoothness=2, known_fail=known_fail)
+
+ def test_newton(self):
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ x = zeros.newton(f, 3, tol=1e-6)
+ assert_allclose(f(x), 0, atol=1e-6)
+ x = zeros.newton(f, 3, x1=5, tol=1e-6) # secant, x0 and x1
+ assert_allclose(f(x), 0, atol=1e-6)
+ x = zeros.newton(f, 3, fprime=f_1, tol=1e-6) # newton
+ assert_allclose(f(x), 0, atol=1e-6)
+ x = zeros.newton(f, 3, fprime=f_1, fprime2=f_2, tol=1e-6) # halley
+ assert_allclose(f(x), 0, atol=1e-6)
+
+ def test_newton_by_name(self):
+ r"""Invoke newton through root_scalar()"""
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='newton', x0=3, fprime=f_1, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='newton', x0=3, xtol=1e-6) # without f'
+ assert_allclose(f(r.root), 0, atol=1e-6)
+
+ def test_secant_by_name(self):
+ r"""Invoke secant through root_scalar()"""
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='secant', x0=3, x1=2, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+ r = root_scalar(f, method='secant', x0=3, x1=5, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='secant', x0=3, xtol=1e-6) # without x1
+ assert_allclose(f(r.root), 0, atol=1e-6)
+
+ def test_halley_by_name(self):
+ r"""Invoke halley through root_scalar()"""
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='halley', x0=3,
+ fprime=f_1, fprime2=f_2, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+
+ def test_root_scalar_fail(self):
+ message = 'fprime2 must be specified for halley'
+ with pytest.raises(ValueError, match=message):
+ root_scalar(f1, method='halley', fprime=f1_1, x0=3, xtol=1e-6) # no fprime2
+ message = 'fprime must be specified for halley'
+ with pytest.raises(ValueError, match=message):
+ root_scalar(f1, method='halley', fprime2=f1_2, x0=3, xtol=1e-6) # no fprime
+
+ def test_array_newton(self):
+ """test newton with array"""
+
+ def f1(x, *a):
+ b = a[0] + x * a[3]
+ return a[1] - a[2] * (np.exp(b / a[5]) - 1.0) - b / a[4] - x
+
+ def f1_1(x, *a):
+ b = a[3] / a[5]
+ return -a[2] * np.exp(a[0] / a[5] + x * b) * b - a[3] / a[4] - 1
+
+ def f1_2(x, *a):
+ b = a[3] / a[5]
+ return -a[2] * np.exp(a[0] / a[5] + x * b) * b**2
+
+ a0 = np.array([
+ 5.32725221, 5.48673747, 5.49539973,
+ 5.36387202, 4.80237316, 1.43764452,
+ 5.23063958, 5.46094772, 5.50512718,
+ 5.42046290
+ ])
+ a1 = (np.sin(range(10)) + 1.0) * 7.0
+ args = (a0, a1, 1e-09, 0.004, 10, 0.27456)
+ x0 = [7.0] * 10
+ x = zeros.newton(f1, x0, f1_1, args)
+ x_expected = (
+ 6.17264965, 11.7702805, 12.2219954,
+ 7.11017681, 1.18151293, 0.143707955,
+ 4.31928228, 10.5419107, 12.7552490,
+ 8.91225749
+ )
+ assert_allclose(x, x_expected)
+ # test halley's
+ x = zeros.newton(f1, x0, f1_1, args, fprime2=f1_2)
+ assert_allclose(x, x_expected)
+ # test secant
+ x = zeros.newton(f1, x0, args=args)
+ assert_allclose(x, x_expected)
+
+ def test_array_newton_complex(self):
+ def f(x):
+ return x + 1+1j
+
+ def fprime(x):
+ return 1.0
+
+ t = np.full(4, 1j)
+ x = zeros.newton(f, t, fprime=fprime)
+ assert_allclose(f(x), 0.)
+
+ # should work even if x0 is not complex
+ t = np.ones(4)
+ x = zeros.newton(f, t, fprime=fprime)
+ assert_allclose(f(x), 0.)
+
+ x = zeros.newton(f, t)
+ assert_allclose(f(x), 0.)
+
+ def test_array_secant_active_zero_der(self):
+ """test secant doesn't continue to iterate zero derivatives"""
+ x = zeros.newton(lambda x, *a: x*x - a[0], x0=[4.123, 5],
+ args=[np.array([17, 25])])
+ assert_allclose(x, (4.123105625617661, 5.0))
+
+ def test_array_newton_integers(self):
+ # test secant with float
+ x = zeros.newton(lambda y, z: z - y ** 2, [4.0] * 2,
+ args=([15.0, 17.0],))
+ assert_allclose(x, (3.872983346207417, 4.123105625617661))
+ # test integer becomes float
+ x = zeros.newton(lambda y, z: z - y ** 2, [4] * 2, args=([15, 17],))
+ assert_allclose(x, (3.872983346207417, 4.123105625617661))
+
+ def test_array_newton_zero_der_failures(self):
+ # test derivative zero warning
+ with pytest.warns(RuntimeWarning):
+ zeros.newton(lambda y: y**2 - 2, [0., 0.], lambda y: 2 * y)
+ # test failures and zero_der
+ with pytest.warns(RuntimeWarning):
+ results = zeros.newton(lambda y: y**2 - 2, [0., 0.],
+ lambda y: 2*y, full_output=True)
+ assert_allclose(results.root, 0)
+ assert results.zero_der.all()
+ assert not results.converged.any()
+
+ def test_newton_combined(self):
+ def f1(x):
+ return x ** 2 - 2 * x - 1
+ def f1_1(x):
+ return 2 * x - 2
+ def f1_2(x):
+ return 2.0 + 0 * x
+
+ def f1_and_p_and_pp(x):
+ return x**2 - 2*x-1, 2*x-2, 2.0
+
+ sol0 = root_scalar(f1, method='newton', x0=3, fprime=f1_1)
+ sol = root_scalar(f1_and_p_and_pp, method='newton', x0=3, fprime=True)
+ assert_allclose(sol0.root, sol.root, atol=1e-8)
+ assert_equal(2*sol.function_calls, sol0.function_calls)
+
+ sol0 = root_scalar(f1, method='halley', x0=3, fprime=f1_1, fprime2=f1_2)
+ sol = root_scalar(f1_and_p_and_pp, method='halley', x0=3, fprime2=True)
+ assert_allclose(sol0.root, sol.root, atol=1e-8)
+ assert_equal(3*sol.function_calls, sol0.function_calls)
+
+ def test_newton_full_output(self, capsys):
+ # Test the full_output capability, both when converging and not.
+ # Use simple polynomials, to avoid hitting platform dependencies
+ # (e.g., exp & trig) in number of iterations
+
+ x0 = 3
+ expected_counts = [(6, 7), (5, 10), (3, 9)]
+
+ for derivs in range(3):
+ kwargs = {'tol': 1e-6, 'full_output': True, }
+ for k, v in [['fprime', f1_1], ['fprime2', f1_2]][:derivs]:
+ kwargs[k] = v
+
+ x, r = zeros.newton(f1, x0, disp=False, **kwargs)
+ assert_(r.converged)
+ assert_equal(x, r.root)
+ assert_equal((r.iterations, r.function_calls), expected_counts[derivs])
+ if derivs == 0:
+ assert r.function_calls <= r.iterations + 1
+ else:
+ assert_equal(r.function_calls, (derivs + 1) * r.iterations)
+
+ # Now repeat, allowing one fewer iteration to force convergence failure
+ iters = r.iterations - 1
+ x, r = zeros.newton(f1, x0, maxiter=iters, disp=False, **kwargs)
+ assert_(not r.converged)
+ assert_equal(x, r.root)
+ assert_equal(r.iterations, iters)
+
+ if derivs == 1:
+ # Check that the correct Exception is raised and
+ # validate the start of the message.
+ msg = f'Failed to converge after {iters} iterations, value is .*'
+ with pytest.raises(RuntimeError, match=msg):
+ x, r = zeros.newton(f1, x0, maxiter=iters, disp=True, **kwargs)
+
+ def test_deriv_zero_warning(self):
+ def func(x):
+ return x ** 2 - 2.0
+ def dfunc(x):
+ return 2 * x
+ with pytest.warns(RuntimeWarning):
+ zeros.newton(func, 0.0, dfunc, disp=False)
+ with pytest.raises(RuntimeError, match='Derivative was zero'):
+ zeros.newton(func, 0.0, dfunc)
+
+ def test_newton_does_not_modify_x0(self):
+ # https://github.com/scipy/scipy/issues/9964
+ x0 = np.array([0.1, 3])
+ x0_copy = x0.copy() # Copy to test for equality.
+ newton(np.sin, x0, np.cos)
+ assert_array_equal(x0, x0_copy)
+
+ def test_gh17570_defaults(self):
+ # Previously, when fprime was not specified, root_scalar would default
+ # to secant. When x1 was not specified, secant failed.
+ # Check that without fprime, the default is secant if x1 is specified
+ # and newton otherwise.
+ # Also confirm that `x` is always a scalar (gh-21148)
+ def f(x):
+ assert np.isscalar(x)
+ return f1(x)
+
+ res_newton_default = root_scalar(f, method='newton', x0=3, xtol=1e-6)
+ res_secant_default = root_scalar(f, method='secant', x0=3, x1=2,
+ xtol=1e-6)
+ # `newton` uses the secant method when `x1` and `x2` are specified
+ res_secant = newton(f, x0=3, x1=2, tol=1e-6, full_output=True)[1]
+
+ # all three found a root
+ assert_allclose(f(res_newton_default.root), 0, atol=1e-6)
+ assert res_newton_default.root.shape == tuple()
+ assert_allclose(f(res_secant_default.root), 0, atol=1e-6)
+ assert res_secant_default.root.shape == tuple()
+ assert_allclose(f(res_secant.root), 0, atol=1e-6)
+ assert res_secant.root.shape == tuple()
+
+ # Defaults are correct
+ assert (res_secant_default.root
+ == res_secant.root
+ != res_newton_default.iterations)
+ assert (res_secant_default.iterations
+ == res_secant_default.function_calls - 1 # true for secant
+ == res_secant.iterations
+ != res_newton_default.iterations
+ == res_newton_default.function_calls/2) # newton 2-point diff
+
+ @pytest.mark.parametrize('kwargs', [dict(), {'method': 'newton'}])
+ def test_args_gh19090(self, kwargs):
+ def f(x, a, b):
+ assert a == 3
+ assert b == 1
+ return (x ** a - b)
+
+ res = optimize.root_scalar(f, x0=3, args=(3, 1), **kwargs)
+ assert res.converged
+ assert_allclose(res.root, 1)
+
+ @pytest.mark.parametrize('method', ['secant', 'newton'])
+ def test_int_x0_gh19280(self, method):
+ # Originally, `newton` ensured that only floats were passed to the
+ # callable. This was inadvertently changed by gh-17669. Check that
+ # it has been changed back.
+ def f(x):
+ # an integer raised to a negative integer power would fail
+ return x**-2 - 2
+
+ res = optimize.root_scalar(f, x0=1, method=method)
+ assert res.converged
+ assert_allclose(abs(res.root), 2**-0.5)
+ assert res.root.dtype == np.dtype(np.float64)
+
+ def test_newton_special_parameters(self):
+ # give zeros.newton() some strange parameters
+ # and check whether an exception appears
+ with pytest.raises(ValueError, match="tol too small"):
+ zeros.newton(f1, 3, tol=-1e-6)
+
+ with pytest.raises(ValueError, match="maxiter must be greater than 0"):
+ zeros.newton(f1, 3, tol=1e-6, maxiter=-50)
+
+ with pytest.raises(ValueError, match="x1 and x0 must be different" ):
+ zeros.newton(f1, 3, x1=3)
+
+
+def test_gh_5555():
+ root = 0.1
+
+ def f(x):
+ return x - root
+
+ methods = [zeros.bisect, zeros.ridder]
+ xtol = rtol = TOL
+ for method in methods:
+ res = method(f, -1e8, 1e7, xtol=xtol, rtol=rtol)
+ assert_allclose(root, res, atol=xtol, rtol=rtol,
+ err_msg=f'method {method.__name__}')
+
+
+def test_gh_5557():
+ # Show that without the changes in 5557 brentq and brenth might
+ # only achieve a tolerance of 2*(xtol + rtol*|res|).
+
+ # f linearly interpolates (0, -0.1), (0.5, -0.1), and (1,
+ # 0.4). The important parts are that |f(0)| < |f(1)| (so that
+ # brent takes 0 as the initial guess), |f(0)| < atol (so that
+ # brent accepts 0 as the root), and that the exact root of f lies
+ # more than atol away from 0 (so that brent doesn't achieve the
+ # desired tolerance).
+ def f(x):
+ if x < 0.5:
+ return -0.1
+ else:
+ return x - 0.6
+
+ atol = 0.51
+ rtol = 4 * _FLOAT_EPS
+ methods = [zeros.brentq, zeros.brenth]
+ for method in methods:
+ res = method(f, 0, 1, xtol=atol, rtol=rtol)
+ assert_allclose(0.6, res, atol=atol, rtol=rtol)
+
+
+def test_brent_underflow_in_root_bracketing():
+ # Testing if an interval [a,b] brackets a zero of a function
+ # by checking f(a)*f(b) < 0 is not reliable when the product
+ # underflows/overflows. (reported in issue# 13737)
+
+ underflow_scenario = (-450.0, -350.0, -400.0)
+ overflow_scenario = (350.0, 450.0, 400.0)
+
+ for a, b, root in [underflow_scenario, overflow_scenario]:
+ c = np.exp(root)
+ for method in [zeros.brenth, zeros.brentq]:
+ res = method(lambda x: np.exp(x)-c, a, b)
+ assert_allclose(root, res)
+
+
+class TestRootResults:
+ r = zeros.RootResults(root=1.0, iterations=44, function_calls=46, flag=0,
+ method="newton")
+
+ def test_repr(self):
+ expected_repr = (" converged: True\n flag: converged"
+ "\n function_calls: 46\n iterations: 44\n"
+ " root: 1.0\n method: newton")
+ assert_equal(repr(self.r), expected_repr)
+
+ def test_type(self):
+ assert isinstance(self.r, OptimizeResult)
+
+
+def test_complex_halley():
+ """Test Halley's works with complex roots"""
+ def f(x, *a):
+ return a[0] * x**2 + a[1] * x + a[2]
+
+ def f_1(x, *a):
+ return 2 * a[0] * x + a[1]
+
+ def f_2(x, *a):
+ retval = 2 * a[0]
+ try:
+ size = len(x)
+ except TypeError:
+ return retval
+ else:
+ return [retval] * size
+
+ z = complex(1.0, 2.0)
+ coeffs = (2.0, 3.0, 4.0)
+ y = zeros.newton(f, z, args=coeffs, fprime=f_1, fprime2=f_2, tol=1e-6)
+ # (-0.75000000000000078+1.1989578808281789j)
+ assert_allclose(f(y, *coeffs), 0, atol=1e-6)
+ z = [z] * 10
+ coeffs = (2.0, 3.0, 4.0)
+ y = zeros.newton(f, z, args=coeffs, fprime=f_1, fprime2=f_2, tol=1e-6)
+ assert_allclose(f(y, *coeffs), 0, atol=1e-6)
+
+
+def test_zero_der_nz_dp(capsys):
+ """Test secant method with a non-zero dp, but an infinite newton step"""
+ # pick a symmetrical functions and choose a point on the side that with dx
+ # makes a secant that is a flat line with zero slope, EG: f = (x - 100)**2,
+ # which has a root at x = 100 and is symmetrical around the line x = 100
+ # we have to pick a really big number so that it is consistently true
+ # now find a point on each side so that the secant has a zero slope
+ dx = np.finfo(float).eps ** 0.33
+ # 100 - p0 = p1 - 100 = p0 * (1 + dx) + dx - 100
+ # -> 200 = p0 * (2 + dx) + dx
+ p0 = (200.0 - dx) / (2.0 + dx)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "RMS of", RuntimeWarning)
+ x = zeros.newton(lambda y: (y - 100.0)**2, x0=[p0] * 10)
+ assert_allclose(x, [100] * 10)
+ # test scalar cases too
+ p0 = (2.0 - 1e-4) / (2.0 + 1e-4)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Tolerance of", RuntimeWarning)
+ x = zeros.newton(lambda y: (y - 1.0) ** 2, x0=p0, disp=False)
+ assert_allclose(x, 1)
+ with pytest.raises(RuntimeError, match='Tolerance of'):
+ x = zeros.newton(lambda y: (y - 1.0) ** 2, x0=p0, disp=True)
+ p0 = (-2.0 + 1e-4) / (2.0 + 1e-4)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Tolerance of", RuntimeWarning)
+ x = zeros.newton(lambda y: (y + 1.0) ** 2, x0=p0, disp=False)
+ assert_allclose(x, -1)
+ with pytest.raises(RuntimeError, match='Tolerance of'):
+ x = zeros.newton(lambda y: (y + 1.0) ** 2, x0=p0, disp=True)
+
+
+def test_array_newton_failures():
+ """Test that array newton fails as expected"""
+ # p = 0.68 # [MPa]
+ # dp = -0.068 * 1e6 # [Pa]
+ # T = 323 # [K]
+ diameter = 0.10 # [m]
+ # L = 100 # [m]
+ roughness = 0.00015 # [m]
+ rho = 988.1 # [kg/m**3]
+ mu = 5.4790e-04 # [Pa*s]
+ u = 2.488 # [m/s]
+ reynolds_number = rho * u * diameter / mu # Reynolds number
+
+ def colebrook_eqn(darcy_friction, re, dia):
+ return (1 / np.sqrt(darcy_friction) +
+ 2 * np.log10(roughness / 3.7 / dia +
+ 2.51 / re / np.sqrt(darcy_friction)))
+
+ # only some failures
+ with pytest.warns(RuntimeWarning):
+ result = zeros.newton(
+ colebrook_eqn, x0=[0.01, 0.2, 0.02223, 0.3], maxiter=2,
+ args=[reynolds_number, diameter], full_output=True
+ )
+ assert not result.converged.all()
+ # they all fail
+ with pytest.raises(RuntimeError):
+ result = zeros.newton(
+ colebrook_eqn, x0=[0.01] * 2, maxiter=2,
+ args=[reynolds_number, diameter], full_output=True
+ )
+
+
+# this test should **not** raise a RuntimeWarning
+def test_gh8904_zeroder_at_root_fails():
+ """Test that Newton or Halley don't warn if zero derivative at root"""
+
+ # a function that has a zero derivative at it's root
+ def f_zeroder_root(x):
+ return x**3 - x**2
+
+ # should work with secant
+ r = zeros.newton(f_zeroder_root, x0=0)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # test again with array
+ r = zeros.newton(f_zeroder_root, x0=[0]*10)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+
+ # 1st derivative
+ def fder(x):
+ return 3 * x**2 - 2 * x
+
+ # 2nd derivative
+ def fder2(x):
+ return 6*x - 2
+
+ # should work with newton and halley
+ r = zeros.newton(f_zeroder_root, x0=0, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ r = zeros.newton(f_zeroder_root, x0=0, fprime=fder,
+ fprime2=fder2)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # test again with array
+ r = zeros.newton(f_zeroder_root, x0=[0]*10, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ r = zeros.newton(f_zeroder_root, x0=[0]*10, fprime=fder,
+ fprime2=fder2)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+
+ # also test that if a root is found we do not raise RuntimeWarning even if
+ # the derivative is zero, EG: at x = 0.5, then fval = -0.125 and
+ # fder = -0.25 so the next guess is 0.5 - (-0.125/-0.5) = 0 which is the
+ # root, but if the solver continued with that guess, then it will calculate
+ # a zero derivative, so it should return the root w/o RuntimeWarning
+ r = zeros.newton(f_zeroder_root, x0=0.5, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # test again with array
+ r = zeros.newton(f_zeroder_root, x0=[0.5]*10, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # doesn't apply to halley
+
+
+def test_gh_8881():
+ r"""Test that Halley's method realizes that the 2nd order adjustment
+ is too big and drops off to the 1st order adjustment."""
+ n = 9
+
+ def f(x):
+ return power(x, 1.0/n) - power(n, 1.0/n)
+
+ def fp(x):
+ return power(x, (1.0-n)/n)/n
+
+ def fpp(x):
+ return power(x, (1.0-2*n)/n) * (1.0/n) * (1.0-n)/n
+
+ x0 = 0.1
+ # The root is at x=9.
+ # The function has positive slope, x0 < root.
+ # Newton succeeds in 8 iterations
+ rt, r = newton(f, x0, fprime=fp, full_output=True)
+ assert r.converged
+ # Before the Issue 8881/PR 8882, halley would send x in the wrong direction.
+ # Check that it now succeeds.
+ rt, r = newton(f, x0, fprime=fp, fprime2=fpp, full_output=True)
+ assert r.converged
+
+
+def test_gh_9608_preserve_array_shape():
+ """
+ Test that shape is preserved for array inputs even if fprime or fprime2 is
+ scalar
+ """
+ def f(x):
+ return x**2
+
+ def fp(x):
+ return 2 * x
+
+ def fpp(x):
+ return 2
+
+ x0 = np.array([-2], dtype=np.float32)
+ rt, r = newton(f, x0, fprime=fp, fprime2=fpp, full_output=True)
+ assert r.converged
+
+ x0_array = np.array([-2, -3], dtype=np.float32)
+ # This next invocation should fail
+ with pytest.raises(IndexError):
+ result = zeros.newton(
+ f, x0_array, fprime=fp, fprime2=fpp, full_output=True
+ )
+
+ def fpp_array(x):
+ return np.full(np.shape(x), 2, dtype=np.float32)
+
+ result = zeros.newton(
+ f, x0_array, fprime=fp, fprime2=fpp_array, full_output=True
+ )
+ assert result.converged.all()
+
+
+@pytest.mark.parametrize(
+ "maximum_iterations,flag_expected",
+ [(10, zeros.CONVERR), (100, zeros.CONVERGED)])
+def test_gh9254_flag_if_maxiter_exceeded(maximum_iterations, flag_expected):
+ """
+ Test that if the maximum iterations is exceeded that the flag is not
+ converged.
+ """
+ result = zeros.brentq(
+ lambda x: ((1.2*x - 2.3)*x + 3.4)*x - 4.5,
+ -30, 30, (), 1e-6, 1e-6, maximum_iterations,
+ full_output=True, disp=False)
+ assert result[1].flag == flag_expected
+ if flag_expected == zeros.CONVERR:
+ # didn't converge because exceeded maximum iterations
+ assert result[1].iterations == maximum_iterations
+ elif flag_expected == zeros.CONVERGED:
+ # converged before maximum iterations
+ assert result[1].iterations < maximum_iterations
+
+
+def test_gh9551_raise_error_if_disp_true():
+ """Test that if disp is true then zero derivative raises RuntimeError"""
+
+ def f(x):
+ return x*x + 1
+
+ def f_p(x):
+ return 2*x
+
+ with pytest.warns(RuntimeWarning):
+ zeros.newton(f, 1.0, f_p, disp=False)
+ with pytest.raises(
+ RuntimeError,
+ match=r'^Derivative was zero\. Failed to converge after \d+ iterations, '
+ r'value is [+-]?\d*\.\d+\.$'):
+ zeros.newton(f, 1.0, f_p)
+ root = zeros.newton(f, complex(10.0, 10.0), f_p)
+ assert_allclose(root, complex(0.0, 1.0))
+
+
+@pytest.mark.parametrize('solver_name',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+def test_gh3089_8394(solver_name):
+ # gh-3089 and gh-8394 reported that bracketing solvers returned incorrect
+ # results when they encountered NaNs. Check that this is resolved.
+ def f(x):
+ return np.nan
+
+ solver = getattr(zeros, solver_name)
+ with pytest.raises(ValueError, match="The function value at x..."):
+ solver(f, 0, 1)
+
+
+@pytest.mark.parametrize('method',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+def test_gh18171(method):
+ # gh-3089 and gh-8394 reported that bracketing solvers returned incorrect
+ # results when they encountered NaNs. Check that `root_scalar` returns
+ # normally but indicates that convergence was unsuccessful. See gh-18171.
+ def f(x):
+ f._count += 1
+ return np.nan
+ f._count = 0
+
+ res = root_scalar(f, bracket=(0, 1), method=method)
+ assert res.converged is False
+ assert res.flag.startswith("The function value at x")
+ assert res.function_calls == f._count
+ assert str(res.root) in res.flag
+
+
+@pytest.mark.parametrize('solver_name',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+@pytest.mark.parametrize('rs_interface', [True, False])
+def test_function_calls(solver_name, rs_interface):
+ # There do not appear to be checks that the bracketing solvers report the
+ # correct number of function evaluations. Check that this is the case.
+ solver = ((lambda f, a, b, **kwargs: root_scalar(f, bracket=(a, b)))
+ if rs_interface else getattr(zeros, solver_name))
+
+ def f(x):
+ f.calls += 1
+ return x**2 - 1
+ f.calls = 0
+
+ res = solver(f, 0, 10, full_output=True)
+
+ if rs_interface:
+ assert res.function_calls == f.calls
+ else:
+ assert res[1].function_calls == f.calls
+
+
+def test_gh_14486_converged_false():
+ """Test that zero slope with secant method results in a converged=False"""
+ def lhs(x):
+ return x * np.exp(-x*x) - 0.07
+
+ with pytest.warns(RuntimeWarning, match='Tolerance of'):
+ res = root_scalar(lhs, method='secant', x0=-0.15, x1=1.0)
+ assert not res.converged
+ assert res.flag == 'convergence error'
+
+ with pytest.warns(RuntimeWarning, match='Tolerance of'):
+ res = newton(lhs, x0=-0.15, x1=1.0, disp=False, full_output=True)[1]
+ assert not res.converged
+ assert res.flag == 'convergence error'
+
+
+@pytest.mark.parametrize('solver_name',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+@pytest.mark.parametrize('rs_interface', [True, False])
+def test_gh5584(solver_name, rs_interface):
+ # gh-5584 reported that an underflow can cause sign checks in the algorithm
+ # to fail. Check that this is resolved.
+ solver = ((lambda f, a, b, **kwargs: root_scalar(f, bracket=(a, b)))
+ if rs_interface else getattr(zeros, solver_name))
+
+ def f(x):
+ return 1e-200*x
+
+ # Report failure when signs are the same
+ with pytest.raises(ValueError, match='...must have different signs'):
+ solver(f, -0.5, -0.4, full_output=True)
+
+ # Solve successfully when signs are different
+ res = solver(f, -0.5, 0.4, full_output=True)
+ res = res if rs_interface else res[1]
+ assert res.converged
+ assert_allclose(res.root, 0, atol=1e-8)
+
+ # Solve successfully when one side is negative zero
+ res = solver(f, -0.5, float('-0.0'), full_output=True)
+ res = res if rs_interface else res[1]
+ assert res.converged
+ assert_allclose(res.root, 0, atol=1e-8)
+
+
+def test_gh13407():
+ # gh-13407 reported that the message produced by `scipy.optimize.toms748`
+ # when `rtol < eps` is incorrect, and also that toms748 is unusual in
+ # accepting `rtol` as low as eps while other solvers raise at 4*eps. Check
+ # that the error message has been corrected and that `rtol=eps` can produce
+ # a lower function value than `rtol=4*eps`.
+ def f(x):
+ return x**3 - 2*x - 5
+
+ xtol = 1e-300
+ eps = np.finfo(float).eps
+ x1 = zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=1*eps)
+ f1 = f(x1)
+ x4 = zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=4*eps)
+ f4 = f(x4)
+ assert f1 < f4
+
+ # using old-style syntax to get exactly the same message
+ message = fr"rtol too small \({eps/2:g} < {eps:g}\)"
+ with pytest.raises(ValueError, match=message):
+ zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=eps/2)
+
+
+def test_newton_complex_gh10103():
+ # gh-10103 reported a problem when `newton` is pass a Python complex x0,
+ # no `fprime` (secant method), and no `x1` (`x1` must be constructed).
+ # Check that this is resolved.
+ def f(z):
+ return z - 1
+ res = newton(f, 1+1j)
+ assert_allclose(res, 1, atol=1e-12)
+
+ res = root_scalar(f, x0=1+1j, x1=2+1.5j, method='secant')
+ assert_allclose(res.root, 1, atol=1e-12)
+
+
+@pytest.mark.parametrize('method', all_methods)
+def test_maxiter_int_check_gh10236(method):
+ # gh-10236 reported that the error message when `maxiter` is not an integer
+ # was difficult to interpret. Check that this was resolved (by gh-10907).
+ message = "'float' object cannot be interpreted as an integer"
+ with pytest.raises(TypeError, match=message):
+ method(f1, 0.0, 1.0, maxiter=72.45)
+
+@pytest.mark.parametrize("method", [zeros.bisect, zeros.ridder,
+ zeros.brentq, zeros.brenth])
+def test_bisect_special_parameter(method):
+ # give some zeros method strange parameters
+ # and check whether an exception appears
+ root = 0.1
+ args = (1e-09, 0.004, 10, 0.27456)
+ rtolbad = 4 * np.finfo(float).eps / 2
+
+ def f(x):
+ return x - root
+
+ with pytest.raises(ValueError, match="xtol too small"):
+ method(f, -1e8, 1e7, args=args, xtol=-1e-6, rtol=TOL)
+ with pytest.raises(ValueError, match="rtol too small"):
+ method(f, -1e8, 1e7, args=args, xtol=1e-6, rtol=rtolbad)
+
+class TestRidderUnderflow:
+ def test_gh_issue_underflow(self):
+ # Regression test for underflow in Ridder's method.
+ # Previously, intermediate calculations (fm*fm) would underflow
+ # to zero before the ratio converged, causing a Runtime Error.
+
+ def f(x): return x**5
+
+ # Before the fix, this raised a RuntimeError.
+ root, result = optimize.ridder(
+ f, -1, 5,
+ xtol=1e-300,
+ full_output=True,
+ maxiter=10000
+ )
+
+ assert result.converged
+ assert abs(root) < 1e-10 # Ensuring zero is found
+
+ def test_early_exit_funcalls(self):
+ # Test case for when midpoint is reached early (fm == 0).
+ nfev = 0
+ def f(x):
+ nonlocal nfev
+ nfev += 1
+ return x
+
+ # Root == 0, the midpoint of [-1, 1].
+ # Calls: f(-1), f(1) [init], then f(0) [iter 1] -> Exit.
+ # Total = 3 calls.
+ root, result = optimize.ridder(
+ f, -1, 1,
+ full_output=True
+ )
+
+ assert result.converged
+ assert root == 0.0
+ assert result.function_calls == nfev
+ assert result.function_calls == 3
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/tnc.py b/.venv/lib/python3.12/site-packages/scipy/optimize/tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0f66058bbcc501eb1303eb3075cb55705b93192
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/tnc.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'fmin_tnc',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="tnc",
+ private_modules=["_tnc"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/optimize/zeros.py b/.venv/lib/python3.12/site-packages/scipy/optimize/zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..907d49d37fc1e7476e81a25dbbc0d3910cbbe004
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/optimize/zeros.py
@@ -0,0 +1,26 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'RootResults',
+ 'bisect',
+ 'brenth',
+ 'brentq',
+ 'newton',
+ 'ridder',
+ 'toms748',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="zeros",
+ private_modules=["_zeros_py"], all=__all__,
+ attribute=name)
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/__init__.py b/.venv/lib/python3.12/site-packages/scipy/signal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0babe2989bff7144b87329b1d12962edb351b897
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/__init__.py
@@ -0,0 +1,322 @@
+"""
+=======================================
+Signal processing (:mod:`scipy.signal`)
+=======================================
+
+.. toctree::
+ :hidden:
+
+ signal.windows
+
+Convolution
+===========
+
+.. autosummary::
+ :toctree: generated/
+
+ convolve -- N-D convolution.
+ correlate -- N-D correlation.
+ fftconvolve -- N-D convolution using the FFT.
+ oaconvolve -- N-D convolution using the overlap-add method.
+ convolve2d -- 2-D convolution (more options).
+ correlate2d -- 2-D correlation (more options).
+ sepfir2d -- Convolve with a 2-D separable FIR filter.
+ choose_conv_method -- Chooses faster of FFT and direct convolution methods.
+ correlation_lags -- Determines lag indices for 1D cross-correlation.
+
+B-splines
+=========
+
+.. autosummary::
+ :toctree: generated/
+
+ gauss_spline -- Gaussian approximation to the B-spline basis function.
+ cspline1d -- Coefficients for 1-D cubic (3rd order) B-spline.
+ qspline1d -- Coefficients for 1-D quadratic (2nd order) B-spline.
+ cspline2d -- Coefficients for 2-D cubic (3rd order) B-spline.
+ qspline2d -- Coefficients for 2-D quadratic (2nd order) B-spline.
+ cspline1d_eval -- Evaluate a cubic spline at the given points.
+ qspline1d_eval -- Evaluate a quadratic spline at the given points.
+ spline_filter -- Smoothing spline (cubic) filtering of a rank-2 array.
+ whittaker_henderson -- Whittaker-Henderson smoothing/graduation
+
+Filtering
+=========
+
+.. autosummary::
+ :toctree: generated/
+
+ order_filter -- N-D order filter.
+ medfilt -- N-D median filter.
+ medfilt2d -- 2-D median filter (faster).
+ wiener -- N-D Wiener filter.
+
+ symiirorder1 -- 2nd-order IIR filter (cascade of first-order systems).
+ symiirorder2 -- 4th-order IIR filter (cascade of second-order systems).
+ lfilter -- 1-D FIR and IIR digital linear filtering.
+ lfiltic -- Construct initial conditions for `lfilter`.
+ lfilter_zi -- Compute an initial state zi for the lfilter function that
+ -- corresponds to the steady state of the step response.
+ filtfilt -- A forward-backward filter.
+ savgol_filter -- Filter a signal using the Savitzky-Golay filter.
+
+ deconvolve -- 1-D deconvolution using lfilter.
+
+ sosfilt -- 1-D IIR digital linear filtering using
+ -- a second-order sections filter representation.
+ sosfilt_zi -- Compute an initial state zi for the sosfilt function that
+ -- corresponds to the steady state of the step response.
+ sosfiltfilt -- A forward-backward filter for second-order sections.
+ hilbert -- Compute 1-D analytic signal, using the Hilbert transform.
+ hilbert2 -- Compute 2-D analytic signal, using the Hilbert transform.
+ envelope -- Compute the envelope of a real- or complex-valued signal.
+
+ decimate -- Downsample a signal.
+ detrend -- Remove linear and/or constant trends from data.
+ resample -- Resample using Fourier method.
+ resample_poly -- Resample using polyphase filtering method.
+ upfirdn -- Upsample, apply FIR filter, downsample.
+
+Filter design
+=============
+
+.. autosummary::
+ :toctree: generated/
+
+ bilinear -- Digital filter from an analog filter using
+ -- the bilinear transform.
+ bilinear_zpk -- Digital filter from an analog filter using
+ -- the bilinear transform.
+ findfreqs -- Find array of frequencies for computing filter response.
+ firls -- FIR filter design using least-squares error minimization.
+ firwin -- Windowed FIR filter design, with frequency response
+ -- defined as pass and stop bands.
+ firwin2 -- Windowed FIR filter design, with arbitrary frequency
+ -- response.
+ firwin_2d -- Windowed FIR filter design, with frequency response for
+ -- 2D using 1D design.
+ freqs -- Analog filter frequency response from TF coefficients.
+ freqs_zpk -- Analog filter frequency response from ZPK coefficients.
+ freqz -- Digital filter frequency response from TF coefficients.
+ sosfreqz -- Digital filter frequency response for SOS format filter (legacy).
+ freqz_sos -- Digital filter frequency response for SOS format filter.
+ freqz_zpk -- Digital filter frequency response from ZPK coefficients.
+ gammatone -- FIR and IIR gammatone filter design.
+ group_delay -- Digital filter group delay.
+ iirdesign -- IIR filter design given bands and gains.
+ iirfilter -- IIR filter design given order and critical frequencies.
+ kaiser_atten -- Compute the attenuation of a Kaiser FIR filter, given
+ -- the number of taps and the transition width at
+ -- discontinuities in the frequency response.
+ kaiser_beta -- Compute the Kaiser parameter beta, given the desired
+ -- FIR filter attenuation.
+ kaiserord -- Design a Kaiser window to limit ripple and width of
+ -- transition region.
+ minimum_phase -- Convert a linear phase FIR filter to minimum phase.
+ savgol_coeffs -- Compute the FIR filter coefficients for a Savitzky-Golay
+ -- filter.
+ remez -- Optimal FIR filter design.
+
+ unique_roots -- Unique roots and their multiplicities.
+ residue -- Partial fraction expansion of b(s) / a(s).
+ residuez -- Partial fraction expansion of b(z) / a(z).
+ invres -- Inverse partial fraction expansion for analog filter.
+ invresz -- Inverse partial fraction expansion for digital filter.
+ BadCoefficients -- Warning on badly conditioned filter coefficients.
+
+Lower-level filter design functions:
+
+.. autosummary::
+ :toctree: generated/
+
+ abcd_normalize -- Check state-space matrices compatibility and ensure they are 2d.
+ band_stop_obj -- Band Stop Objective Function for order minimization.
+ besselap -- Return (z,p,k) for analog prototype of Bessel filter.
+ buttap -- Return (z,p,k) for analog prototype of Butterworth filter.
+ cheb1ap -- Return (z,p,k) for type I Chebyshev filter.
+ cheb2ap -- Return (z,p,k) for type II Chebyshev filter.
+ ellipap -- Return (z,p,k) for analog prototype of elliptic filter.
+ lp2bp -- Transform a lowpass filter prototype to a bandpass filter.
+ lp2bp_zpk -- Transform a lowpass filter prototype to a bandpass filter.
+ lp2bs -- Transform a lowpass filter prototype to a bandstop filter.
+ lp2bs_zpk -- Transform a lowpass filter prototype to a bandstop filter.
+ lp2hp -- Transform a lowpass filter prototype to a highpass filter.
+ lp2hp_zpk -- Transform a lowpass filter prototype to a highpass filter.
+ lp2lp -- Transform a lowpass filter prototype to a lowpass filter.
+ lp2lp_zpk -- Transform a lowpass filter prototype to a lowpass filter.
+ normalize -- Normalize polynomial representation of a transfer function.
+
+
+
+Matlab-style IIR filter design
+==============================
+
+.. autosummary::
+ :toctree: generated/
+
+ butter -- Butterworth
+ buttord
+ cheby1 -- Chebyshev Type I
+ cheb1ord
+ cheby2 -- Chebyshev Type II
+ cheb2ord
+ ellip -- Elliptic (Cauer)
+ ellipord
+ bessel -- Bessel (no order selection available -- try butterod)
+ iirnotch -- Design second-order IIR notch digital filter.
+ iirpeak -- Design second-order IIR peak (resonant) digital filter.
+ iircomb -- Design IIR comb filter.
+
+Continuous-time linear systems
+==============================
+
+.. autosummary::
+ :toctree: generated/
+
+ lti -- Continuous-time linear time invariant system base class.
+ StateSpace -- Linear time invariant system in state space form.
+ TransferFunction -- Linear time invariant system in transfer function form.
+ ZerosPolesGain -- Linear time invariant system in zeros, poles, gain form.
+ lsim -- Continuous-time simulation of output to linear system.
+ impulse -- Impulse response of linear, time-invariant (LTI) system.
+ step -- Step response of continuous-time LTI system.
+ freqresp -- Frequency response of a continuous-time LTI system.
+ bode -- Bode magnitude and phase data (continuous-time LTI).
+
+Discrete-time linear systems
+============================
+
+.. autosummary::
+ :toctree: generated/
+
+ dlti -- Discrete-time linear time invariant system base class.
+ StateSpace -- Linear time invariant system in state space form.
+ TransferFunction -- Linear time invariant system in transfer function form.
+ ZerosPolesGain -- Linear time invariant system in zeros, poles, gain form.
+ dlsim -- Simulation of output to a discrete-time linear system.
+ dimpulse -- Impulse response of a discrete-time LTI system.
+ dstep -- Step response of a discrete-time LTI system.
+ dfreqresp -- Frequency response of a discrete-time LTI system.
+ dbode -- Bode magnitude and phase data (discrete-time LTI).
+
+LTI representations
+===================
+
+.. autosummary::
+ :toctree: generated/
+
+ tf2zpk -- Transfer function to zero-pole-gain.
+ tf2sos -- Transfer function to second-order sections.
+ tf2ss -- Transfer function to state-space.
+ zpk2tf -- Zero-pole-gain to transfer function.
+ zpk2sos -- Zero-pole-gain to second-order sections.
+ zpk2ss -- Zero-pole-gain to state-space.
+ ss2tf -- State-pace to transfer function.
+ ss2zpk -- State-space to pole-zero-gain.
+ sos2zpk -- Second-order sections to zero-pole-gain.
+ sos2tf -- Second-order sections to transfer function.
+ cont2discrete -- Continuous-time to discrete-time LTI conversion.
+ place_poles -- Pole placement.
+
+Waveforms
+=========
+
+.. autosummary::
+ :toctree: generated/
+
+ chirp -- Frequency swept cosine signal, with several freq functions.
+ gausspulse -- Gaussian modulated sinusoid.
+ max_len_seq -- Maximum length sequence.
+ sawtooth -- Periodic sawtooth.
+ square -- Square wave.
+ sweep_poly -- Frequency swept cosine signal; freq is arbitrary polynomial.
+ unit_impulse -- Discrete unit impulse.
+
+Window functions
+================
+
+For window functions, see the `scipy.signal.windows` namespace.
+
+In the `scipy.signal` namespace, there is a convenience function to
+obtain these windows by name:
+
+.. autosummary::
+ :toctree: generated/
+
+ get_window -- Convenience function for creating various windows.
+
+Peak finding
+============
+
+.. autosummary::
+ :toctree: generated/
+
+ argrelmin -- Calculate the relative minima of data.
+ argrelmax -- Calculate the relative maxima of data.
+ argrelextrema -- Calculate the relative extrema of data.
+ find_peaks -- Find a subset of peaks inside a signal.
+ find_peaks_cwt -- Find peaks in a 1-D array with wavelet transformation.
+ peak_prominences -- Calculate the prominence of each peak in a signal.
+ peak_widths -- Calculate the width of each peak in a signal.
+
+Spectral analysis
+=================
+
+.. autosummary::
+ :toctree: generated/
+
+ periodogram -- Compute a (modified) periodogram.
+ welch -- Compute a periodogram using Welch's method.
+ csd -- Compute the cross spectral density, using Welch's method.
+ coherence -- Compute the magnitude squared coherence, using Welch's method.
+ spectrogram -- Compute the spectrogram (legacy).
+ lombscargle -- Computes the Lomb-Scargle periodogram.
+ vectorstrength -- Computes the vector strength.
+ ShortTimeFFT -- Interface for calculating the \
+ :ref:`Short Time Fourier Transform ` and \
+ its inverse.
+ closest_STFT_dual_window -- Calculate the STFT dual window of a given window \
+ closest to a desired dual window.
+ stft -- Compute the Short Time Fourier Transform (legacy).
+ istft -- Compute the Inverse Short Time Fourier Transform (legacy).
+ check_COLA -- Check the COLA constraint for iSTFT reconstruction (legacy).
+ check_NOLA -- Check the NOLA constraint for iSTFT reconstruction.
+
+Chirp Z-transform and Zoom FFT
+============================================
+
+.. autosummary::
+ :toctree: generated/
+
+ czt - Chirp z-transform convenience function
+ zoom_fft - Zoom FFT convenience function
+ CZT - Chirp z-transform function generator
+ ZoomFFT - Zoom FFT function generator
+ czt_points - Output the z-plane points sampled by a chirp z-transform
+
+The functions are simpler to use than the classes, but are less efficient when
+using the same transform on many arrays of the same length, since they
+repeatedly generate the same chirp signal with every call. In these cases,
+use the classes to create a reusable function instead.
+
+"""
+# bring in the public functionality from private namespaces
+
+# mypy: ignore-errors
+
+from ._support_alternative_backends import *
+from . import _support_alternative_backends
+__all__ = _support_alternative_backends.__all__
+del _support_alternative_backends, _signal_api, _delegators # noqa: F821 # pyrefly:ignore[unbound-name]
+
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+ bsplines, filter_design, fir_filter_design, lti_conversion, ltisys,
+ spectral, signaltools, waveforms, wavelets, spline
+)
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_arraytools.py b/.venv/lib/python3.12/site-packages/scipy/signal/_arraytools.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ce75d8d892a64021da7abc5d149556c22cf983
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_arraytools.py
@@ -0,0 +1,264 @@
+"""
+Functions for acting on a axis of an array.
+"""
+import numpy as np
+
+
+def axis_slice(a, start=None, stop=None, step=None, axis=-1):
+ """Take a slice along axis 'axis' from 'a'.
+
+ Parameters
+ ----------
+ a : numpy.ndarray
+ The array to be sliced.
+ start, stop, step : int or None
+ The slice parameters.
+ axis : int, optional
+ The axis of `a` to be sliced.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import axis_slice
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> axis_slice(a, start=0, stop=1, axis=1)
+ array([[1],
+ [4],
+ [7]])
+ >>> axis_slice(a, start=1, axis=0)
+ array([[4, 5, 6],
+ [7, 8, 9]])
+
+ Notes
+ -----
+ The keyword arguments start, stop and step are used by calling
+ slice(start, stop, step). This implies axis_slice() does not
+ handle its arguments the exactly the same as indexing. To select
+ a single index k, for example, use
+ axis_slice(a, start=k, stop=k+1)
+ In this case, the length of the axis 'axis' in the result will
+ be 1; the trivial dimension is not removed. (Use numpy.squeeze()
+ to remove trivial axes.)
+ """
+ a_slice = [slice(None)] * a.ndim
+ a_slice[axis] = slice(start, stop, step)
+ b = a[tuple(a_slice)]
+ return b
+
+
+def axis_reverse(a, axis=-1):
+ """Reverse the 1-D slices of `a` along axis `axis`.
+
+ Returns axis_slice(a, step=-1, axis=axis).
+ """
+ return axis_slice(a, step=-1, axis=axis)
+
+
+def odd_ext(x, n, axis=-1):
+ """
+ Odd extension at the boundaries of an array
+
+ Generate a new ndarray by making an odd extension of `x` along an axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import odd_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> odd_ext(a, 2)
+ array([[-1, 0, 1, 2, 3, 4, 5, 6, 7],
+ [-4, -1, 0, 1, 4, 9, 16, 23, 28]])
+
+ Odd extension is a "180 degree rotation" at the endpoints of the original
+ array:
+
+ >>> t = np.linspace(0, 1.5, 100)
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
+ >>> b = odd_ext(a, 40)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='odd extension')
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+ """
+ if n < 1:
+ return x
+ if n > x.shape[axis] - 1:
+ raise ValueError(("The extension length n (%d) is too big. " +
+ "It must not exceed x.shape[axis]-1, which is %d.")
+ % (n, x.shape[axis] - 1))
+ left_end = axis_slice(x, start=0, stop=1, axis=axis)
+ left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
+ right_end = axis_slice(x, start=-1, axis=axis)
+ right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
+ ext = np.concatenate((2 * left_end - left_ext,
+ x,
+ 2 * right_end - right_ext),
+ axis=axis)
+ return ext
+
+
+def even_ext(x, n, axis=-1):
+ """
+ Even extension at the boundaries of an array
+
+ Generate a new ndarray by making an even extension of `x` along an axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import even_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> even_ext(a, 2)
+ array([[ 3, 2, 1, 2, 3, 4, 5, 4, 3],
+ [ 4, 1, 0, 1, 4, 9, 16, 9, 4]])
+
+ Even extension is a "mirror image" at the boundaries of the original array:
+
+ >>> t = np.linspace(0, 1.5, 100)
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
+ >>> b = even_ext(a, 40)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='even extension')
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+ """
+ if n < 1:
+ return x
+ if n > x.shape[axis] - 1:
+ raise ValueError(("The extension length n (%d) is too big. " +
+ "It must not exceed x.shape[axis]-1, which is %d.")
+ % (n, x.shape[axis] - 1))
+ left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
+ right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
+ ext = np.concatenate((left_ext,
+ x,
+ right_ext),
+ axis=axis)
+ return ext
+
+
+def const_ext(x, n, axis=-1):
+ """
+ Constant extension at the boundaries of an array
+
+ Generate a new ndarray that is a constant extension of `x` along an axis.
+
+ The extension repeats the values at the first and last element of
+ the axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import const_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> const_ext(a, 2)
+ array([[ 1, 1, 1, 2, 3, 4, 5, 5, 5],
+ [ 0, 0, 0, 1, 4, 9, 16, 16, 16]])
+
+ Constant extension continues with the same values as the endpoints of the
+ array:
+
+ >>> t = np.linspace(0, 1.5, 100)
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
+ >>> b = const_ext(a, 40)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='constant extension')
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+ """
+ if n < 1:
+ return x
+ left_end = axis_slice(x, start=0, stop=1, axis=axis)
+ ones_shape = [1] * x.ndim
+ ones_shape[axis] = n
+ ones = np.ones(ones_shape, dtype=x.dtype)
+ left_ext = ones * left_end
+ right_end = axis_slice(x, start=-1, axis=axis)
+ right_ext = ones * right_end
+ ext = np.concatenate((left_ext,
+ x,
+ right_ext),
+ axis=axis)
+ return ext
+
+
+def zero_ext(x, n, axis=-1):
+ """
+ Zero padding at the boundaries of an array
+
+ Generate a new ndarray that is a zero-padded extension of `x` along
+ an axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the
+ axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import zero_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> zero_ext(a, 2)
+ array([[ 0, 0, 1, 2, 3, 4, 5, 0, 0],
+ [ 0, 0, 0, 1, 4, 9, 16, 0, 0]])
+ """
+ if n < 1:
+ return x
+ zeros_shape = list(x.shape)
+ zeros_shape[axis] = n
+ zeros = np.zeros(zeros_shape, dtype=x.dtype)
+ ext = np.concatenate((zeros, x, zeros), axis=axis)
+ return ext
+
+
+def _validate_fs(fs, allow_none=True):
+ """
+ Check if the given sampling frequency is a scalar and raises an exception
+ otherwise. If allow_none is False, also raises an exception for none
+ sampling rates. Returns the sampling frequency as float or none if the
+ input is none.
+ """
+ if fs is None:
+ if not allow_none:
+ raise ValueError("Sampling frequency can not be none.")
+ else: # should be float
+ if not np.isscalar(fs):
+ raise ValueError("Sampling frequency fs must be a single scalar.")
+ fs = float(fs)
+ return fs
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_czt.py b/.venv/lib/python3.12/site-packages/scipy/signal/_czt.py
new file mode 100644
index 0000000000000000000000000000000000000000..24b3892dfd5e48dc0679bea1cba0d6cdb24a5ec0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_czt.py
@@ -0,0 +1,580 @@
+# This program is public domain
+# Authors: Paul Kienzle, Nadav Horesh
+"""
+Chirp z-transform.
+
+We provide two interfaces to the chirp z-transform: an object interface
+which precalculates part of the transform and can be applied efficiently
+to many different data sets, and a functional interface which is applied
+only to the given data set.
+
+Transforms
+----------
+
+CZT : callable (x, axis=-1) -> array
+ Define a chirp z-transform that can be applied to different signals.
+ZoomFFT : callable (x, axis=-1) -> array
+ Define a Fourier transform on a range of frequencies.
+
+Functions
+---------
+
+czt : array
+ Compute the chirp z-transform for a signal.
+zoom_fft : array
+ Compute the Fourier transform on a range of frequencies.
+"""
+
+import cmath
+import numbers
+import numpy as np
+from numpy import pi, arange
+from scipy.fft import fft, ifft, next_fast_len
+
+__all__ = ['czt', 'zoom_fft', 'CZT', 'ZoomFFT', 'czt_points']
+
+
+def _validate_sizes(n, m):
+ if n < 1 or not isinstance(n, numbers.Integral):
+ raise ValueError('Invalid number of CZT data '
+ f'points ({n}) specified. '
+ 'n must be positive and integer type.')
+
+ if m is None:
+ m = n
+ elif m < 1 or not isinstance(m, numbers.Integral):
+ raise ValueError('Invalid number of CZT output '
+ f'points ({m}) specified. '
+ 'm must be positive and integer type.')
+
+ return m
+
+
+def czt_points(m, w=None, a=1+0j):
+ """
+ Return the points at which the chirp z-transform is computed.
+
+ Parameters
+ ----------
+ m : int
+ The number of points desired.
+ w : complex, optional
+ The ratio between points in each step.
+ Defaults to equally spaced points around the entire unit circle.
+ a : complex, optional
+ The starting point in the complex plane. Default is 1+0j.
+
+ Returns
+ -------
+ out : ndarray
+ The points in the Z plane at which `CZT` samples the z-transform,
+ when called with arguments `m`, `w`, and `a`, as complex numbers.
+
+ See Also
+ --------
+ CZT : Class that creates a callable chirp z-transform function.
+ czt : Convenience function for quickly calculating CZT.
+
+ Examples
+ --------
+ Plot the points of a 16-point FFT:
+
+ >>> import numpy as np
+ >>> from scipy.signal import czt_points
+ >>> points = czt_points(16)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(points.real, points.imag, 'o')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal')
+ >>> plt.show()
+
+ and a 91-point logarithmic spiral that crosses the unit circle:
+
+ >>> m, w, a = 91, 0.995*np.exp(-1j*np.pi*.05), 0.8*np.exp(1j*np.pi/6)
+ >>> points = czt_points(m, w, a)
+ >>> plt.plot(points.real, points.imag, 'o')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal')
+ >>> plt.show()
+ """
+ m = _validate_sizes(1, m)
+
+ k = arange(m)
+
+ a = 1.0 * a # at least float
+
+ if w is None:
+ # Nothing specified, default to FFT
+ return a * np.exp(2j * pi * k / m)
+ else:
+ # w specified
+ w = 1.0 * w # at least float
+ return a * w**-k
+
+
+class CZT:
+ """
+ Create a callable chirp z-transform function.
+
+ Transform to compute the frequency response around a spiral.
+ Objects of this class are callables which can compute the
+ chirp z-transform on their inputs. This object precalculates the constant
+ chirps used in the given transform.
+
+ Parameters
+ ----------
+ n : int
+ The size of the signal.
+ m : int, optional
+ The number of output points desired. Default is `n`.
+ w : complex, optional
+ The ratio between points in each step. This must be precise or the
+ accumulated error will degrade the tail of the output sequence.
+ Defaults to equally spaced points around the entire unit circle.
+ a : complex, optional
+ The starting point in the complex plane. Default is 1+0j.
+
+ Returns
+ -------
+ f : CZT
+ Callable object ``f(x, axis=-1)`` for computing the chirp z-transform
+ on `x`.
+
+ See Also
+ --------
+ czt : Convenience function for quickly calculating CZT.
+ ZoomFFT : Class that creates a callable partial FFT function.
+
+ Notes
+ -----
+ The defaults are chosen such that ``f(x)`` is equivalent to
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, m)`` is equivalent to
+ ``fft.fft(x, m)``.
+
+ If `w` does not lie on the unit circle, then the transform will be
+ around a spiral with exponentially-increasing radius. Regardless,
+ angle will increase linearly.
+
+ For transforms that do lie on the unit circle, accuracy is better when
+ using `ZoomFFT`, since any numerical error in `w` is
+ accumulated for long data lengths, drifting away from the unit circle.
+
+ The chirp z-transform can be faster than an equivalent FFT with
+ zero padding. Try it with your own array sizes to see.
+
+ However, the chirp z-transform is considerably less precise than the
+ equivalent zero-padded FFT.
+
+ As this CZT is implemented using the Bluestein algorithm, it can compute
+ large prime-length Fourier transforms in O(N log N) time, rather than the
+ O(N**2) time required by the direct DFT calculation. (`scipy.fft` also
+ uses Bluestein's algorithm'.)
+
+ (The name "chirp z-transform" comes from the use of a chirp in the
+ Bluestein algorithm. It does not decompose signals into chirps, like
+ other transforms with "chirp" in the name.)
+
+ References
+ ----------
+ .. [1] Leo I. Bluestein, "A linear filtering approach to the computation
+ of the discrete Fourier transform," Northeast Electronics Research
+ and Engineering Meeting Record 10, 218-219 (1968).
+ .. [2] Rabiner, Schafer, and Rader, "The chirp z-transform algorithm and
+ its application," Bell Syst. Tech. J. 48, 1249-1292 (1969).
+
+ Examples
+ --------
+ Compute multiple prime-length FFTs:
+
+ >>> from scipy.signal import CZT
+ >>> import numpy as np
+ >>> a = np.random.rand(7)
+ >>> b = np.random.rand(7)
+ >>> c = np.random.rand(7)
+ >>> czt_7 = CZT(n=7)
+ >>> A = czt_7(a)
+ >>> B = czt_7(b)
+ >>> C = czt_7(c)
+
+ Display the points at which the FFT is calculated:
+
+ >>> czt_7.points()
+ array([ 1.00000000+0.j , 0.62348980+0.78183148j,
+ -0.22252093+0.97492791j, -0.90096887+0.43388374j,
+ -0.90096887-0.43388374j, -0.22252093-0.97492791j,
+ 0.62348980-0.78183148j])
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(czt_7.points().real, czt_7.points().imag, 'o')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal')
+ >>> plt.show()
+ """
+
+ def __init__(self, n, m=None, w=None, a=1+0j):
+ m = _validate_sizes(n, m)
+
+ k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2))
+
+ if w is None:
+ # Nothing specified, default to FFT-like
+ w = cmath.exp(-2j*pi/m)
+ wk2 = np.exp(-(1j * pi * ((k**2) % (2*m))) / m)
+ else:
+ # w specified
+ wk2 = w**(k**2/2.)
+
+ a = 1.0 * a # at least float
+
+ self.w, self.a = w, a
+ self.m, self.n = m, n
+
+ nfft = next_fast_len(n + m - 1)
+ self._Awk2 = a**-k[:n] * wk2[:n]
+ self._nfft = nfft
+ self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
+ self._wk2 = wk2[:m]
+ self._yidx = slice(n-1, n+m-1)
+
+ def __call__(self, x, *, axis=-1):
+ """
+ Calculate the chirp z-transform of a signal.
+
+ Parameters
+ ----------
+ x : array
+ The signal to transform.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
+
+ Returns
+ -------
+ out : ndarray
+ An array of the same dimensions as `x`, but with the length of the
+ transformed axis set to `m`.
+ """
+ x = np.asarray(x)
+ if x.shape[axis] != self.n:
+ raise ValueError(f"CZT defined for length {self.n}, not "
+ f"{x.shape[axis]}")
+ # Calculate transpose coordinates, to allow operation on any given axis
+ trnsp = np.arange(x.ndim)
+ trnsp[[axis, -1]] = [-1, axis]
+ x = x.transpose(*trnsp)
+ y = ifft(self._Fwk2 * fft(x*self._Awk2, self._nfft))
+ y = y[..., self._yidx] * self._wk2
+ return y.transpose(*trnsp)
+
+ def points(self):
+ """
+ Return the points at which the chirp z-transform is computed.
+
+ Returns
+ -------
+ ndarray
+ The points in the Z plane at which `CZT` samples the z-transform.
+ """
+ return czt_points(self.m, self.w, self.a)
+
+
+class ZoomFFT(CZT):
+ """
+ Create a callable zoom FFT transform function.
+
+ This is a specialization of the chirp z-transform (`CZT`) for a set of
+ equally-spaced frequencies around the unit circle, used to calculate a
+ section of the FFT more efficiently than calculating the entire FFT and
+ truncating.
+
+ Parameters
+ ----------
+ n : int
+ The size of the signal.
+ fn : array_like
+ A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
+ scalar, for which the range [0, `fn`] is assumed.
+ m : int, optional
+ The number of points to evaluate. Default is `n`.
+ fs : float, optional
+ The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
+ then `f1` and `f2` would also be given in kHz.
+ The default sampling frequency is 2, so `f1` and `f2` should be
+ in the range [0, 1] to keep the transform below the Nyquist
+ frequency.
+ endpoint : bool, optional
+ If True, `f2` is the last sample. Otherwise, it is not included.
+ Default is False.
+
+ Returns
+ -------
+ f : ZoomFFT
+ Callable object ``f(x, axis=-1)`` for computing the zoom FFT on `x`.
+
+ See Also
+ --------
+ zoom_fft : Convenience function for calculating a zoom FFT.
+
+ Notes
+ -----
+ The defaults are chosen such that ``f(x, 2)`` is equivalent to
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, 2, m)`` is equivalent to
+ ``fft.fft(x, m)``.
+
+ Sampling frequency is 1/dt, the time step between samples in the
+ signal `x`. The unit circle corresponds to frequencies from 0 up
+ to the sampling frequency. The default sampling frequency of 2
+ means that `f1`, `f2` values up to the Nyquist frequency are in the
+ range [0, 1). For `f1`, `f2` values expressed in radians, a sampling
+ frequency of 2*pi should be used.
+
+ Remember that a zoom FFT can only interpolate the points of the existing
+ FFT. It cannot help to resolve two separate nearby frequencies.
+ Frequency resolution can only be increased by increasing acquisition
+ time.
+
+ These functions are implemented using Bluestein's algorithm (as is
+ `scipy.fft`). [2]_
+
+ References
+ ----------
+ .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
+ applications", pg 29 (1970)
+ https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
+ .. [2] Leo I. Bluestein, "A linear filtering approach to the computation
+ of the discrete Fourier transform," Northeast Electronics Research
+ and Engineering Meeting Record 10, 218-219 (1968).
+
+ Examples
+ --------
+ To plot the transform results use something like the following:
+
+ >>> import numpy as np
+ >>> from scipy.signal import ZoomFFT
+ >>> t = np.linspace(0, 1, 1021)
+ >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t)
+ >>> f1, f2 = 5, 27
+ >>> transform = ZoomFFT(len(x), [f1, f2], len(x), fs=1021)
+ >>> X = transform(x)
+ >>> f = np.linspace(f1, f2, len(x))
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(f, 20*np.log10(np.abs(X)))
+ >>> plt.show()
+ """
+
+ def __init__(self, n, fn, m=None, *, fs=2, endpoint=False):
+ m = _validate_sizes(n, m)
+
+ k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2))
+
+ if np.size(fn) == 2:
+ f1, f2 = fn
+ elif np.size(fn) == 1:
+ f1, f2 = 0.0, fn
+ else:
+ raise ValueError('fn must be a scalar or 2-length sequence')
+
+ self.f1, self.f2, self.fs = f1, f2, fs
+
+ if endpoint:
+ scale = ((f2 - f1) * m) / (fs * (m - 1))
+ else:
+ scale = (f2 - f1) / fs
+ a = cmath.exp(2j * pi * f1/fs)
+ wk2 = np.exp(-(1j * pi * scale * k**2) / m)
+
+ self.w = cmath.exp(-2j*pi/m * scale)
+ self.a = a
+ self.m, self.n = m, n
+
+ ak = np.exp(-2j * pi * f1/fs * k[:n])
+ self._Awk2 = ak * wk2[:n]
+
+ nfft = next_fast_len(n + m - 1)
+ self._nfft = nfft
+ self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
+ self._wk2 = wk2[:m]
+ self._yidx = slice(n-1, n+m-1)
+
+
+def czt(x, m=None, w=None, a=1+0j, *, axis=-1):
+ """
+ Compute the frequency response around a spiral in the Z plane.
+
+ Parameters
+ ----------
+ x : array
+ The signal to transform.
+ m : int, optional
+ The number of output points desired. Default is the length of the
+ input data.
+ w : complex, optional
+ The ratio between points in each step. This must be precise or the
+ accumulated error will degrade the tail of the output sequence.
+ Defaults to equally spaced points around the entire unit circle.
+ a : complex, optional
+ The starting point in the complex plane. Default is 1+0j.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
+
+ Returns
+ -------
+ out : ndarray
+ An array of the same dimensions as `x`, but with the length of the
+ transformed axis set to `m`.
+
+ See Also
+ --------
+ CZT : Class that creates a callable chirp z-transform function.
+ zoom_fft : Convenience function for partial FFT calculations.
+
+ Notes
+ -----
+ The defaults are chosen such that ``signal.czt(x)`` is equivalent to
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.czt(x, m)`` is
+ equivalent to ``fft.fft(x, m)``.
+
+ If the transform needs to be repeated, use `CZT` to construct a
+ specialized transform function which can be reused without
+ recomputing constants.
+
+ An example application is in system identification, repeatedly evaluating
+ small slices of the z-transform of a system, around where a pole is
+ expected to exist, to refine the estimate of the pole's true location. [1]_
+
+ References
+ ----------
+ .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
+ applications", pg 20 (1970)
+ https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
+
+ Examples
+ --------
+ Generate a sinusoid:
+
+ >>> import numpy as np
+ >>> f1, f2, fs = 8, 10, 200 # Hz
+ >>> t = np.linspace(0, 1, fs, endpoint=False)
+ >>> x = np.sin(2*np.pi*t*f2)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(t, x)
+ >>> plt.axis([0, 1, -1.1, 1.1])
+ >>> plt.show()
+
+ Its discrete Fourier transform has all of its energy in a single frequency
+ bin:
+
+ >>> from scipy.fft import rfft, rfftfreq
+ >>> from scipy.signal import czt, czt_points
+ >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x)))
+ >>> plt.margins(0, 0.1)
+ >>> plt.show()
+
+ However, if the sinusoid is logarithmically-decaying:
+
+ >>> x = np.exp(-t*f1) * np.sin(2*np.pi*t*f2)
+ >>> plt.plot(t, x)
+ >>> plt.axis([0, 1, -1.1, 1.1])
+ >>> plt.show()
+
+ the DFT will have spectral leakage:
+
+ >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x)))
+ >>> plt.margins(0, 0.1)
+ >>> plt.show()
+
+ While the DFT always samples the z-transform around the unit circle, the
+ chirp z-transform allows us to sample the Z-transform along any
+ logarithmic spiral, such as a circle with radius smaller than unity:
+
+ >>> M = fs // 2 # Just positive frequencies, like rfft
+ >>> a = np.exp(-f1/fs) # Starting point of the circle, radius < 1
+ >>> w = np.exp(-1j*np.pi/M) # "Step size" of circle
+ >>> points = czt_points(M + 1, w, a) # M + 1 to include Nyquist
+ >>> plt.plot(points.real, points.imag, '.')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal'); plt.axis([-1.05, 1.05, -0.05, 1.05])
+ >>> plt.show()
+
+ With the correct radius, this transforms the decaying sinusoid (and others
+ with the same decay rate) without spectral leakage:
+
+ >>> z_vals = czt(x, M + 1, w, a) # Include Nyquist for comparison to rfft
+ >>> freqs = np.angle(points)*fs/(2*np.pi) # angle = omega, radius = sigma
+ >>> plt.plot(freqs, abs(z_vals))
+ >>> plt.margins(0, 0.1)
+ >>> plt.show()
+ """
+ x = np.asarray(x)
+ transform = CZT(x.shape[axis], m=m, w=w, a=a)
+ return transform(x, axis=axis)
+
+
+def zoom_fft(x, fn, m=None, *, fs=2, endpoint=False, axis=-1):
+ """
+ Compute the DFT of `x` only for frequencies in range `fn`.
+
+ Parameters
+ ----------
+ x : array
+ The signal to transform.
+ fn : array_like
+ A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
+ scalar, for which the range [0, `fn`] is assumed.
+ m : int, optional
+ The number of points to evaluate. The default is the length of `x`.
+ fs : float, optional
+ The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
+ then `f1` and `f2` would also be given in kHz.
+ The default sampling frequency is 2, so `f1` and `f2` should be
+ in the range [0, 1] to keep the transform below the Nyquist
+ frequency.
+ endpoint : bool, optional
+ If True, `f2` is the last sample. Otherwise, it is not included.
+ Default is False.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
+
+ Returns
+ -------
+ out : ndarray
+ The transformed signal. The Fourier transform will be calculated
+ at the points f1, f1+df, f1+2df, ..., f2, where df=(f2-f1)/m.
+
+ See Also
+ --------
+ ZoomFFT : Class that creates a callable partial FFT function.
+
+ Notes
+ -----
+ The defaults are chosen such that ``signal.zoom_fft(x, 2)`` is equivalent
+ to ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.zoom_fft(x, 2, m)``
+ is equivalent to ``fft.fft(x, m)``.
+
+ To graph the magnitude of the resulting transform, use::
+
+ plot(linspace(f1, f2, m, endpoint=False), abs(zoom_fft(x, [f1, f2], m)))
+
+ If the transform needs to be repeated, use `ZoomFFT` to construct
+ a specialized transform function which can be reused without
+ recomputing constants.
+
+ Examples
+ --------
+ To plot the transform results use something like the following:
+
+ >>> import numpy as np
+ >>> from scipy.signal import zoom_fft
+ >>> t = np.linspace(0, 1, 1021)
+ >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t)
+ >>> f1, f2 = 5, 27
+ >>> X = zoom_fft(x, [f1, f2], len(x), fs=1021)
+ >>> f = np.linspace(f1, f2, len(x))
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(f, 20*np.log10(np.abs(X)))
+ >>> plt.show()
+ """
+ x = np.asarray(x)
+ transform = ZoomFFT(x.shape[axis], fn, m=m, fs=fs, endpoint=endpoint)
+ return transform(x, axis=axis)
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_delegators.py b/.venv/lib/python3.12/site-packages/scipy/signal/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..42b2c22500c322a5e4fd839b447642f7e5bf796c
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_delegators.py
@@ -0,0 +1,573 @@
+"""Delegators for alternative backends in scipy.signal.
+
+The signature of `func_signature` must match the signature of signal.func.
+The job of a `func_signature` is to know which arguments of `signal.func`
+are arrays.
+
+* signatures are generated by
+
+--------------
+ import inspect
+ from scipy import signal
+
+ names = [x for x in dir(signal) if not x.startswith('_')]
+ objs = [getattr(signal, name) for name in names]
+ funcs = [obj for obj in objs if inspect.isroutine(obj)]
+
+ for func in funcs:
+ try:
+ sig = inspect.signature(func)
+ except ValueError:
+ sig = "( FIXME )"
+ print(f"def {func.__name__}_signature{sig}:\n\treturn array_namespace(...
+ )\n\n")
+---------------
+
+* which arguments to delegate on: manually trawled the documentation for
+ array-like and array arguments
+
+"""
+import numpy as np
+from scipy._lib._array_api import array_namespace, np_compat, is_jax
+
+
+def _skip_if_lti(arg):
+ """Handle `system` arg overloads.
+
+ ATM, only pass tuples through. Consider updating when cupyx.lti class
+ is supported.
+ """
+ if isinstance(arg, tuple):
+ return arg
+ else:
+ return (None,)
+
+
+def _skip_if_str_or_tuple(window):
+ """Handle `window` being a str or a tuple or an array-like.
+ """
+ if isinstance(window, str) or isinstance(window, tuple) or callable(window):
+ return None
+ else:
+ return window
+
+
+def _skip_if_poly1d(arg):
+ return None if isinstance(arg, np.poly1d) else arg
+
+
+###################
+
+def abcd_normalize_signature(A=None, B=None, C=None, D=None):
+ return array_namespace(A, B, C, D)
+
+def argrelextrema_signature(data, *args, **kwds):
+ return array_namespace(data)
+
+argrelmax_signature = argrelextrema_signature
+argrelmin_signature = argrelextrema_signature
+
+
+def band_stop_obj_signature(wp, ind, passb, stopb, gpass, gstop, type):
+ return array_namespace(passb, stopb)
+
+
+def bessel_signature(N, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+butter_signature = bessel_signature
+
+
+def cheby2_signature(N, rs, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+def cheby1_signature(N, rp, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+def ellip_signature(N, rp, rs, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+########################## XXX: no arrays in, arrays out
+def besselap_signature(N, norm='phase', *, xp=None, device=None):
+ return np if xp is None else xp
+
+
+def buttap_signature(N, *, xp=None, device=None):
+ return np if xp is None else xp
+
+
+def cheb1ap_signature(N, rp, *, xp=None, device=None):
+ return np if xp is None else xp
+
+
+def cheb2ap_signature(N, rs, *, xp=None, device=None):
+ return np if xp is None else xp
+
+def ellipap_signature(N, rp, rs, *, xp=None, device=None):
+ return np if xp is None else xp
+
+def correlation_lags_signature(in1_len, in2_len, mode='full'):
+ return np
+
+
+def czt_points_signature(m, w=None, a=(1+0j)):
+ return np
+
+
+def gammatone_signature(
+ freq, ftype, order=None, numtaps=None, fs=None, *, xp=None, device=None
+ ):
+ return np_compat if xp is None else xp
+
+
+def iircomb_signature(
+ w0, Q, ftype='notch', fs=2.0, *, pass_zero=False, xp=None, device=None
+):
+ return np_compat if xp is None else xp
+
+
+def iirnotch_signature(w0, Q, fs=2.0, *, xp=None, device=None):
+ return np if xp is None else xp
+
+iirpeak_signature = iirnotch_signature
+
+
+def savgol_coeffs_signature(
+ window_length, polyorder, deriv=0, delta=1.0, pos=None, use='conv',
+ *, xp=None, device=None
+):
+ return np if xp is None else xp
+
+
+
+def unit_impulse_signature(shape, idx=None, dtype=float):
+ return np
+############################
+
+
+def buttord_signature(wp, ws, gpass, gstop, analog=False, fs=None):
+ return array_namespace(wp, ws)
+
+cheb1ord_signature = buttord_signature
+cheb2ord_signature = buttord_signature
+ellipord_signature = buttord_signature
+
+
+########### NB: scalars in, scalars out
+def kaiser_atten_signature(numtaps, width):
+ return np
+
+def kaiser_beta_signature(a):
+ return np
+
+def kaiserord_signature(ripple, width):
+ return np
+
+def get_window_signature(window, Nx, fftbins=True, *, xp=None, device=None):
+ return np if xp is None else xp
+#################################
+
+
+def bode_signature(system, w=None, n=100):
+ return array_namespace(*_skip_if_lti(system), w)
+
+dbode_signature = bode_signature
+
+
+def freqresp_signature(system, w=None, n=10000):
+ return array_namespace(*_skip_if_lti(system), w)
+
+dfreqresp_signature = freqresp_signature
+
+
+def impulse_signature(system, X0=None, T=None, N=None):
+ return array_namespace(*_skip_if_lti(system), X0, T)
+
+
+def dimpulse_signature(system, x0=None, t=None, n=None):
+ return array_namespace(*_skip_if_lti(system), x0, t)
+
+
+def lsim_signature(system, U, T, X0=None, interp=True):
+ return array_namespace(*_skip_if_lti(system), U, T, X0)
+
+
+def dlsim_signature(system, u, t=None, x0=None):
+ return array_namespace(*_skip_if_lti(system), u, t, x0)
+
+
+def step_signature(system, X0=None, T=None, N=None):
+ return array_namespace(*_skip_if_lti(system), X0, T)
+
+def dstep_signature(system, x0=None, t=None, n=None):
+ return array_namespace(*_skip_if_lti(system), x0, t)
+
+
+def cont2discrete_signature(system, dt, method='zoh', alpha=None):
+ return array_namespace(*_skip_if_lti(system))
+
+
+def bilinear_signature(b, a, fs=1.0):
+ return array_namespace(b, a)
+
+
+def bilinear_zpk_signature(z, p, k, fs):
+ return array_namespace(z, p)
+
+
+def chirp_signature(t,*args, **kwds):
+ return array_namespace(t)
+
+
+############## XXX: array-likes in, str out
+def choose_conv_method_signature(in1, in2, *args, **kwds):
+ return array_namespace(in1, in2)
+############################################
+
+
+def convolve_signature(in1, in2, *args, **kwds):
+ return array_namespace(in1, in2)
+
+fftconvolve_signature = convolve_signature
+oaconvolve_signature = convolve_signature
+correlate_signature = convolve_signature
+correlate_signature = convolve_signature
+convolve2d_signature = convolve_signature
+correlate2d_signature = convolve_signature
+
+
+def coherence_signature(x, y, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, y, _skip_if_str_or_tuple(window))
+
+
+def csd_signature(x, y, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, y, _skip_if_str_or_tuple(window))
+
+
+def periodogram_signature(x, fs=1.0, window='boxcar', *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def welch_signature(x, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def spectrogram_signature(x, fs=1.0, window=('tukey_periodic', 0.25), *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def stft_signature(x, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def istft_signature(Zxx, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(Zxx, _skip_if_str_or_tuple(window))
+
+
+def resample_signature(x, num, t=None, axis=0, window=None, domain='time'):
+ return array_namespace(x, t, _skip_if_str_or_tuple(window))
+
+
+def resample_poly_signature(x, up, down, axis=0, window=('kaiser', 5.0), *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def check_COLA_signature(window, nperseg, noverlap, tol=1e-10):
+ return array_namespace(_skip_if_str_or_tuple(window))
+
+
+def check_NOLA_signature(window, nperseg, noverlap, tol=1e-10):
+ return array_namespace(_skip_if_str_or_tuple(window))
+
+
+def czt_signature(x, *args, **kwds):
+ return array_namespace(x)
+
+decimate_signature = czt_signature
+gauss_spline_signature = czt_signature
+
+
+def deconvolve_signature(signal, divisor):
+ return array_namespace(signal, divisor)
+
+
+def detrend_signature(data, axis=1, type='linear', bp=0, *args, **kwds):
+ xp = array_namespace(data)
+ # JAX doesn't accept JAX arrays for bp, only ints, lists and NumPy
+ # arrays.
+ return xp if is_jax(xp) else array_namespace(data, bp)
+
+
+def filtfilt_signature(b, a, x, *args, **kwds):
+ return array_namespace(b, a, x)
+
+
+def lfilter_signature(b, a, x, axis=-1, zi=None):
+ return array_namespace(b, a, x, zi)
+
+
+def envelope_signature(z, *args, **kwds):
+ return array_namespace(z)
+
+
+def find_peaks_signature(
+ x, height=None, threshold=None, distance=None, prominence=None, width=None,
+ wlen=None, rel_height=0.5, plateau_size=None
+):
+ # TODO: fix me - `prominence` is not necessarily an array.
+ # return array_namespace(x, height, threshold, prominence, width, plateau_size)
+ # See https://github.com/scipy/scipy/pull/22644#issuecomment-3568443768. For now:
+ return np_compat
+
+def find_peaks_cwt_signature(
+ vector, widths, wavelet=None, max_distances=None, *args, **kwds
+):
+ return array_namespace(vector, widths, max_distances)
+
+
+def findfreqs_signature(num, den, N, kind='ba'):
+ return array_namespace(num, den)
+
+
+def firls_signature(numtaps, bands, desired, *, weight=None, fs=None):
+ return array_namespace(bands, desired, weight)
+
+
+def firwin_signature(numtaps, cutoff, *args, **kwds):
+ if isinstance(cutoff, int | float):
+ xp = np_compat
+ else:
+ xp = array_namespace(cutoff)
+ return xp
+
+
+def firwin2_signature(numtaps, freq, gain, *args, **kwds):
+ return array_namespace(freq, gain)
+
+
+def freqs_zpk_signature(z, p, k, worN=200, *args, **kwds):
+ return array_namespace(z, p, worN)
+
+freqz_zpk_signature = freqs_zpk_signature
+
+
+def freqs_signature(b, a, worN=200, *args, **kwds):
+ return array_namespace(b, a, worN)
+
+
+def freqz_signature(b, a=1, worN=512, *args, **kwds):
+ # differs from freqs: `a` has a default value
+ return array_namespace(b, a, worN)
+
+
+def freqz_sos_signature(sos, worN=512, *args, **kwds):
+ return array_namespace(sos, worN)
+
+sosfreqz_signature = freqz_sos_signature
+
+
+def gausspulse_signature(t, *args, **kwds):
+ arr_t = None if isinstance(t, str) else t
+ return array_namespace(arr_t)
+
+
+def group_delay_signature(system, w=512, whole=False, fs=6.283185307179586):
+ return array_namespace(*system, w)
+
+
+def hilbert_signature(x, *args, **kwds):
+ return array_namespace(x)
+
+hilbert2_signature = hilbert_signature
+
+
+def iirdesign_signature(wp, ws, *args, **kwds):
+ return array_namespace(wp, ws)
+
+
+def iirfilter_signature(N, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+def invres_signature(r, p, k, tol=0.001, rtype='avg'):
+ return array_namespace(r, p, k)
+
+invresz_signature = invres_signature
+
+
+############################### XXX: excluded, blacklisted on CuPy (mismatched API)
+def lfilter_zi_signature(b, a):
+ return array_namespace(b, a)
+
+def sosfilt_zi_signature(sos):
+ return array_namespace(sos)
+
+# needs to be blacklisted on CuPy (is not implemented)
+def remez_signature(numtaps, bands, desired, *, weight=None, **kwds):
+ return array_namespace(bands, desired, weight)
+#############################################
+
+def lfiltic_signature(b, a, y, x=None):
+ return array_namespace(b, a, y, x)
+
+
+def lombscargle_signature(
+ x, y, freqs, precenter=False, normalize=False, *,
+ weights=None, floating_mean=False
+):
+ return array_namespace(x, y, freqs, weights)
+
+
+def lp2bp_signature(b, a, *args, **kwds):
+ return array_namespace(b, a)
+
+lp2bs_signature = lp2bp_signature
+lp2hp_signature = lp2bp_signature
+lp2lp_signature = lp2bp_signature
+
+tf2zpk_signature = lp2bp_signature
+tf2sos_signature = lp2bp_signature
+
+normalize_signature = lp2bp_signature
+residue_signature = lp2bp_signature
+residuez_signature = residue_signature
+
+
+def lp2bp_zpk_signature(z, p, k, *args, **kwds):
+ return array_namespace(z, p)
+
+lp2bs_zpk_signature = lp2bp_zpk_signature
+lp2hp_zpk_signature = lp2bs_zpk_signature
+lp2lp_zpk_signature = lp2bs_zpk_signature
+
+
+def zpk2sos_signature(z, p, k, *args, **kwds):
+ return array_namespace(z, p)
+
+zpk2ss_signature = zpk2sos_signature
+zpk2tf_signature = zpk2sos_signature
+
+
+def max_len_seq_signature(nbits, state=None, length=None, taps=None):
+ return array_namespace(state, taps)
+
+
+def medfilt_signature(volume, kernel_size=None):
+ return array_namespace(volume)
+
+
+def medfilt2d_signature(input, kernel_size=3):
+ return array_namespace(input)
+
+
+def minimum_phase_signature(h, *args, **kwds):
+ return array_namespace(h)
+
+
+def order_filter_signature(a, domain, rank):
+ return array_namespace(a, domain)
+
+
+def peak_prominences_signature(x, peaks, *args, **kwds):
+ return array_namespace(x, peaks)
+
+
+peak_widths_signature = peak_prominences_signature
+
+
+def place_poles_signature(A, B, poles, method='YT', rtol=0.001, maxiter=30):
+ return array_namespace(A, B, poles)
+
+
+def savgol_filter_signature(x, *args, **kwds):
+ return array_namespace(x)
+
+
+def sawtooth_signature(t, width=1):
+ return array_namespace(t)
+
+
+def sepfir2d_signature(input, hrow, hcol):
+ return array_namespace(input, hrow, hcol)
+
+
+def sos2tf_signature(sos):
+ return array_namespace(sos)
+
+
+sos2zpk_signature = sos2tf_signature
+
+
+def sosfilt_signature(sos, x, axis=-1, zi=None):
+ return array_namespace(sos, x, zi)
+
+
+def sosfiltfilt_signature(sos, x, *args, **kwds):
+ return array_namespace(sos, x)
+
+
+def spline_filter_signature(Iin, lmbda=5.0):
+ return array_namespace(Iin)
+
+
+def square_signature(t, duty=0.5):
+ return array_namespace(t, duty)
+
+
+def ss2tf_signature(A, B, C, D, input=0):
+ return array_namespace(A, B, C, D)
+
+ss2zpk_signature = ss2tf_signature
+
+
+def sweep_poly_signature(t, poly, phi=0):
+ return array_namespace(t, _skip_if_poly1d(poly))
+
+
+def symiirorder1_signature(signal, c0, z1, precision=-1.0):
+ return array_namespace(signal)
+
+
+def symiirorder2_signature(input, r, omega, precision=-1.0):
+ return array_namespace(input, r, omega)
+
+
+def cspline1d_signature(signal, *args, **kwds):
+ return array_namespace(signal)
+
+qspline1d_signature = cspline1d_signature
+cspline2d_signature = cspline1d_signature
+qspline2d_signature = qspline1d_signature
+
+
+def cspline1d_eval_signature(cj, newx, *args, **kwds):
+ return array_namespace(cj, newx)
+
+qspline1d_eval_signature = cspline1d_eval_signature
+
+
+def tf2ss_signature(num, den):
+ return array_namespace(num, den)
+
+
+def unique_roots_signature(p, tol=0.001, rtype='min'):
+ return array_namespace(p)
+
+
+def upfirdn_signature(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):
+ return array_namespace(h, x)
+
+
+def vectorstrength_signature(events, period):
+ return array_namespace(events, period)
+
+
+def wiener_signature(im, mysize=None, noise=None):
+ return array_namespace(im)
+
+
+def zoom_fft_signature(x, fn, m=None, *, fs=2, endpoint=False, axis=-1):
+ return array_namespace(x, fn)
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_filter_design.py b/.venv/lib/python3.12/site-packages/scipy/signal/_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..88710c15393ef7b1409862b6a0fc0d57e42afeff
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_filter_design.py
@@ -0,0 +1,6097 @@
+"""Filter design."""
+import math
+import cmath
+import operator
+import warnings
+import builtins
+
+from math import pi
+
+import numpy as np
+from numpy.polynomial.polynomial import polyval as npp_polyval
+
+from scipy import special, optimize, fft as sp_fft
+from scipy.special import comb
+from scipy._lib import doccer
+from scipy._lib._util import float_factorial
+from scipy.signal._arraytools import _validate_fs
+from scipy.signal import _polyutils as _pu
+
+import scipy._external.array_api_extra as xpx
+from scipy._lib._array_api import (
+ array_namespace, xp_promote, xp_size, xp_default_dtype, is_jax, xp_float_to_complex,
+ xp_result_type,
+)
+from scipy._external.array_api_compat import numpy as np_compat
+
+
+__all__ = ['findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize',
+ 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign',
+ 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel',
+ 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord',
+ 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap',
+ 'BadCoefficients', 'freqs_zpk', 'freqz_zpk',
+ 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay',
+ 'sosfreqz', 'freqz_sos', 'iirnotch', 'iirpeak', 'bilinear_zpk',
+ 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk',
+ 'gammatone', 'iircomb']
+
+
+class BadCoefficients(UserWarning):
+ """Warning about badly conditioned filter coefficients."""
+ pass
+
+
+abs = np.absolute
+
+
+def _is_int_type(x):
+ """
+ Check if input is of a scalar integer type (so ``5`` and ``array(5)`` will
+ pass, while ``5.0`` and ``array([5])`` will fail.
+ """
+ if np.ndim(x) != 0:
+ # Older versions of NumPy did not raise for np.array([1]).__index__()
+ # This is safe to remove when support for those versions is dropped
+ return False
+ try:
+ operator.index(x)
+ except TypeError:
+ return False
+ else:
+ return True
+
+
+def _real_dtype_for_complex(dtyp, *, xp):
+ if xp.isdtype(dtyp, 'real floating'):
+ return dtyp
+ if dtyp == xp.complex64:
+ return xp.float32
+ elif dtyp == xp.complex128:
+ return xp.float64
+ else:
+ raise ValueError(f"Unknown dtype {dtyp}.")
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/_core/function_base.py#L195-L302
+def _logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, *, xp):
+ if not isinstance(base, float | int) and xp.asarray(base).ndim > 0:
+ # If base is non-scalar, broadcast it with the others, since it
+ # may influence how axis is interpreted.
+ start, stop, base = map(xp.asarray, (start, stop, base))
+ ndmax = xp.broadcast_arrays(start, stop, base).ndim
+ start, stop, base = (
+ xpx.atleast_nd(a, ndim=ndmax)
+ for a in (start, stop, base)
+ )
+ base = xp.expand_dims(base)
+ try:
+ result_dt = xp.result_type(start, stop, base)
+ except ValueError:
+ # all of start, stop and base are python scalars
+ result_dt = xp_default_dtype(xp)
+ y = xp.linspace(start, stop, num=num, endpoint=endpoint, dtype=result_dt)
+
+ yp = xp.pow(base, y)
+ if dtype is None:
+ return yp
+ return xp.astype(yp, dtype, copy=False)
+
+
+def findfreqs(num, den, N, kind='ba'):
+ """
+ Find array of frequencies for computing the response of an analog filter.
+
+ Parameters
+ ----------
+ num, den : array_like, 1-D
+ The polynomial coefficients of the numerator and denominator of the
+ transfer function of the filter or LTI system, where the coefficients
+ are ordered from highest to lowest degree. Or, the roots of the
+ transfer function numerator and denominator (i.e., zeroes and poles).
+ N : int
+ The length of the array to be computed.
+ kind : str {'ba', 'zp'}, optional
+ Specifies whether the numerator and denominator are specified by their
+ polynomial coefficients ('ba'), or their roots ('zp').
+
+ Returns
+ -------
+ w : (N,) ndarray
+ A 1-D array of frequencies, logarithmically spaced.
+
+ Examples
+ --------
+ Find a set of nine frequencies that span the "interesting part" of the
+ frequency response for the filter with the transfer function
+
+ H(s) = s / (s^2 + 8s + 25)
+
+ >>> from scipy import signal
+ >>> signal.findfreqs([1, 0], [1, 8, 25], N=9)
+ array([ 1.00000000e-02, 3.16227766e-02, 1.00000000e-01,
+ 3.16227766e-01, 1.00000000e+00, 3.16227766e+00,
+ 1.00000000e+01, 3.16227766e+01, 1.00000000e+02])
+ """
+ xp = array_namespace(num, den)
+ num, den = map(xp.asarray, (num, den))
+
+ if kind == 'ba':
+ ep = xpx.atleast_nd(_pu.polyroots(den, xp=xp), ndim=1, xp=xp)
+ tz = xpx.atleast_nd(_pu.polyroots(num, xp=xp), ndim=1, xp=xp)
+ elif kind == 'zp':
+ ep = xpx.atleast_nd(den, ndim=1, xp=xp)
+ tz = xpx.atleast_nd(num, ndim=1, xp=xp)
+ else:
+ raise ValueError("input must be one of {'ba', 'zp'}")
+
+ ep = xp_float_to_complex(ep, xp=xp)
+ tz = xp_float_to_complex(tz, xp=xp)
+
+ if ep.shape[0] == 0:
+ ep = xp.asarray([-1000], dtype=ep.dtype)
+
+ ez = xp.concat((
+ ep[xp.imag(ep) >= 0],
+ tz[(xp.abs(tz) < 1e5) & (xp.imag(tz) >= 0)]
+ ))
+
+ integ = xp.astype(xp.abs(ez) < 1e-10, ez.dtype) # XXX True->1, False->0
+ hfreq = xp.round(
+ xp.log10(xp.max(3*xp.abs(xp.real(ez) + integ) + 1.5*xp.imag(ez))) + 0.5
+ )
+
+ # the fudge factor is for backwards compatibility: round(-1.5) can be -1 or -2
+ # depending on the floating-point jitter in -1.5
+ fudge = 1e-14 if is_jax(xp) else 0
+ lfreq = xp.round(
+ xp.log10(0.1*xp.min(xp.abs(xp.real(ez + integ)) + 2*xp.imag(ez))) - 0.5 - fudge
+ )
+
+ w = _logspace(lfreq, hfreq, N, xp=xp)
+ return w
+
+
+def freqs(b, a, worN=200, plot=None):
+ """
+ Compute frequency response of analog filter.
+
+ Given the M-order numerator `b` and N-order denominator `a` of an analog
+ filter, compute its frequency response::
+
+ b[0]*(jw)**M + b[1]*(jw)**(M-1) + ... + b[M]
+ H(w) = ----------------------------------------------
+ a[0]*(jw)**N + a[1]*(jw)**(N-1) + ... + a[N]
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator of a linear filter.
+ a : array_like
+ Denominator of a linear filter.
+ worN : {None, int, array_like}, optional
+ If None, then compute at 200 frequencies around the interesting parts
+ of the response curve (determined by pole-zero locations). If a single
+ integer, then compute at that many frequencies. Otherwise, compute the
+ response at the angular frequencies (e.g., rad/s) given in `worN`.
+ plot : callable, optional
+ A callable that takes two arguments. If given, the return parameters
+ `w` and `h` are passed to plot. Useful for plotting the frequency
+ response inside `freqs`.
+
+ Returns
+ -------
+ w : ndarray
+ The angular frequencies at which `h` was computed.
+ h : ndarray
+ The frequency response.
+
+ See Also
+ --------
+ freqz : Compute the frequency response of a digital filter.
+
+ Notes
+ -----
+ Using Matplotlib's "plot" function as the callable for `plot` produces
+ unexpected results, this plots the real part of the complex transfer
+ function, not the magnitude. Try ``lambda w, h: plot(w, abs(h))``.
+
+ Examples
+ --------
+ >>> from scipy.signal import freqs, iirfilter
+ >>> import numpy as np
+
+ >>> b, a = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1')
+
+ >>> w, h = freqs(b, a, worN=np.logspace(-1, 2, 1000))
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude response [dB]')
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(b, a, worN)
+
+ if worN is None:
+ # For backwards compatibility
+ w = findfreqs(b, a, 200)
+ elif _is_int_type(worN):
+ w = findfreqs(b, a, worN)
+ else:
+ w = xpx.atleast_nd(xp.asarray(worN), ndim=1, xp=xp)
+
+ s = 1j * w
+ h = _pu.polyval(b, s, xp=xp) / _pu.polyval(a, s, xp=xp)
+ if plot is not None:
+ plot(w, h)
+
+ return w, h
+
+
+def freqs_zpk(z, p, k, worN=200):
+ """
+ Compute frequency response of analog filter.
+
+ Given the zeros `z`, poles `p`, and gain `k` of a filter, compute its
+ frequency response::
+
+ (jw-z[0]) * (jw-z[1]) * ... * (jw-z[-1])
+ H(w) = k * ----------------------------------------
+ (jw-p[0]) * (jw-p[1]) * ... * (jw-p[-1])
+
+ Parameters
+ ----------
+ z : array_like
+ Zeroes of a linear filter
+ p : array_like
+ Poles of a linear filter
+ k : scalar
+ Gain of a linear filter
+ worN : {None, int, array_like}, optional
+ If None, then compute at 200 frequencies around the interesting parts
+ of the response curve (determined by pole-zero locations). If a single
+ integer, then compute at that many frequencies. Otherwise, compute the
+ response at the angular frequencies (e.g., rad/s) given in `worN`.
+
+ Returns
+ -------
+ w : ndarray
+ The angular frequencies at which `h` was computed.
+ h : ndarray
+ The frequency response.
+
+ See Also
+ --------
+ freqs : Compute the frequency response of an analog filter in TF form
+ freqz : Compute the frequency response of a digital filter in TF form
+ freqz_zpk : Compute the frequency response of a digital filter in ZPK form
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import freqs_zpk, iirfilter
+
+ >>> z, p, k = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1',
+ ... output='zpk')
+
+ >>> w, h = freqs_zpk(z, p, k, worN=np.logspace(-1, 2, 1000))
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude response [dB]')
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(z, p)
+ z, p = map(xp.asarray, (z, p))
+
+ # NB: k is documented to be a scalar; for backwards compat we keep allowing it
+ # to be a size-1 array, but it does not influence the namespace calculation.
+ k = xp.asarray(k, dtype=xp_default_dtype(xp))
+ if xp_size(k) > 1:
+ raise ValueError('k must be a single scalar gain')
+
+ if worN is None:
+ # For backwards compatibility
+ w = findfreqs(z, p, 200, kind='zp')
+ elif _is_int_type(worN):
+ w = findfreqs(z, p, worN, kind='zp')
+ else:
+ w = worN
+
+ w = xpx.atleast_nd(xp.asarray(w), ndim=1, xp=xp)
+ s = 1j * w
+ num = _pu.npp_polyvalfromroots(s, z, xp=xp)
+ den = _pu.npp_polyvalfromroots(s, p, xp=xp)
+ h = k * num/den
+ return w, h
+
+
+def freqz(b, a=1, worN=512, whole=False, plot=None, fs=2*pi,
+ include_nyquist=False):
+ """
+ Compute the frequency response of a digital filter.
+
+ Given the M-order numerator `b` and N-order denominator `a` of a digital
+ filter, compute its frequency response::
+
+ jw -jw -jwM
+ jw B(e ) b[0] + b[1]e + ... + b[M]e
+ H(e ) = ------ = -----------------------------------
+ jw -jw -jwN
+ A(e ) a[0] + a[1]e + ... + a[N]e
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator of a linear filter. If `b` has dimension greater than 1,
+ it is assumed that the coefficients are stored in the first dimension,
+ and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies
+ array must be compatible for broadcasting.
+ a : array_like
+ Denominator of a linear filter. If `b` has dimension greater than 1,
+ it is assumed that the coefficients are stored in the first dimension,
+ and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies
+ array must be compatible for broadcasting.
+ worN : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512). This is a convenient alternative to::
+
+ np.linspace(0, fs if whole else fs/2, N, endpoint=include_nyquist)
+
+ Using a number that is fast for FFT computations can result in
+ faster computations (see Notes).
+
+ If an array_like, compute the response at the frequencies given.
+ These are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs. Ignored if worN is array_like.
+ plot : callable
+ A callable that takes two arguments. If given, the return parameters
+ `w` and `h` are passed to plot. Useful for plotting the frequency
+ response inside `freqz`.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+ include_nyquist : bool, optional
+ If `whole` is False and `worN` is an integer, setting `include_nyquist`
+ to True will include the last frequency (Nyquist frequency) and is
+ otherwise ignored.
+
+ .. versionadded:: 1.5.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which `h` was computed, in the same units as `fs`.
+ By default, `w` is normalized to the range [0, pi) (radians/sample).
+ h : ndarray
+ The frequency response, as complex numbers.
+
+ See Also
+ --------
+ freqz_zpk
+ freqz_sos
+
+ Notes
+ -----
+ Using Matplotlib's :func:`matplotlib.pyplot.plot` function as the callable
+ for `plot` produces unexpected results, as this plots the real part of the
+ complex transfer function, not the magnitude.
+ Try ``lambda w, h: plot(w, np.abs(h))``.
+
+ A direct computation via (R)FFT is used to compute the frequency response
+ when the following conditions are met:
+
+ 1. An integer value is given for `worN`.
+ 2. `worN` is fast to compute via FFT (i.e.,
+ `next_fast_len(worN) ` equals `worN`).
+ 3. The denominator coefficients are a single value (``a.shape[0] == 1``).
+ 4. `worN` is at least as long as the numerator coefficients
+ (``worN >= b.shape[0]``).
+ 5. If ``b.ndim > 1``, then ``b.shape[-1] == 1``.
+
+ For long FIR filters, the FFT approach can have lower error and be much
+ faster than the equivalent direct polynomial calculation.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> taps, f_c = 80, 1.0 # number of taps and cut-off frequency
+ >>> b = signal.firwin(taps, f_c, window=('kaiser', 8), fs=2*np.pi)
+ >>> w, h = signal.freqz(b)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, ax1 = plt.subplots(tight_layout=True)
+ >>> ax1.set_title(f"Frequency Response of {taps} tap FIR Filter" +
+ ... f"($f_c={f_c}$ rad/sample)")
+ >>> ax1.axvline(f_c, color='black', linestyle=':', linewidth=0.8)
+ >>> ax1.plot(w, 20 * np.log10(abs(h)), 'C0')
+ >>> ax1.set_ylabel("Amplitude in dB", color='C0')
+ >>> ax1.set(xlabel="Frequency in rad/sample", xlim=(0, np.pi))
+
+ >>> ax2 = ax1.twinx()
+ >>> phase = np.unwrap(np.angle(h))
+ >>> ax2.plot(w, phase, 'C1')
+ >>> ax2.set_ylabel('Phase [rad]', color='C1')
+ >>> ax2.grid(True)
+ >>> ax2.axis('tight')
+ >>> plt.show()
+
+ Broadcasting Examples
+
+ Suppose we have two FIR filters whose coefficients are stored in the
+ rows of an array with shape (2, 25). For this demonstration, we'll
+ use random data:
+
+ >>> rng = np.random.default_rng()
+ >>> b = rng.random((2, 25))
+
+ To compute the frequency response for these two filters with one call
+ to `freqz`, we must pass in ``b.T``, because `freqz` expects the first
+ axis to hold the coefficients. We must then extend the shape with a
+ trivial dimension of length 1 to allow broadcasting with the array
+ of frequencies. That is, we pass in ``b.T[..., np.newaxis]``, which has
+ shape (25, 2, 1):
+
+ >>> w, h = signal.freqz(b.T[..., np.newaxis], worN=1024)
+ >>> w.shape
+ (1024,)
+ >>> h.shape
+ (2, 1024)
+
+ Now, suppose we have two transfer functions, with the same numerator
+ coefficients ``b = [0.5, 0.5]``. The coefficients for the two denominators
+ are stored in the first dimension of the 2-D array `a`::
+
+ a = [ 1 1 ]
+ [ -0.25, -0.5 ]
+
+ >>> b = np.array([0.5, 0.5])
+ >>> a = np.array([[1, 1], [-0.25, -0.5]])
+
+ Only `a` is more than 1-D. To make it compatible for
+ broadcasting with the frequencies, we extend it with a trivial dimension
+ in the call to `freqz`:
+
+ >>> w, h = signal.freqz(b, a[..., np.newaxis], worN=1024)
+ >>> w.shape
+ (1024,)
+ >>> h.shape
+ (2, 1024)
+
+ """
+ xp = array_namespace(b, a)
+
+ b, a = map(xp.asarray, (b, a))
+ if xp.isdtype(a.dtype, 'integral'):
+ a = xp.astype(a, xp_default_dtype(xp))
+ res_dtype = xp.result_type(b, a)
+ real_dtype = _real_dtype_for_complex(res_dtype, xp=xp)
+
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ if worN is None:
+ # For backwards compatibility
+ worN = 512
+
+ h = None
+
+ if _is_int_type(worN):
+ N = operator.index(worN)
+ del worN
+ if N < 0:
+ raise ValueError(f'worN must be nonnegative, got {N}')
+ lastpoint = 2 * pi if whole else pi
+ # if include_nyquist is true and whole is false, w should
+ # include end point
+ w = xp.linspace(0, lastpoint, N,
+ endpoint=include_nyquist and not whole, dtype=real_dtype)
+ n_fft = N if whole else 2 * (N - 1) if include_nyquist else 2 * N
+ if (xp_size(a) == 1 and (b.ndim == 1 or (b.shape[-1] == 1))
+ and n_fft >= b.shape[0]
+ and n_fft > 0): # TODO: review threshold acc. to benchmark?
+
+ if (xp.isdtype(b.dtype, "real floating") and
+ xp.isdtype(a.dtype, "real floating")
+ ):
+ fft_func = sp_fft.rfft
+ else:
+ fft_func = sp_fft.fft
+
+ h = fft_func(b, n=n_fft, axis=0)
+ h = h[:min(N, h.shape[0]), ...]
+ h /= a
+
+ if fft_func is sp_fft.rfft and whole:
+ # exclude DC and maybe Nyquist (no need to use axis_reverse
+ # here because we can build reversal with the truncation)
+ stop = None if n_fft % 2 == 1 else -1
+ h_flipped = xp.flip(h[1:stop, ...], axis=0)
+ h = xp.concat((h, xp.conj(h_flipped)))
+ if b.ndim > 1:
+ # Last axis of h has length 1, so drop it.
+ h = h[..., 0]
+ # Move the first axis of h to the end.
+ h = xp.moveaxis(h, 0, -1)
+ else:
+ if isinstance(worN, complex):
+ # backwards compat
+ worN = worN.real
+ w = xpx.atleast_nd(xp.asarray(worN, dtype=res_dtype), ndim=1, xp=xp)
+ if xp.isdtype(w.dtype, 'integral'):
+ w = xp.astype(w, xp_default_dtype(xp))
+ del worN
+ w = 2 * pi * w / fs
+
+ if h is None: # still need to compute using freqs w
+ zm1 = xp.exp(-1j * w)
+ h = (_pu.npp_polyval(zm1, b, tensor=False, xp=xp) /
+ _pu.npp_polyval(zm1, a, tensor=False, xp=xp))
+
+ w = w * (fs / (2 * pi))
+
+ if plot is not None:
+ plot(w, h)
+
+ return w, h
+
+
+def freqz_zpk(z, p, k, worN=512, whole=False, fs=2*pi):
+ r"""
+ Compute the frequency response of a digital filter in ZPK form.
+
+ Given the Zeros, Poles and Gain of a digital filter, compute its frequency
+ response:
+
+ :math:`H(z)=k \prod_i (z - Z[i]) / \prod_j (z - P[j])`
+
+ where :math:`k` is the `gain`, :math:`Z` are the `zeros` and :math:`P` are
+ the `poles`.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeroes of a linear filter
+ p : array_like
+ Poles of a linear filter
+ k : scalar
+ Gain of a linear filter
+ worN : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512).
+
+ If an array_like, compute the response at the frequencies given.
+ These are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs. Ignored if w is array_like.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which `h` was computed, in the same units as `fs`.
+ By default, `w` is normalized to the range [0, pi) (radians/sample).
+ h : ndarray
+ The frequency response, as complex numbers.
+
+ See Also
+ --------
+ freqs : Compute the frequency response of an analog filter in TF form
+ freqs_zpk : Compute the frequency response of an analog filter in ZPK form
+ freqz : Compute the frequency response of a digital filter in TF form
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ Examples
+ --------
+ Design a 4th-order digital Butterworth filter with cut-off of 100 Hz in a
+ system with sample rate of 1000 Hz, and plot the frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> z, p, k = signal.butter(4, 100, output='zpk', fs=1000)
+ >>> w, h = signal.freqz_zpk(z, p, k, fs=1000)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> ax1 = fig.add_subplot(1, 1, 1)
+ >>> ax1.set_title('Digital filter frequency response')
+
+ >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b')
+ >>> ax1.set_ylabel('Amplitude [dB]', color='b')
+ >>> ax1.set_xlabel('Frequency [Hz]')
+ >>> ax1.grid(True)
+
+ >>> ax2 = ax1.twinx()
+ >>> phase = np.unwrap(np.angle(h))
+ >>> ax2.plot(w, phase, 'g')
+ >>> ax2.set_ylabel('Phase [rad]', color='g')
+
+ >>> plt.axis('tight')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(z, p)
+ z, p = map(xp.asarray, (z, p))
+
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+ res_dtype = xp.result_type(z, p)
+ res_dtype = xp.float64 if res_dtype in (xp.float64, xp.complex128) else xp.float32
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ if whole:
+ lastpoint = 2 * pi
+ else:
+ lastpoint = pi
+
+ if worN is None:
+ # For backwards compatibility
+ w = xp.linspace(0, lastpoint, 512, endpoint=False, dtype=res_dtype)
+ elif _is_int_type(worN):
+ w = xp.linspace(0, lastpoint, worN, endpoint=False, dtype=res_dtype)
+ else:
+ w = xp.asarray(worN)
+ if xp.isdtype(w.dtype, 'integral'):
+ w = xp.astype(w, xp_default_dtype(xp))
+ w = xpx.atleast_nd(w, ndim=1, xp=xp)
+ w = 2 * pi * w / fs
+
+ zm1 = xp.exp(1j * w)
+ func = _pu.npp_polyvalfromroots
+ h = xp.asarray(k, dtype=res_dtype) * func(zm1, z, xp=xp) / func(zm1, p, xp=xp)
+
+ w = w*(fs/(2*pi))
+
+ return w, h
+
+
+def group_delay(system, w=512, whole=False, fs=2*pi):
+ r"""Compute the group delay of a digital filter.
+
+ The group delay measures by how many samples amplitude envelopes of
+ various spectral components of a signal are delayed by a filter.
+ It is formally defined as the derivative of continuous (unwrapped) phase::
+
+ d jw
+ D(w) = - -- arg H(e)
+ dw
+
+ Parameters
+ ----------
+ system : tuple of array_like (b, a)
+ Numerator and denominator coefficients of a filter transfer function.
+ w : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512).
+
+ If an array_like, compute the delay at the frequencies given. These
+ are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs. Ignored if w is array_like.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which group delay was computed, in the same units
+ as `fs`. By default, `w` is normalized to the range [0, pi)
+ (radians/sample).
+ gd : ndarray
+ The group delay.
+
+ See Also
+ --------
+ freqz : Frequency response of a digital filter
+
+ Notes
+ -----
+ The similar function in MATLAB is called `grpdelay`.
+
+ If the transfer function :math:`H(z)` has zeros or poles on the unit
+ circle, the group delay at corresponding frequencies is undefined.
+ When such a case arises the warning is raised and the group delay
+ is set to 0 at those frequencies.
+
+ For the details of numerical computation of the group delay refer to [1]_ or [2]_.
+
+ .. versionadded:: 0.16.0
+
+ References
+ ----------
+ .. [1] Richard G. Lyons, "Understanding Digital Signal Processing,
+ 3rd edition", p. 830.
+ .. [2] Julius O. Smith III, "Numerical Computation of Group Delay",
+ in "Introduction to Digital Filters with Audio Applications",
+ online book, 2007,
+ https://ccrma.stanford.edu/~jos/fp/Numerical_Computation_Group_Delay.html
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> b, a = signal.iirdesign(0.1, 0.3, 5, 50, ftype='cheby1')
+ >>> w, gd = signal.group_delay((b, a))
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.title('Digital filter group delay')
+ >>> plt.plot(w, gd)
+ >>> plt.ylabel('Group delay [samples]')
+ >>> plt.xlabel('Frequency [rad/sample]')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(*system, w)
+ b, a = map(np.atleast_1d, system)
+
+ if w is None:
+ # For backwards compatibility
+ w = 512
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ if _is_int_type(w):
+ if whole:
+ w = np.linspace(0, 2 * pi, w, endpoint=False)
+ else:
+ w = np.linspace(0, pi, w, endpoint=False)
+ else:
+ w = np.atleast_1d(w)
+ w = 2*pi*w/fs
+
+ c = np.convolve(b, np.conjugate(a[::-1]))
+ cr = c * np.arange(c.size)
+ z = np.exp(-1j * w)
+ num = np.polyval(cr[::-1], z)
+ den = np.polyval(c[::-1], z)
+ gd = np.real(num / den) - a.size + 1
+ singular = ~np.isfinite(gd)
+ near_singular = np.absolute(den) < 10 * EPSILON
+
+ if np.any(singular):
+ gd[singular] = 0
+ warnings.warn(
+ "The group delay is singular at frequencies "
+ f"[{', '.join(f'{ws:.3f}' for ws in w[singular])}], setting to 0",
+ stacklevel=2
+ )
+
+ elif np.any(near_singular):
+ warnings.warn(
+ "The filter's denominator is extremely small at frequencies "
+ f"[{', '.join(f'{ws:.3f}' for ws in w[near_singular])}], "
+ "around which a singularity may be present",
+ stacklevel=2
+ )
+
+ w = w * (fs / (2 * xp.pi))
+
+ return xp.asarray(w), xp.asarray(gd)
+
+
+def _validate_sos(sos, xp=None):
+ """Helper to validate a SOS input"""
+ if xp is None:
+ xp = np # backcompat, cf sosfilt, sosfiltfilt
+
+ sos = xp.asarray(sos)
+ sos = xpx.atleast_nd(sos, ndim=2, xp=xp)
+ if sos.ndim != 2:
+ raise ValueError('sos array must be 2D')
+ n_sections, m = sos.shape
+ if m != 6:
+ raise ValueError('sos array must be shape (n_sections, 6)')
+ if not xp.all(sos[:, 3] == 1):
+ raise ValueError('sos[:, 3] should be all ones')
+ return sos, n_sections
+
+
+def freqz_sos(sos, worN=512, whole=False, fs=2*pi):
+ r"""
+ Compute the frequency response of a digital filter in SOS format.
+
+ Given `sos`, an array with shape (n, 6) of second order sections of
+ a digital filter, compute the frequency response of the system function::
+
+ B0(z) B1(z) B{n-1}(z)
+ H(z) = ----- * ----- * ... * ---------
+ A0(z) A1(z) A{n-1}(z)
+
+ for z = exp(omega*1j), where B{k}(z) and A{k}(z) are numerator and
+ denominator of the transfer function of the k-th second order section.
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. Each row corresponds to a second-order
+ section, with the first three columns providing the numerator
+ coefficients and the last three providing the denominator
+ coefficients.
+ worN : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512). Using a number that is fast for FFT computations can result
+ in faster computations (see Notes of `freqz`).
+
+ If an array_like, compute the response at the frequencies given (must
+ be 1-D). These are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which `h` was computed, in the same units as `fs`.
+ By default, `w` is normalized to the range [0, pi) (radians/sample).
+ h : ndarray
+ The frequency response, as complex numbers.
+
+ See Also
+ --------
+ freqz, sosfilt, sosfreqz
+
+ Notes
+ -----
+ This function used to be called ``sosfreqz`` in older versions (≥ 0.19.0)
+
+ .. versionadded:: 1.15.0
+
+ Examples
+ --------
+ Design a 15th-order bandpass filter in SOS format.
+
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> sos = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass',
+ ... output='sos')
+
+ Compute the frequency response at 1500 points from DC to Nyquist.
+
+ >>> w, h = signal.freqz_sos(sos, worN=1500)
+
+ Plot the response.
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.subplot(2, 1, 1)
+ >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5))
+ >>> plt.plot(w/np.pi, db)
+ >>> plt.ylim(-75, 5)
+ >>> plt.grid(True)
+ >>> plt.yticks([0, -20, -40, -60])
+ >>> plt.ylabel('Gain [dB]')
+ >>> plt.title('Frequency Response')
+ >>> plt.subplot(2, 1, 2)
+ >>> plt.plot(w/np.pi, np.angle(h))
+ >>> plt.grid(True)
+ >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi],
+ ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$'])
+ >>> plt.ylabel('Phase [rad]')
+ >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)')
+ >>> plt.show()
+
+ If the same filter is implemented as a single transfer function,
+ numerical error corrupts the frequency response:
+
+ >>> b, a = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass',
+ ... output='ba')
+ >>> w, h = signal.freqz(b, a, worN=1500)
+ >>> plt.subplot(2, 1, 1)
+ >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5))
+ >>> plt.plot(w/np.pi, db)
+ >>> plt.ylim(-75, 5)
+ >>> plt.grid(True)
+ >>> plt.yticks([0, -20, -40, -60])
+ >>> plt.ylabel('Gain [dB]')
+ >>> plt.title('Frequency Response')
+ >>> plt.subplot(2, 1, 2)
+ >>> plt.plot(w/np.pi, np.angle(h))
+ >>> plt.grid(True)
+ >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi],
+ ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$'])
+ >>> plt.ylabel('Phase [rad]')
+ >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(sos)
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ sos, n_sections = _validate_sos(sos, xp)
+ if n_sections == 0:
+ raise ValueError('Cannot compute frequencies with no sections')
+ h = 1.
+ for j in range(sos.shape[0]):
+ row = sos[j, :]
+ w, rowh = freqz(row[:3], row[3:], worN=worN, whole=whole, fs=fs)
+ h *= rowh
+ return w, h
+
+
+def sosfreqz(*args, **kwargs):
+ """
+ Compute the frequency response of a digital filter in SOS format (legacy).
+
+ .. legacy:: function
+
+ This function is an alias, provided for backward compatibility.
+ New code should use the function :func:`scipy.signal.freqz_sos`.
+ This function became obsolete from version 1.15.0.
+
+ """ # numpydoc ignore=RT01
+ return freqz_sos(*args, **kwargs)
+
+
+def _cplxreal(z, tol=None):
+ """
+ Split into complex and real parts, combining conjugate pairs.
+
+ The 1-D input vector `z` is split up into its complex (`zc`) and real (`zr`)
+ elements. Every complex element must be part of a complex-conjugate pair,
+ which are combined into a single number (with positive imaginary part) in
+ the output. Two complex numbers are considered a conjugate pair if their
+ real and imaginary parts differ in magnitude by less than ``tol * abs(z)``.
+
+ Parameters
+ ----------
+ z : array_like
+ Vector of complex numbers to be sorted and split
+ tol : float, optional
+ Relative tolerance for testing realness and conjugate equality.
+ Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for
+ float64)
+
+ Returns
+ -------
+ zc : ndarray
+ Complex elements of `z`, with each pair represented by a single value
+ having positive imaginary part, sorted first by real part, and then
+ by magnitude of imaginary part. The pairs are averaged when combined
+ to reduce error.
+ zr : ndarray
+ Real elements of `z` (those having imaginary part less than
+ `tol` times their magnitude), sorted by value.
+
+ Raises
+ ------
+ ValueError
+ If there are any complex numbers in `z` for which a conjugate
+ cannot be found.
+
+ See Also
+ --------
+ _cplxpair
+
+ Examples
+ --------
+ >>> from scipy.signal._filter_design import _cplxreal
+ >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j]
+ >>> zc, zr = _cplxreal(a)
+ >>> print(zc)
+ [ 1.+1.j 2.+1.j 2.+1.j 2.+2.j]
+ >>> print(zr)
+ [ 1. 3. 4.]
+ """
+
+ z = np.atleast_1d(z)
+ if z.size == 0:
+ return z, z
+ elif z.ndim != 1:
+ raise ValueError('_cplxreal only accepts 1-D input')
+
+ if tol is None:
+ # Get tolerance from dtype of input
+ tol = 100 * np.finfo((1.0 * z).dtype).eps
+
+ # Sort by real part, magnitude of imaginary part (speed up further sorting)
+ z = z[np.lexsort((abs(z.imag), z.real))]
+
+ # Split reals from conjugate pairs
+ real_indices = abs(z.imag) <= tol * abs(z)
+ zr = z[real_indices].real
+
+ if len(zr) == len(z):
+ # Input is entirely real
+ return np.array([]), zr
+
+ # Split positive and negative halves of conjugates
+ z = z[~real_indices]
+ zp = z[z.imag > 0]
+ zn = z[z.imag < 0]
+
+ if len(zp) != len(zn):
+ raise ValueError('Array contains complex value with no matching '
+ 'conjugate.')
+
+ # Find runs of (approximately) the same real part
+ same_real = np.diff(zp.real) <= tol * abs(zp[:-1])
+ diffs = np.diff(np.concatenate(([0], same_real, [0])))
+ run_starts = np.nonzero(diffs > 0)[0]
+ run_stops = np.nonzero(diffs < 0)[0]
+
+ # Sort each run by their imaginary parts
+ for i in range(len(run_starts)):
+ start = run_starts[i]
+ stop = run_stops[i] + 1
+ for chunk in (zp[start:stop], zn[start:stop]):
+ chunk[...] = chunk[np.lexsort([abs(chunk.imag)])]
+
+ # Check that negatives match positives
+ if any(abs(zp - zn.conj()) > tol * abs(zn)):
+ raise ValueError('Array contains complex value with no matching '
+ 'conjugate.')
+
+ # Average out numerical inaccuracy in real vs imag parts of pairs
+ zc = (zp + zn.conj()) / 2
+
+ return zc, zr
+
+
+def _cplxpair(z, tol=None):
+ """
+ Sort into pairs of complex conjugates.
+
+ Complex conjugates in `z` are sorted by increasing real part. In each
+ pair, the number with negative imaginary part appears first.
+
+ If pairs have identical real parts, they are sorted by increasing
+ imaginary magnitude.
+
+ Two complex numbers are considered a conjugate pair if their real and
+ imaginary parts differ in magnitude by less than ``tol * abs(z)``. The
+ pairs are forced to be exact complex conjugates by averaging the positive
+ and negative values.
+
+ Purely real numbers are also sorted, but placed after the complex
+ conjugate pairs. A number is considered real if its imaginary part is
+ smaller than `tol` times the magnitude of the number.
+
+ Parameters
+ ----------
+ z : array_like
+ 1-D input array to be sorted.
+ tol : float, optional
+ Relative tolerance for testing realness and conjugate equality.
+ Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for
+ float64)
+
+ Returns
+ -------
+ y : ndarray
+ Complex conjugate pairs followed by real numbers.
+
+ Raises
+ ------
+ ValueError
+ If there are any complex numbers in `z` for which a conjugate
+ cannot be found.
+
+ See Also
+ --------
+ _cplxreal
+
+ Examples
+ --------
+ >>> from scipy.signal._filter_design import _cplxpair
+ >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j]
+ >>> z = _cplxpair(a)
+ >>> print(z)
+ [ 1.-1.j 1.+1.j 2.-1.j 2.+1.j 2.-1.j 2.+1.j 2.-2.j 2.+2.j 1.+0.j
+ 3.+0.j 4.+0.j]
+ """
+
+ z = np.atleast_1d(z)
+ if z.size == 0 or np.isrealobj(z):
+ return np.sort(z)
+
+ if z.ndim != 1:
+ raise ValueError('z must be 1-D')
+
+ zc, zr = _cplxreal(z, tol)
+
+ # Interleave complex values and their conjugates, with negative imaginary
+ # parts first in each pair
+ zc = np.dstack((zc.conj(), zc)).flatten()
+ z = np.append(zc, zr)
+ return z
+
+
+def tf2zpk(b, a):
+ r"""Return zero, pole, gain (z, p, k) representation from a numerator,
+ denominator representation of a linear filter.
+
+ Parameters
+ ----------
+ b : array_like, shape (M,)
+ Numerator polynomial coefficients. Must be 1-D.
+ a : array_like, shape (N,)
+ Denominator polynomial coefficients. Must be 1-D.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transfer function.
+ p : ndarray
+ Poles of the transfer function.
+ k : float
+ System gain.
+
+ Notes
+ -----
+ If some values of `b` are too close to 0, they are removed. In that case,
+ a BadCoefficients warning is emitted.
+
+ The `b` and `a` arrays are interpreted as coefficients for positive,
+ descending powers of the transfer function variable. So the inputs
+ :math:`b = [b_0, b_1, ..., b_M]` and :math:`a =[a_0, a_1, ..., a_N]`
+ can represent an analog filter of the form:
+
+ .. math::
+
+ H(s) = \frac
+ {b_0 s^M + b_1 s^{(M-1)} + \cdots + b_M}
+ {a_0 s^N + a_1 s^{(N-1)} + \cdots + a_N}
+
+ or a discrete-time filter of the form:
+
+ .. math::
+
+ H(z) = \frac
+ {b_0 z^M + b_1 z^{(M-1)} + \cdots + b_M}
+ {a_0 z^N + a_1 z^{(N-1)} + \cdots + a_N}
+
+ This "positive powers" form is found more commonly in controls
+ engineering. If `M` and `N` are equal (which is true for all filters
+ generated by the bilinear transform), then this happens to be equivalent
+ to the "negative powers" discrete-time form preferred in DSP:
+
+ .. math::
+
+ H(z) = \frac
+ {b_0 + b_1 z^{-1} + \cdots + b_M z^{-M}}
+ {a_0 + a_1 z^{-1} + \cdots + a_N z^{-N}}
+
+ Although this is true for common filters, remember that this is not true
+ in the general case. If `M` and `N` are not equal, the discrete-time
+ transfer function coefficients must first be converted to the "positive
+ powers" form before finding the poles and zeros.
+
+ Examples
+ --------
+ Find the zeroes, poles and gain of
+ a filter with the transfer function
+
+ .. math::
+
+ H(s) = \frac{3s^2}{s^2 + 5s + 13}
+
+ >>> from scipy.signal import tf2zpk
+ >>> tf2zpk([3, 0, 0], [1, 5, 13])
+ ( array([ 0. , 0. ]),
+ array([ -2.5+2.59807621j , -2.5-2.59807621j]),
+ 3.0)
+ """
+ xp = array_namespace(b, a)
+ b, a = normalize(b, a)
+
+ a, b = xp_promote(a, b, xp=xp, force_floating=True)
+
+ k = b[0]
+ b = b / b[0]
+ z = _pu.polyroots(b, xp=xp)
+ p = _pu.polyroots(a, xp=xp)
+ return z, p, k
+
+
+def zpk2tf(z, p, k):
+ r"""
+ Return polynomial transfer function representation from zeros and poles.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the transfer function.
+ p : array_like
+ Poles of the transfer function.
+ k : float
+ System gain.
+
+ Returns
+ -------
+ b : ndarray
+ Numerator polynomial coefficients.
+ a : ndarray
+ Denominator polynomial coefficients.
+
+ Examples
+ --------
+ Find the polynomial representation of a transfer function H(s)
+ using its 'zpk' (Zero-Pole-Gain) representation.
+
+ .. math::
+
+ H(z) = 5 \frac
+ { (s - 2)(s - 6) }
+ { (s - 1)(s - 8) }
+
+ >>> from scipy.signal import zpk2tf
+ >>> z = [2, 6]
+ >>> p = [1, 8]
+ >>> k = 5
+ >>> zpk2tf(z, p, k)
+ ( array([ 5., -40., 60.]), array([ 1., -9., 8.]))
+ """
+ xp = array_namespace(z, p)
+ z, p = map(xp.asarray, (z, p))
+ k = xp.asarray(k, dtype=xp.result_type(xp.real(z), xp.real(p), k))
+ if xp.isdtype(k.dtype, "integral"):
+ k = xp.astype(k, xp.float64)
+
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ k = xpx.atleast_nd(k, ndim=1, xp=xp)
+
+ if z.ndim > 1:
+ temp = _pu.poly(z[0, ...], xp=xp)
+ result_dtype = xp_result_type(temp, k, force_floating=True, xp=xp)
+ b = xp.empty((z.shape[0], z.shape[1] + 1), dtype=result_dtype)
+ if k.shape[0] == 1:
+ k = [k[0]] * z.shape[0]
+ for i in range(z.shape[0]):
+ k_i = xp.asarray(k[i], dtype=result_dtype)
+ poly_i = xp.asarray(_pu.poly(z[i, ...], xp=xp), dtype=result_dtype)
+ b_i = k_i * poly_i
+ b = xpx.at(b)[i, ...].set(b_i)
+ else:
+ # Use xp.multiply to work around torch type promotion
+ # non-compliance for operations between 0d and higher
+ # dimensional arrays.
+ b = xp.multiply(k, _pu.poly(z, xp=xp))
+
+ a = _pu.poly(p, xp=xp)
+ a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
+
+ return b, a
+
+
+def tf2sos(b, a, pairing=None, *, analog=False):
+ r"""
+ Return second-order sections from transfer function representation.
+
+ Parameters
+ ----------
+ b : array_like, shape (M,)
+ Numerator polynomial coefficients. Must be 1-D.
+ a : array_like, shape (N,)
+ Denominator polynomial coefficients. Must be 1-D.
+ pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional
+ The method to use to combine pairs of poles and zeros into sections.
+ See `zpk2sos` for information and restrictions on `pairing` and
+ `analog` arguments.
+ analog : bool, optional
+ If True, system is analog, otherwise discrete.
+
+ .. versionadded:: 1.8.0
+
+ Returns
+ -------
+ sos : ndarray
+ Array of second-order filter coefficients, with shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ See Also
+ --------
+ zpk2sos, sosfilt
+
+ Notes
+ -----
+ It is generally discouraged to convert from TF to SOS format, since doing
+ so usually will not improve numerical precision errors. Instead, consider
+ designing filters in ZPK format and converting directly to SOS. TF is
+ converted to SOS by first converting to ZPK format, then converting
+ ZPK to SOS.
+
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+ Find the 'sos' (second-order sections) of the transfer function H(s)
+ using its polynomial representation.
+
+ .. math::
+
+ H(s) = \frac{s^2 - 3.5s - 2}{s^4 + 3s^3 - 15s^2 - 19s + 30}
+
+ >>> from scipy.signal import tf2sos
+ >>> tf2sos([1, -3.5, -2], [1, 3, -15, -19, 30], analog=True)
+ array([[ 0. , 0. , 1. , 1. , 2. , -15. ],
+ [ 1. , -3.5, -2. , 1. , 1. , -2. ]])
+ """
+ return zpk2sos(*tf2zpk(b, a), pairing=pairing, analog=analog)
+
+
+def sos2tf(sos):
+ r"""
+ Return a single transfer function from a series of second-order sections.
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ Returns
+ -------
+ b : ndarray
+ Numerator polynomial coefficients.
+ a : ndarray
+ Denominator polynomial coefficients.
+
+ Notes
+ -----
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+ Find the polynomial representation of an elliptic filter
+ using its 'sos' (second-order sections) format.
+
+ >>> from scipy.signal import sos2tf
+ >>> from scipy import signal
+ >>> sos = signal.ellip(1, 0.001, 50, 0.1, output='sos')
+ >>> sos2tf(sos)
+ ( array([0.91256522, 0.91256522, 0. ]),
+ array([1. , 0.82513043, 0. ]))
+ """
+ xp = array_namespace(sos)
+ sos = xp.asarray(sos)
+
+ result_type = sos.dtype
+ if xp.isdtype(result_type, 'integral'):
+ result_type = xp_default_dtype(xp)
+
+ b = xp.asarray([1], dtype=result_type)
+ a = xp.asarray([1], dtype=result_type)
+
+ n_sections = sos.shape[0]
+ for section in range(n_sections):
+ b = _pu.polymul(b, sos[section, :3], xp=xp)
+ a = _pu.polymul(a, sos[section, 3:], xp=xp)
+ return b, a
+
+
+def sos2zpk(sos):
+ """
+ Return zeros, poles, and gain of a series of second-order sections.
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transfer function.
+ p : ndarray
+ Poles of the transfer function.
+ k : float
+ System gain.
+
+ Notes
+ -----
+ The number of zeros and poles returned will be ``n_sections * 2``
+ even if some of these are (effectively) zero.
+
+ .. versionadded:: 0.16.0
+ """
+ xp = array_namespace(sos)
+ sos = xp.asarray(sos)
+
+ n_sections = sos.shape[0]
+ z = xp.zeros(n_sections*2, dtype=xp.complex128)
+ p = xp.zeros(n_sections*2, dtype=xp.complex128)
+ k = 1.
+ for section in range(n_sections):
+ zpk = tf2zpk(sos[section, :3], sos[section, 3:])
+ z = xpx.at(z, slice(2*section, 2*section + zpk[0].shape[0])).set(zpk[0])
+ p = xpx.at(p, slice(2*section, 2*section + zpk[1].shape[0])).set(zpk[1])
+ k *= zpk[2]
+ return z, p, k
+
+
+def _nearest_real_complex_idx(fro, to, which):
+ """Get the next closest real or complex element based on distance"""
+ assert which in ('real', 'complex', 'any')
+ order = np.argsort(np.abs(fro - to))
+ if which == 'any':
+ return order[0]
+ else:
+ mask = np.isreal(fro[order])
+ if which == 'complex':
+ mask = ~mask
+ return order[np.nonzero(mask)[0][0]]
+
+
+def _single_zpksos(z, p, k):
+ """Create one second-order section from up to two zeros and poles"""
+ sos = np.zeros(6)
+ b, a = zpk2tf(z, p, k)
+ sos[3-len(b):3] = b
+ sos[6-len(a):6] = a
+ return sos
+
+
+def zpk2sos(z, p, k, pairing=None, *, analog=False):
+ """Return second-order sections from zeros, poles, and gain of a system.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the transfer function.
+ p : array_like
+ Poles of the transfer function.
+ k : float
+ System gain.
+ pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional
+ The method to use to combine pairs of poles and zeros into sections.
+ If analog is False and pairing is None, pairing is set to 'nearest';
+ if analog is True, pairing must be 'minimal', and is set to that if
+ it is None.
+ analog : bool, optional
+ If True, system is analog, otherwise discrete.
+
+ .. versionadded:: 1.8.0
+
+ Returns
+ -------
+ sos : ndarray
+ Array of second-order filter coefficients, with shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ See Also
+ --------
+ sosfilt
+
+ Notes
+ -----
+ The algorithm used to convert ZPK to SOS format is designed to
+ minimize errors due to numerical precision issues. The pairing
+ algorithm attempts to minimize the peak gain of each biquadratic
+ section. This is done by pairing poles with the nearest zeros, starting
+ with the poles closest to the unit circle for discrete-time systems, and
+ poles closest to the imaginary axis for continuous-time systems.
+
+ ``pairing='minimal'`` outputs may not be suitable for `sosfilt`,
+ and ``analog=True`` outputs will never be suitable for `sosfilt`.
+
+ *Algorithms*
+
+ The steps in the ``pairing='nearest'``, ``pairing='keep_odd'``,
+ and ``pairing='minimal'`` algorithms are mostly shared. The
+ ``'nearest'`` algorithm attempts to minimize the peak gain, while
+ ``'keep_odd'`` minimizes peak gain under the constraint that
+ odd-order systems should retain one section as first order.
+ ``'minimal'`` is similar to ``'keep_odd'``, but no additional
+ poles or zeros are introduced
+
+ The algorithm steps are as follows:
+
+ As a pre-processing step for ``pairing='nearest'``,
+ ``pairing='keep_odd'``, add poles or zeros to the origin as
+ necessary to obtain the same number of poles and zeros for
+ pairing. If ``pairing == 'nearest'`` and there are an odd number
+ of poles, add an additional pole and a zero at the origin.
+
+ The following steps are then iterated over until no more poles or
+ zeros remain:
+
+ 1. Take the (next remaining) pole (complex or real) closest to the
+ unit circle (or imaginary axis, for ``analog=True``) to
+ begin a new filter section.
+ 2. If the pole is real and there are no other remaining real poles [#]_,
+ add the closest real zero to the section and leave it as a first
+ order section. Note that after this step we are guaranteed to be
+ left with an even number of real poles, complex poles, real zeros,
+ and complex zeros for subsequent pairing iterations.
+ 3. Else:
+
+ 1. If the pole is complex and the zero is the only remaining real
+ zero*, then pair the pole with the *next* closest zero
+ (guaranteed to be complex). This is necessary to ensure that
+ there will be a real zero remaining to eventually create a
+ first-order section (thus keeping the odd order).
+ 2. Else pair the pole with the closest remaining zero (complex or real).
+ 3. Proceed to complete the second-order section by adding another
+ pole and zero to the current pole and zero in the section:
+
+ 1. If the current pole and zero are both complex, add their conjugates.
+ 2. Else if the pole is complex and the zero is real, add the
+ conjugate pole and the next closest real zero.
+ 3. Else if the pole is real and the zero is complex, add the
+ conjugate zero and the real pole closest to those zeros.
+ 4. Else (we must have a real pole and real zero) add the next
+ real pole closest to the unit circle, and then add the real
+ zero closest to that pole.
+
+ .. [#] This conditional can only be met for specific odd-order inputs
+ with the ``pairing = 'keep_odd'`` or ``'minimal'`` methods.
+
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+
+ Design a 6th order low-pass elliptic digital filter for a system with a
+ sampling rate of 8000 Hz that has a pass-band corner frequency of
+ 1000 Hz. The ripple in the pass-band should not exceed 0.087 dB, and
+ the attenuation in the stop-band should be at least 90 dB.
+
+ In the following call to `ellip`, we could use ``output='sos'``,
+ but for this example, we'll use ``output='zpk'``, and then convert
+ to SOS format with `zpk2sos`:
+
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> z, p, k = signal.ellip(6, 0.087, 90, 1000/(0.5*8000), output='zpk')
+
+ Now convert to SOS format.
+
+ >>> sos = signal.zpk2sos(z, p, k)
+
+ The coefficients of the numerators of the sections:
+
+ >>> sos[:, :3]
+ array([[0.0014152 , 0.00248677, 0.0014152 ],
+ [1. , 0.72976874, 1. ],
+ [1. , 0.17607852, 1. ]])
+
+ The symmetry in the coefficients occurs because all the zeros are on the
+ unit circle.
+
+ The coefficients of the denominators of the sections:
+
+ >>> sos[:, 3:]
+ array([[ 1. , -1.32544025, 0.46989976],
+ [ 1. , -1.26118294, 0.62625924],
+ [ 1. , -1.2570723 , 0.8619958 ]])
+
+ The next example shows the effect of the `pairing` option. We have a
+ system with three poles and three zeros, so the SOS array will have
+ shape (2, 6). The means there is, in effect, an extra pole and an extra
+ zero at the origin in the SOS representation.
+
+ >>> z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j])
+ >>> p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j])
+
+ With ``pairing='nearest'`` (the default), we obtain
+
+ >>> signal.zpk2sos(z1, p1, 1)
+ array([[ 1. , 1. , 0.5 , 1. , -0.75, 0. ],
+ [ 1. , 1. , 0. , 1. , -1.6 , 0.65]])
+
+ The first section has the zeros {-0.5-0.05j, -0.5+0.5j} and the poles
+ {0, 0.75}, and the second section has the zeros {-1, 0} and poles
+ {0.8+0.1j, 0.8-0.1j}. Note that the extra pole and zero at the origin
+ have been assigned to different sections.
+
+ With ``pairing='keep_odd'``, we obtain:
+
+ >>> signal.zpk2sos(z1, p1, 1, pairing='keep_odd')
+ array([[ 1. , 1. , 0. , 1. , -0.75, 0. ],
+ [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]])
+
+ The extra pole and zero at the origin are in the same section.
+ The first section is, in effect, a first-order section.
+
+ With ``pairing='minimal'``, the first-order section doesn't have
+ the extra pole and zero at the origin:
+
+ >>> signal.zpk2sos(z1, p1, 1, pairing='minimal')
+ array([[ 0. , 1. , 1. , 0. , 1. , -0.75],
+ [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]])
+
+ """
+ # TODO in the near future:
+ # 1. Add SOS capability to `filtfilt`, `freqz`, etc. somehow (#3259).
+ # 2. Make `decimate` use `sosfilt` instead of `lfilter`.
+ # 3. Make sosfilt automatically simplify sections to first order
+ # when possible. Note this might make `sosfiltfilt` a bit harder (ICs).
+ # 4. Further optimizations of the section ordering / pole-zero pairing.
+ # See the wiki for other potential issues.
+
+ xp = array_namespace(z, p)
+
+ # convert to numpy, convert back on exit XXX
+ z, p = map(np.asarray, (z, p))
+ k = np.asarray(k)
+
+ if pairing is None:
+ pairing = 'minimal' if analog else 'nearest'
+
+ valid_pairings = ['nearest', 'keep_odd', 'minimal']
+ if pairing not in valid_pairings:
+ raise ValueError(f'pairing must be one of {valid_pairings}, not {pairing}')
+
+ if analog and pairing != 'minimal':
+ raise ValueError('for analog zpk2sos conversion, '
+ 'pairing must be "minimal"')
+
+ if len(z) == len(p) == 0:
+ if not analog:
+ return xp.asarray(np.asarray([[k, 0., 0., 1., 0., 0.]]))
+ else:
+ return xp.asarray(np.asarray([[0., 0., k, 0., 0., 1.]]))
+
+ if pairing != 'minimal':
+ # ensure we have the same number of poles and zeros, and make copies
+ p = np.concatenate((p, np.zeros(max(len(z) - len(p), 0))))
+ z = np.concatenate((z, np.zeros(max(len(p) - len(z), 0))))
+ n_sections = (max(len(p), len(z)) + 1) // 2
+
+ if len(p) % 2 == 1 and pairing == 'nearest':
+ p = np.concatenate((p, [0.]))
+ z = np.concatenate((z, [0.]))
+ assert len(p) == len(z)
+ else:
+ if len(p) < len(z):
+ raise ValueError('for analog zpk2sos conversion, '
+ 'must have len(p)>=len(z)')
+
+ n_sections = (len(p) + 1) // 2
+
+ # Ensure we have complex conjugate pairs
+ # (note that _cplxreal only gives us one element of each complex pair):
+ z = np.concatenate(_cplxreal(z))
+ p = np.concatenate(_cplxreal(p))
+ if not np.isreal(k):
+ raise ValueError('k must be real')
+ k = k.real
+
+ if not analog:
+ # digital: "worst" is the closest to the unit circle
+ def idx_worst(p):
+ return np.argmin(np.abs(1 - np.abs(p)))
+ else:
+ # analog: "worst" is the closest to the imaginary axis
+ def idx_worst(p):
+ return np.argmin(np.abs(np.real(p)))
+
+ sos = np.zeros((n_sections, 6))
+
+ # Construct the system, reversing order so the "worst" are last
+ for si in range(n_sections-1, -1, -1):
+ # Select the next "worst" pole
+ p1_idx = idx_worst(p)
+ p1 = p[p1_idx]
+ p = np.delete(p, p1_idx)
+
+ # Pair that pole with a zero
+
+ if np.isreal(p1) and np.isreal(p).sum() == 0:
+ # Special case (1): last remaining real pole
+ if pairing != 'minimal':
+ z1_idx = _nearest_real_complex_idx(z, p1, 'real')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+ sos[si] = _single_zpksos([z1, 0], [p1, 0], 1)
+ elif len(z) > 0:
+ z1_idx = _nearest_real_complex_idx(z, p1, 'real')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+ sos[si] = _single_zpksos([z1], [p1], 1)
+ else:
+ sos[si] = _single_zpksos([], [p1], 1)
+
+ elif (len(p) + 1 == len(z)
+ and not np.isreal(p1)
+ and np.isreal(p).sum() == 1
+ and np.isreal(z).sum() == 1):
+
+ # Special case (2): there's one real pole and one real zero
+ # left, and an equal number of poles and zeros to pair up.
+ # We *must* pair with a complex zero
+
+ z1_idx = _nearest_real_complex_idx(z, p1, 'complex')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+ sos[si] = _single_zpksos([z1, z1.conj()], [p1, p1.conj()], 1)
+
+ else:
+ if np.isreal(p1):
+ prealidx = np.flatnonzero(np.isreal(p))
+ p2_idx = prealidx[idx_worst(p[prealidx])]
+ p2 = p[p2_idx]
+ p = np.delete(p, p2_idx)
+ else:
+ p2 = p1.conj()
+
+ # find closest zero
+ if len(z) > 0:
+ z1_idx = _nearest_real_complex_idx(z, p1, 'any')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+
+ if not np.isreal(z1):
+ sos[si] = _single_zpksos([z1, z1.conj()], [p1, p2], 1)
+ else:
+ if len(z) > 0:
+ z2_idx = _nearest_real_complex_idx(z, p1, 'real')
+ z2 = z[z2_idx]
+ assert np.isreal(z2)
+ z = np.delete(z, z2_idx)
+ sos[si] = _single_zpksos([z1, z2], [p1, p2], 1)
+ else:
+ sos[si] = _single_zpksos([z1], [p1, p2], 1)
+ else:
+ # no more zeros
+ sos[si] = _single_zpksos([], [p1, p2], 1)
+
+ assert len(p) == len(z) == 0 # we've consumed all poles and zeros
+ del p, z
+
+ # put gain in first sos
+ sos[0][:3] *= k
+ return xp.asarray(sos)
+
+
+def _align_nums(nums, xp):
+ """Aligns the shapes of multiple numerators.
+
+ Given an array of numerator coefficient arrays [[a_1, a_2,...,
+ a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator
+ arrays with zero's so that all numerators have the same length. Such
+ alignment is necessary for functions like 'tf2ss', which needs the
+ alignment when dealing with SIMO transfer functions.
+
+ Parameters
+ ----------
+ nums: array_like
+ Numerator or list of numerators. Not necessarily with same length.
+
+ Returns
+ -------
+ nums: array
+ The numerator. If `nums` input was a list of numerators then a 2-D
+ array with padded zeros for shorter numerators is returned. Otherwise
+ returns ``np.asarray(nums)``.
+ """
+ try:
+ # The statement can throw a ValueError if one
+ # of the numerators is a single digit and another
+ # is array-like e.g. if nums = [5, [1, 2, 3]]
+ nums = xp.asarray(nums)
+
+ if not xp.isdtype(nums.dtype, "numeric"):
+ raise ValueError("dtype of numerator is non-numeric")
+
+ return nums
+
+ except ValueError:
+ nums = [xpx.atleast_nd(xp.asarray(num), ndim=1) for num in nums]
+ max_width = max(xp_size(num) for num in nums)
+
+ # pre-allocate
+ aligned_nums = xp.zeros((len(nums), max_width))
+
+ # Create numerators with padded zeros
+ for index, num in enumerate(nums):
+ aligned_nums[index, -num.size:] = num
+
+ return aligned_nums
+
+
+def normalize(b, a):
+ """Normalize numerator/denominator of a continuous-time transfer function.
+
+ If values of `b` are too close to 0, they are removed. In that case, a
+ BadCoefficients warning is emitted.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator of the transfer function. Can be a 2-D array to normalize
+ multiple transfer functions.
+ a : array_like
+ Denominator of the transfer function. At most 1-D.
+
+ Returns
+ -------
+ num : array
+ The numerator of the normalized transfer function. At least a 1-D
+ array. A 2-D array if the input `num` is a 2-D array.
+ den : 1-D array
+ The denominator of the normalized transfer function.
+
+ Notes
+ -----
+ Coefficients for both the numerator and denominator should be specified in
+ descending exponent order (e.g., ``s^2 + 3s + 5`` would be represented as
+ ``[1, 3, 5]``).
+
+ Examples
+ --------
+ >>> from scipy.signal import normalize
+
+ Normalize the coefficients of the transfer function
+ ``(3*s^2 - 2*s + 5) / (2*s^2 + 3*s + 1)``:
+
+ >>> b = [3, -2, 5]
+ >>> a = [2, 3, 1]
+ >>> normalize(b, a)
+ (array([ 1.5, -1. , 2.5]), array([1. , 1.5, 0.5]))
+
+ A warning is generated if, for example, the first coefficient of
+ `b` is 0. In the following example, the result is as expected:
+
+ >>> import warnings
+ >>> with warnings.catch_warnings(record=True, action='always') as w:
+ ... num, den = normalize([0, 3, 6], [2, -5, 4])
+
+ >>> num
+ array([1.5, 3. ])
+ >>> den
+ array([ 1. , -2.5, 2. ])
+
+ >>> print(w[0].message)
+ Badly conditioned filter coefficients (numerator): the results may be meaningless
+
+ """
+ try:
+ xp = array_namespace(b, a)
+ except TypeError:
+ # object arrays, test_ltisys.py::TestSS2TF::test_simo_round_trip
+ xp = np_compat
+
+ den = xp.asarray(a)
+ den = xpx.atleast_nd(den, ndim=1, xp=xp)
+
+ num = xp.asarray(b)
+ num = xpx.atleast_nd(_align_nums(num, xp), ndim=2, xp=xp)
+
+ if den.ndim != 1:
+ raise ValueError("Denominator polynomial must be rank-1 array.")
+ if num.ndim > 2:
+ raise ValueError("Numerator polynomial must be rank-1 or"
+ " rank-2 array.")
+ if xp.all(den == 0):
+ raise ValueError("Denominator must have at least on nonzero element.")
+
+ # Trim leading zeros in denominator, leave at least one.
+ den = _pu._trim_zeros(den, 'f')
+
+ # Normalize transfer function
+ num, den = num / den[0], den / den[0]
+
+ # Count numerator columns that are all zero
+ leading_zeros = 0
+ for j in range(num.shape[-1]):
+ col = num[:, j]
+ if xp.all(xp.abs(col) <= 1e-14):
+ leading_zeros += 1
+ else:
+ break
+
+ # Trim leading zeros of numerator
+ if leading_zeros > 0:
+ warnings.warn("Badly conditioned filter coefficients (numerator): the "
+ "results may be meaningless",
+ BadCoefficients, stacklevel=2)
+ # Make sure at least one column remains
+ if leading_zeros == num.shape[1]:
+ leading_zeros -= 1
+ num = num[:, leading_zeros:]
+
+ # Squeeze first dimension if singular
+ if num.shape[0] == 1:
+ num = num[0, :]
+
+ return num, den
+
+
+def lp2lp(b, a, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a different frequency.
+
+ Return an analog low-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency, in
+ transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like, shape (M,)
+ Numerator polynomial coefficients. Must be 1-D.
+ a : array_like, shape (N,)
+ Denominator polynomial coefficients. Must be 1-D.
+ wo : float
+ Desired cutoff, as angular frequency (e.g. rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed low-pass filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed low-pass filter.
+
+ See Also
+ --------
+ lp2hp, lp2bp, lp2bs, bilinear
+ lp2lp_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s}{\omega_0}
+
+ Examples
+ --------
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.0])
+ >>> lp2 = signal.lti(*signal.lp2lp(lp.num, lp.den, 2))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_lp2, p_lp2 = lp2.bode(w)
+
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_lp2, label='Transformed Lowpass')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+
+ """
+ xp = array_namespace(a, b)
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ try:
+ wo = float(wo)
+ except TypeError:
+ wo = float(wo[0])
+ d = a.shape[0]
+ n = b.shape[0]
+ M = max((d, n))
+ pwo = wo ** xp.arange(M - 1, -1, -1, dtype=xp.float64)
+ start1 = max((n - d, 0))
+ start2 = max((d - n, 0))
+ b = b * pwo[start1] / pwo[start2:]
+ a = a * pwo[start1] / pwo[start1:]
+ return normalize(b, a)
+
+
+def _resize(a, new_shape, xp):
+ # https://github.com/numpy/numpy/blob/v2.2.4/numpy/_core/fromnumeric.py#L1535
+ a = xp.reshape(a, (-1,))
+
+ new_size = 1
+ for dim_length in new_shape:
+ new_size *= dim_length
+ if dim_length < 0:
+ raise ValueError(
+ 'all elements of `new_shape` must be non-negative'
+ )
+
+ if xp_size(a) == 0 or new_size == 0:
+ # First case must zero fill. The second would have repeats == 0.
+ return xp.zeros_like(a, shape=new_shape)
+
+ repeats = -(-new_size // xp_size(a)) # ceil division
+ a = xp.concat((a,) * repeats)[:new_size]
+
+ return xp.reshape(a, new_shape)
+
+
+def lp2hp(b, a, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a highpass filter.
+
+ Return an analog high-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency, in
+ transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like, shape (M,)
+ Numerator polynomial coefficients. Must be 1-D.
+ a : array_like, shape (N,)
+ Denominator polynomial coefficients. Must be 1-D.
+ wo : float
+ Desired cutoff, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed high-pass filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed high-pass filter.
+
+ See Also
+ --------
+ lp2lp, lp2bp, lp2bs, bilinear
+ lp2hp_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{\omega_0}{s}
+
+ This maintains symmetry of the lowpass and highpass responses on a
+ logarithmic scale.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.0])
+ >>> hp = signal.lti(*signal.lp2hp(lp.num, lp.den))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_hp, p_hp = hp.bode(w)
+
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_hp, label='Highpass')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+
+ """
+ xp = array_namespace(a, b)
+
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ try:
+ wo = float(wo)
+ except TypeError:
+ wo = float(wo[0])
+ d = a.shape[0]
+ n = b.shape[0]
+ if wo != 1:
+ pwo = wo ** xp.arange(max((d, n)), dtype=b.dtype)
+ else:
+ pwo = xp.ones(max((d, n)), dtype=b.dtype)
+ if d >= n:
+ outa = xp.flip(a) * pwo
+ outb = _resize(b, (d,), xp=xp)
+ outb = xpx.at(outb)[n:].set(0.0)
+ outb = xpx.at(outb)[:n].set(xp.flip(b) * pwo[:n])
+ else:
+ outb = xp.flip(b) * pwo
+ outa = _resize(a, (n,), xp=xp)
+ outa = xpx.at(outa)[d:].set(0.0)
+ outa = xpx.at(outa)[:d].set(xp.flip(a) * pwo[:d])
+
+ return normalize(outb, outa)
+
+
+def lp2bp(b, a, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandpass filter.
+
+ Return an analog band-pass filter with center frequency `wo` and
+ bandwidth `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, in transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like, shape (M,)
+ Numerator polynomial coefficients. Must be 1-D.
+ a : array_like, shape (N,)
+ Denominator polynomial coefficients. Must be 1-D.
+ wo : float
+ Desired passband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired passband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed band-pass filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed band-pass filter.
+
+ See Also
+ --------
+ lp2lp, lp2hp, lp2bs, bilinear
+ lp2bp_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}}
+
+ This is the "wideband" transformation, producing a passband with
+ geometric (log frequency) symmetry about `wo`.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.0])
+ >>> bp = signal.lti(*signal.lp2bp(lp.num, lp.den))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_bp, p_bp = bp.bode(w)
+
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_bp, label='Bandpass')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+ """
+ xp = array_namespace(a, b)
+
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ D = a.shape[0] - 1
+ N = b.shape[0] - 1
+ ma = max([N, D])
+ Np = N + ma
+ Dp = D + ma
+ bprime = xp.empty(Np + 1, dtype=b.dtype)
+ aprime = xp.empty(Dp + 1, dtype=a.dtype)
+ wosq = wo * wo
+ for j in range(Np + 1):
+ val = 0.0
+ for i in range(0, N + 1):
+ for k in range(0, i + 1):
+ if ma - i + 2 * k == j:
+ val += comb(i, k) * b[N - i] * (wosq) ** (i - k) / bw ** i
+ bprime = xpx.at(bprime, Np - j).set(val, xp=xp)
+ for j in range(Dp + 1):
+ val = 0.0
+ for i in range(0, D + 1):
+ for k in range(0, i + 1):
+ if ma - i + 2 * k == j:
+ val += comb(i, k) * a[D - i] * (wosq) ** (i - k) / bw ** i
+ aprime = xpx.at(aprime, Dp - j).set(val, xp=xp)
+
+ return normalize(bprime, aprime)
+
+
+def lp2bs(b, a, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandstop filter.
+
+ Return an analog band-stop filter with center frequency `wo` and
+ bandwidth `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, in transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like, shape (M,)
+ Numerator polynomial coefficients. Must be 1-D.
+ a : array_like, shape (N,)
+ Denominator polynomial coefficients. Must be 1-D.
+ wo : float
+ Desired stopband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired stopband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed band-stop filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed band-stop filter.
+
+ See Also
+ --------
+ lp2lp, lp2hp, lp2bp, bilinear
+ lp2bs_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2}
+
+ This is the "wideband" transformation, producing a stopband with
+ geometric (log frequency) symmetry about `wo`.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.5])
+ >>> bs = signal.lti(*signal.lp2bs(lp.num, lp.den))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_bs, p_bs = bs.bode(w)
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_bs, label='Bandstop')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+ """
+ xp = array_namespace(a, b)
+
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ D = a.shape[0] - 1
+ N = b.shape[0] - 1
+ M = max([N, D])
+ Np = M + M
+ Dp = M + M
+ bprime = xp.empty(Np + 1, dtype=b.dtype)
+ aprime = xp.empty(Dp + 1, dtype=a.dtype)
+ wosq = wo * wo
+ for j in range(Np + 1):
+ val = 0.0
+ for i in range(0, N + 1):
+ for k in range(0, M - i + 1):
+ if i + 2 * k == j:
+ val += (comb(M - i, k) * b[N - i] *
+ (wosq) ** (M - i - k) * bw ** i)
+ bprime = xpx.at(bprime, Np - j).set(val, xp=xp)
+ for j in range(Dp + 1):
+ val = 0.0
+ for i in range(0, D + 1):
+ for k in range(0, M - i + 1):
+ if i + 2 * k == j:
+ val += (comb(M - i, k) * a[D - i] *
+ (wosq) ** (M - i - k) * bw ** i)
+ aprime = xpx.at(aprime, Dp - j).set(val, xp=xp)
+
+ return normalize(bprime, aprime)
+
+
+def bilinear(b, a, fs=1.0):
+ r"""Calculate a digital IIR filter from an analog transfer function by utilizing
+ the bilinear transform.
+
+ Parameters
+ ----------
+ b : array_like
+ Coefficients of the numerator polynomial of the analog transfer function in
+ form of a complex- or real-valued 1d array.
+ a : array_like
+ Coefficients of the denominator polynomial of the analog transfer function in
+ form of a complex- or real-valued 1d array.
+ fs : float
+ Sample rate, as ordinary frequency (e.g., hertz). No pre-warping is
+ done in this function.
+
+ Returns
+ -------
+ beta : ndarray
+ Coefficients of the numerator polynomial of the digital transfer function in
+ form of a complex- or real-valued 1d array.
+ alpha : ndarray
+ Coefficients of the denominator polynomial of the digital transfer function in
+ form of a complex- or real-valued 1d array.
+
+ Notes
+ -----
+ The parameters :math:`b = [b_0, \ldots, b_Q]` and :math:`a = [a_0, \ldots, a_P]`
+ are 1d arrays of length :math:`Q+1` and :math:`P+1`. They define the analog
+ transfer function
+
+ .. math::
+
+ H_a(s) = \frac{b_0 s^Q + b_1 s^{Q-1} + \cdots + b_Q}{
+ a_0 s^P + a_1 s^{P-1} + \cdots + a_P}\ .
+
+ The bilinear transform [1]_ is applied by substituting
+
+ .. math::
+
+ s = \kappa \frac{z-1}{z+1}\ , \qquad \kappa := 2 f_s\ ,
+
+ into :math:`H_a(s)`, with :math:`f_s` being the sampling rate.
+ This results in the digital transfer function in the :math:`z`-domain
+
+ .. math::
+
+ H_d(z) = \frac{b_0 \left(\kappa \frac{z-1}{z+1}\right)^Q +
+ b_1 \left(\kappa \frac{z-1}{z+1}\right)^{Q-1} +
+ \cdots + b_Q}{
+ a_0 \left(\kappa \frac{z-1}{z+1}\right)^P +
+ a_1 \left(\kappa \frac{z-1}{z+1}\right)^{P-1} +
+ \cdots + a_P}\ .
+
+ This expression can be simplified by multiplying numerator and denominator by
+ :math:`(z+1)^N`, with :math:`N=\max(P, Q)`. This allows :math:`H_d(z)` to be
+ reformulated as
+
+ .. math::
+
+ & & \frac{b_0 \big(\kappa (z-1)\big)^Q (z+1)^{N-Q} +
+ b_1 \big(\kappa (z-1)\big)^{Q-1} (z+1)^{N-Q+1} +
+ \cdots + b_Q(z+1)^N}{
+ a_0 \big(\kappa (z-1)\big)^P (z+1)^{N-P} +
+ a_1 \big(\kappa (z-1)\big)^{P-1} (z+1)^{N-P+1} +
+ \cdots + a_P(z+1)^N}\\
+ &=:& \frac{\beta_0 + \beta_1 z^{-1} + \cdots + \beta_N z^{-N}}{
+ \alpha_0 + \alpha_1 z^{-1} + \cdots + \alpha_N z^{-N}}\ .
+
+
+ This is the equation implemented to perform the bilinear transform. Note that for
+ large :math:`f_s`, :math:`\kappa^Q` or :math:`\kappa^P` can cause a numeric
+ overflow for sufficiently large :math:`P` or :math:`Q`.
+
+ References
+ ----------
+ .. [1] "Bilinear Transform", Wikipedia,
+ https://en.wikipedia.org/wiki/Bilinear_transform
+
+ See Also
+ --------
+ lp2lp, lp2hp, lp2bp, lp2bs, bilinear_zpk
+
+ Examples
+ --------
+ The following example shows the frequency response of an analog bandpass filter and
+ the corresponding digital filter derived by utilitzing the bilinear transform:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ ...
+ >>> fs = 100 # sampling frequency
+ >>> om_c = 2 * np.pi * np.array([7, 13]) # corner frequencies
+ >>> bb_s, aa_s = signal.butter(4, om_c, btype='bandpass', analog=True, output='ba')
+ >>> bb_z, aa_z = signal.bilinear(bb_s, aa_s, fs)
+ ...
+ >>> w_z, H_z = signal.freqz(bb_z, aa_z) # frequency response of digitial filter
+ >>> w_s, H_s = signal.freqs(bb_s, aa_s, worN=w_z*fs) # analog filter response
+ ...
+ >>> f_z, f_s = w_z * fs / (2*np.pi), w_s / (2*np.pi)
+ >>> Hz_dB, Hs_dB = (20*np.log10(np.abs(H_).clip(1e-10)) for H_ in (H_z, H_s))
+ >>> fg0, ax0 = plt.subplots()
+ >>> ax0.set_title("Frequency Response of 4-th order Bandpass Filter")
+ >>> ax0.set(xlabel='Frequency $f$ in Hertz', ylabel='Magnitude in dB',
+ ... xlim=[f_z[1], fs/2], ylim=[-200, 2])
+ >>> ax0.semilogx(f_z, Hz_dB, alpha=.5, label=r'$|H_z(e^{j 2 \pi f})|$')
+ >>> ax0.semilogx(f_s, Hs_dB, alpha=.5, label=r'$|H_s(j 2 \pi f)|$')
+ >>> ax0.legend()
+ >>> ax0.grid(which='both', axis='x')
+ >>> ax0.grid(which='major', axis='y')
+ >>> plt.show()
+
+ The difference in the higher frequencies shown in the plot is caused by an effect
+ called "frequency warping". [1]_ describes a method called "pre-warping" to
+ reduce those deviations.
+ """
+ xp = array_namespace(b, a)
+
+ b, a = map(np.asarray, (b, a))
+ b, a = np.atleast_1d(b), np.atleast_1d(a) # convert scalars, if needed
+ if not a.ndim == 1:
+ raise ValueError(f"Parameter a is not a 1d array since {a.shape=}")
+ if not b.ndim == 1:
+ raise ValueError(f"Parameter b is not a 1d array since {b.shape=}")
+ b, a = np.trim_zeros(b, 'f'), np.trim_zeros(a, 'f') # remove leading zeros
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Splitting the factor fs*2 between numerator and denominator reduces the chance of
+ # numeric overflow for large fs and large N:
+ fac = np.sqrt(fs*2)
+ zp1 = np.polynomial.Polynomial((+1, 1)) / fac # Polynomial (z + 1) / fac
+ zm1 = np.polynomial.Polynomial((-1, 1)) * fac # Polynomial (z - 1) * fac
+ # Note that NumPy's Polynomial coefficient order is backward compared to a and b.
+
+ N = max(len(a), len(b)) - 1
+ numerator = sum(b_ * zp1**(N-q) * zm1**q for q, b_ in enumerate(b[::-1]))
+ denominator = sum(a_ * zp1**(N-p) * zm1**p for p, a_ in enumerate(a[::-1]))
+
+ return normalize(
+ xp.asarray(numerator.coef[::-1].copy()),
+ xp.asarray(denominator.coef[::-1].copy())
+ )
+
+
+def _validate_gpass_gstop(gpass, gstop):
+
+ if gpass <= 0.0:
+ raise ValueError("gpass should be larger than 0.0")
+ elif gstop <= 0.0:
+ raise ValueError("gstop should be larger than 0.0")
+ elif gpass > gstop:
+ raise ValueError("gpass should be smaller than gstop")
+
+
+def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba',
+ fs=None):
+ """Complete IIR digital and analog filter design.
+
+ Given passband and stopband frequencies and gains, construct an analog or
+ digital IIR filter of minimum order for a given basic type. Return the
+ output in numerator, denominator ('ba'), pole-zero ('zpk') or second order
+ sections ('sos') form.
+
+ Parameters
+ ----------
+ wp, ws : float or array like, shape (2,)
+ Passband and stopband edge frequencies. Possible values are scalars
+ (for lowpass and highpass filters) or ranges (for bandpass and bandstop
+ filters).
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ Note, that for bandpass and bandstop filters passband must lie strictly
+ inside stopband or vice versa. Also note that the cutoff at the band edges
+ for IIR filters is defined as half-power, so -3dB, not half-amplitude (-6dB)
+ like for `scipy.signal.firwin`.
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ ftype : str, optional
+ The type of IIR filter to design:
+
+ - Butterworth : 'butter'
+ - Chebyshev I : 'cheby1'
+ - Chebyshev II : 'cheby2'
+ - Cauer/elliptic: 'ellip'
+
+ output : {'ba', 'zpk', 'sos'}, optional
+ Filter form of the output:
+
+ - second-order sections (recommended): 'sos'
+ - numerator/denominator (default) : 'ba'
+ - pole-zero : 'zpk'
+
+ In general the second-order sections ('sos') form is
+ recommended because inferring the coefficients for the
+ numerator/denominator form ('ba') suffers from numerical
+ instabilities. For reasons of backward compatibility the default
+ form is the numerator/denominator form ('ba'), where the 'b'
+ and the 'a' in 'ba' refer to the commonly used names of the
+ coefficients used.
+
+ Note: Using the second-order sections form ('sos') is sometimes
+ associated with additional computational costs: for
+ data-intense use cases it is therefore recommended to also
+ investigate the numerator/denominator form ('ba').
+
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ butter : Filter design using order and critical points
+ cheby1, cheby2, ellip, bessel
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, cheb2ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+
+ Notes
+ -----
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import matplotlib.ticker
+
+ >>> wp = 0.2
+ >>> ws = 0.3
+ >>> gpass = 1
+ >>> gstop = 40
+
+ >>> system = signal.iirdesign(wp, ws, gpass, gstop)
+ >>> w, h = signal.freqz(*system)
+
+ >>> fig, ax1 = plt.subplots()
+ >>> ax1.set_title('Digital filter frequency response')
+ >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b')
+ >>> ax1.set_ylabel('Amplitude [dB]', color='b')
+ >>> ax1.set_xlabel('Frequency [rad/sample]')
+ >>> ax1.grid(True)
+ >>> ax1.set_ylim([-120, 20])
+ >>> ax2 = ax1.twinx()
+ >>> phase = np.unwrap(np.angle(h))
+ >>> ax2.plot(w, phase, 'g')
+ >>> ax2.set_ylabel('Phase [rad]', color='g')
+ >>> ax2.grid(True)
+ >>> ax2.axis('tight')
+ >>> ax2.set_ylim([-6, 1])
+ >>> nticks = 8
+ >>> ax1.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks))
+ >>> ax2.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks))
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ try:
+ ordfunc = filter_dict[ftype][1]
+ except KeyError as e:
+ raise ValueError(f"Invalid IIR filter type: {ftype}") from e
+ except IndexError as e:
+ raise ValueError(f"{ftype} does not have order selection. "
+ "Use iirfilter function.") from e
+
+ _validate_gpass_gstop(gpass, gstop)
+
+ wp = xpx.atleast_nd(wp, ndim=1, xp=xp)
+ ws = xpx.atleast_nd(ws, ndim=1, xp=xp)
+
+ fs = _validate_fs(fs, allow_none=True)
+
+ if wp.shape[0] != ws.shape[0] or wp.shape not in [(1,), (2,)]:
+ raise ValueError("wp and ws must have one or two elements each, and "
+ f"the same shape, got {wp.shape} and {ws.shape}")
+
+ if xp.any(wp <= 0) or xp.any(ws <= 0):
+ raise ValueError("Values for wp, ws must be greater than 0")
+
+ if not analog:
+ if fs is None:
+ if xp.any(wp >= 1) or xp.any(ws >= 1):
+ raise ValueError("Values for wp, ws must be less than 1")
+ elif xp.any(wp >= fs/2) or xp.any(ws >= fs/2):
+ raise ValueError("Values for wp, ws must be less than fs/2 "
+ f"(fs={fs} -> fs/2={fs/2})")
+
+ if wp.shape[0] == 2:
+ if not ((ws[0] < wp[0] and wp[1] < ws[1]) or
+ (wp[0] < ws[0] and ws[1] < wp[1])):
+ raise ValueError("Passband must lie strictly inside stopband "
+ "or vice versa")
+
+ band_type = 2 * (wp.shape[0] - 1)
+ band_type += 1
+ if wp[0] >= ws[0]:
+ band_type += 1
+
+ btype = {1: 'lowpass', 2: 'highpass',
+ 3: 'bandstop', 4: 'bandpass'}[band_type]
+
+ N, Wn = ordfunc(wp, ws, gpass, gstop, analog=analog, fs=fs)
+ return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype,
+ ftype=ftype, output=output, fs=fs)
+
+
+def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=False,
+ ftype='butter', output='ba', fs=None):
+ """
+ IIR digital and analog filter design given order and critical points.
+
+ Design an Nth-order digital or analog filter and return the filter
+ coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+
+ When Wn is a length-2 sequence, ``Wn[0]`` must be less than ``Wn[1]``.
+ rp : float, optional
+ For Chebyshev and elliptic filters, provides the maximum ripple
+ in the passband. (dB)
+ rs : float, optional
+ For Chebyshev and elliptic filters, provides the minimum attenuation
+ in the stop band. (dB)
+ btype : {'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
+ The type of filter. Default is 'bandpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ ftype : str, optional
+ The type of IIR filter to design:
+
+ - Butterworth : 'butter'
+ - Chebyshev I : 'cheby1'
+ - Chebyshev II : 'cheby2'
+ - Cauer/elliptic: 'ellip'
+ - Bessel/Thomson: 'bessel'
+
+ output : {'ba', 'zpk', 'sos'}, optional
+ Filter form of the output:
+
+ - second-order sections (recommended): 'sos'
+ - numerator/denominator (default) : 'ba'
+ - pole-zero : 'zpk'
+
+ In general the second-order sections ('sos') form is
+ recommended because inferring the coefficients for the
+ numerator/denominator form ('ba') suffers from numerical
+ instabilities. For reasons of backward compatibility the default
+ form is the numerator/denominator form ('ba'), where the 'b'
+ and the 'a' in 'ba' refer to the commonly used names of the
+ coefficients used.
+
+ Note: Using the second-order sections form ('sos') is sometimes
+ associated with additional computational costs: for
+ data-intense use cases it is therefore recommended to also
+ investigate the numerator/denominator form ('ba').
+
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ butter : Filter design using order and critical points
+ cheby1, cheby2, ellip, bessel
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, cheb2ord, ellipord
+ iirdesign : General filter design using passband and stopband spec
+
+ Notes
+ -----
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Generate a 17th-order Chebyshev II analog bandpass filter from 50 Hz to
+ 200 Hz and plot the frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> b, a = signal.iirfilter(17, [2*np.pi*50, 2*np.pi*200], rs=60,
+ ... btype='band', analog=True, ftype='cheby2')
+ >>> w, h = signal.freqs(b, a, 1000)
+ >>> fig = plt.figure()
+ >>> ax = fig.add_subplot(1, 1, 1)
+ >>> ax.semilogx(w / (2*np.pi), 20 * np.log10(np.maximum(abs(h), 1e-5)))
+ >>> ax.set_title('Chebyshev Type II bandpass frequency response')
+ >>> ax.set_xlabel('Frequency [Hz]')
+ >>> ax.set_ylabel('Amplitude [dB]')
+ >>> ax.axis((10, 1000, -100, 10))
+ >>> ax.grid(which='both', axis='both')
+ >>> plt.show()
+
+ Create a digital filter with the same properties, in a system with
+ sampling rate of 2000 Hz, and plot the frequency response. (Second-order
+ sections implementation is required to ensure stability of a filter of
+ this order):
+
+ >>> sos = signal.iirfilter(17, [50, 200], rs=60, btype='band',
+ ... analog=False, ftype='cheby2', fs=2000,
+ ... output='sos')
+ >>> w, h = signal.freqz_sos(sos, 2000, fs=2000)
+ >>> fig = plt.figure()
+ >>> ax = fig.add_subplot(1, 1, 1)
+ >>> ax.semilogx(w, 20 * np.log10(np.maximum(abs(h), 1e-5)))
+ >>> ax.set_title('Chebyshev Type II bandpass frequency response')
+ >>> ax.set_xlabel('Frequency [Hz]')
+ >>> ax.set_ylabel('Amplitude [dB]')
+ >>> ax.axis((10, 1000, -100, 10))
+ >>> ax.grid(which='both', axis='both')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(Wn)
+ # For now, outputs will have float64 base dtype regardless of
+ # the dtype of Wn, so cast to float64 here to ensure 64 bit
+ # precision for all calculations.
+ Wn = xp.asarray(Wn, dtype=xp.float64)
+
+ fs = _validate_fs(fs, allow_none=True)
+ ftype, btype, output = (x.lower() for x in (ftype, btype, output))
+ if fs is not None:
+ if analog:
+ raise ValueError("fs cannot be specified for an analog filter")
+ Wn = Wn / (fs/2)
+
+ if xp.any(Wn <= 0):
+ raise ValueError("filter critical frequencies must be greater than 0")
+
+ if xp_size(Wn) > 1 and not Wn[0] < Wn[1]:
+ raise ValueError("Wn[0] must be less than Wn[1]")
+
+ try:
+ btype = band_dict[btype]
+ except KeyError as e:
+ raise ValueError(f"'{btype}' is an invalid bandtype for filter.") from e
+
+ try:
+ typefunc = filter_dict[ftype][0]
+ except KeyError as e:
+ raise ValueError(f"'{ftype}' is not a valid basic IIR filter.") from e
+
+ if output not in ['ba', 'zpk', 'sos']:
+ raise ValueError(f"'{output}' is not a valid output form.")
+
+ if rp is not None and rp < 0:
+ raise ValueError("passband ripple (rp) must be positive")
+
+ if rs is not None and rs < 0:
+ raise ValueError("stopband attenuation (rs) must be positive")
+
+ # Get analog lowpass prototype
+ if typefunc == buttap:
+ z, p, k = typefunc(N, xp=xp)
+ elif typefunc == besselap:
+ z, p, k = typefunc(N, norm=bessel_norms[ftype], xp=xp)
+ elif typefunc == cheb1ap:
+ if rp is None:
+ raise ValueError("passband ripple (rp) must be provided to "
+ "design a Chebyshev I filter.")
+ z, p, k = typefunc(N, rp, xp=xp)
+ elif typefunc == cheb2ap:
+ if rs is None:
+ raise ValueError("stopband attenuation (rs) must be provided to "
+ "design a Chebyshev II filter.")
+ z, p, k = typefunc(N, rs, xp=xp)
+ elif typefunc == ellipap:
+ if rs is None or rp is None:
+ raise ValueError("Both rp and rs must be provided to design an "
+ "elliptic filter.")
+ z, p, k = typefunc(N, rp, rs, xp=xp)
+ else:
+ raise NotImplementedError(f"'{ftype}' not implemented in iirfilter.")
+
+ # Pre-warp frequencies for digital filter design
+ if not analog:
+ if xp.any(Wn <= 0) or xp.any(Wn >= 1):
+ if fs is not None:
+ raise ValueError("Digital filter critical frequencies must "
+ f"be 0 < Wn < fs/2 (fs={fs} -> fs/2={fs/2})")
+ raise ValueError("Digital filter critical frequencies "
+ "must be 0 < Wn < 1")
+ fs = 2.0
+ warped = 2 * fs * xp.tan(xp.pi * Wn / fs)
+ else:
+ warped = Wn
+
+ # transform to lowpass, bandpass, highpass, or bandstop
+ if btype in ('lowpass', 'highpass'):
+ if xp_size(Wn) != 1:
+ raise ValueError('Must specify a single critical frequency Wn '
+ 'for lowpass or highpass filter')
+
+ if btype == 'lowpass':
+ z, p, k = lp2lp_zpk(z, p, k, wo=warped)
+ elif btype == 'highpass':
+ z, p, k = lp2hp_zpk(z, p, k, wo=warped)
+ elif btype in ('bandpass', 'bandstop'):
+ try:
+ bw = warped[1] - warped[0]
+ wo = xp.sqrt(warped[0] * warped[1])
+ except IndexError as e:
+ raise ValueError('Wn must specify start and stop frequencies for '
+ 'bandpass or bandstop filter') from e
+
+ if btype == 'bandpass':
+ z, p, k = lp2bp_zpk(z, p, k, wo=wo, bw=bw)
+ elif btype == 'bandstop':
+ z, p, k = lp2bs_zpk(z, p, k, wo=wo, bw=bw)
+ else:
+ raise NotImplementedError(f"'{btype}' not implemented in iirfilter.")
+
+ # Find discrete equivalent if necessary
+ if not analog:
+ z, p, k = bilinear_zpk(z, p, k, fs=fs)
+
+ # Transform to proper out type (pole-zero, state-space, numer-denom)
+ if output == 'zpk':
+ return z, p, k
+ elif output == 'ba':
+ return zpk2tf(z, p, k)
+ elif output == 'sos':
+ return zpk2sos(z, p, k, analog=analog)
+
+
+def _relative_degree(z, p):
+ """
+ Return relative degree of transfer function from zeros and poles
+ """
+ degree = p.shape[0] - z.shape[0]
+ if degree < 0:
+ raise ValueError("Improper transfer function. "
+ "Must have at least as many poles as zeros.")
+ else:
+ return degree
+
+
+def bilinear_zpk(z, p, k, fs):
+ r"""
+ Return a digital IIR filter from an analog one using a bilinear transform.
+
+ Transform a set of poles and zeros from the analog s-plane to the digital
+ z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for
+ ``s``, maintaining the shape of the frequency response.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ fs : float
+ Sample rate, as ordinary frequency (e.g., hertz). No prewarping is
+ done in this function.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed digital filter transfer function.
+ p : ndarray
+ Poles of the transformed digital filter transfer function.
+ k : float
+ System gain of the transformed digital filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, lp2bs_zpk
+ bilinear
+
+ Notes
+ -----
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> fs = 100
+ >>> bf = 2 * np.pi * np.array([7, 13])
+ >>> filts = signal.lti(*signal.butter(4, bf, btype='bandpass', analog=True,
+ ... output='zpk'))
+ >>> filtz = signal.lti(*signal.bilinear_zpk(filts.zeros, filts.poles,
+ ... filts.gain, fs))
+ >>> wz, hz = signal.freqz_zpk(filtz.zeros, filtz.poles, filtz.gain)
+ >>> ws, hs = signal.freqs_zpk(filts.zeros, filts.poles, filts.gain,
+ ... worN=fs*wz)
+ >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hz).clip(1e-15)),
+ ... label=r'$|H_z(e^{j \omega})|$')
+ >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hs).clip(1e-15)),
+ ... label=r'$|H(j \omega)|$')
+ >>> plt.legend()
+ >>> plt.xlabel('Frequency [Hz]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(True)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ degree = _relative_degree(z, p)
+
+ fs2 = 2.0*fs
+
+ # Bilinear transform the poles and zeros
+ z_z = (fs2 + z) / (fs2 - z)
+ p_z = (fs2 + p) / (fs2 - p)
+
+ # Any zeros that were at infinity get moved to the Nyquist frequency
+ z_z = xp.concat((z_z, -xp.ones(degree)))
+
+ # Compensate for gain change
+ k_z = k * xp.real(xp.prod(fs2 - z) / xp.prod(fs2 - p))
+
+ return z_z, p_z, k_z
+
+
+def lp2lp_zpk(z, p, k, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a different frequency.
+
+ Return an analog low-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency,
+ using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired cutoff, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed low-pass filter transfer function.
+ p : ndarray
+ Poles of the transformed low-pass filter transfer function.
+ k : float
+ System gain of the transformed low-pass filter.
+
+ See Also
+ --------
+ lp2hp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear
+ lp2lp
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s}{\omega_0}
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to
+ transform it to a new 'zpk' representation associated with a cutoff frequency wo.
+
+ >>> from scipy.signal import lp2lp_zpk
+ >>> z = [7, 2]
+ >>> p = [5, 13]
+ >>> k = 0.8
+ >>> wo = 0.4
+ >>> lp2lp_zpk(z, p, k, wo)
+ ( array([2.8, 0.8]), array([2. , 5.2]), 0.8)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo) # Avoid int wraparound
+
+ degree = _relative_degree(z, p)
+
+ # Scale all points radially from origin to shift cutoff frequency
+ z_lp = wo * z
+ p_lp = wo * p
+
+ # Each shifted pole decreases gain by wo, each shifted zero increases it.
+ # Cancel out the net change to keep overall gain the same
+ k_lp = k * wo**degree
+
+ return z_lp, p_lp, k_lp
+
+
+def lp2hp_zpk(z, p, k, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a highpass filter.
+
+ Return an analog high-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency,
+ using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired cutoff, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed high-pass filter transfer function.
+ p : ndarray
+ Poles of the transformed high-pass filter transfer function.
+ k : float
+ System gain of the transformed high-pass filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear
+ lp2hp
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{\omega_0}{s}
+
+ This maintains symmetry of the lowpass and highpass responses on a
+ logarithmic scale.
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to
+ transform it to a highpass filter with a cutoff frequency wo.
+
+ >>> from scipy.signal import lp2hp_zpk
+ >>> z = [ -2 + 3j , -0.5 - 0.8j ]
+ >>> p = [ -1 , -4 ]
+ >>> k = 10
+ >>> wo = 0.6
+ >>> lp2hp_zpk(z, p, k, wo)
+ ( array([-0.09230769-0.13846154j, -0.33707865+0.53932584j]),
+ array([-0.6 , -0.15]),
+ 8.5)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ # XXX: no xp_promote here since that breaks TestButter
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo)
+
+ degree = _relative_degree(z, p)
+
+ # Invert positions radially about unit circle to convert LPF to HPF
+ # Scale all points radially from origin to shift cutoff frequency
+ z_hp = wo / z
+ p_hp = wo / p
+
+ # If lowpass had zeros at infinity, inverting moves them to origin.
+ z_hp = xp.concat((z_hp, xp.zeros(degree)))
+
+ # Cancel out gain change caused by inversion
+ k_hp = k * xp.real(xp.prod(-z) / xp.prod(-p))
+
+ return z_hp, p_hp, k_hp
+
+
+def lp2bp_zpk(z, p, k, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandpass filter.
+
+ Return an analog band-pass filter with center frequency `wo` and
+ bandwidth `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired passband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired passband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed band-pass filter transfer function.
+ p : ndarray
+ Poles of the transformed band-pass filter transfer function.
+ k : float
+ System gain of the transformed band-pass filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2hp_zpk, lp2bs_zpk, bilinear
+ lp2bp
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}}
+
+ This is the "wideband" transformation, producing a passband with
+ geometric (log frequency) symmetry about `wo`.
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to
+ transform it to a bandpass filter with a center frequency wo and
+ bandwidth bw.
+
+ >>> from scipy.signal import lp2bp_zpk
+ >>> z = [ 5 + 2j , 5 - 2j ]
+ >>> p = [ 7 , -16 ]
+ >>> k = 0.8
+ >>> wo = 0.62
+ >>> bw = 15
+ >>> lp2bp_zpk(z, p, k, wo, bw)
+ ( array([7.49955815e+01+3.00017676e+01j, 7.49955815e+01-3.00017676e+01j,
+ 4.41850748e-03-1.76761126e-03j, 4.41850748e-03+1.76761126e-03j]),
+ array([1.04996339e+02+0.j, -1.60167736e-03+0.j, 3.66108003e-03+0.j,
+ -2.39998398e+02+0.j]), 0.8)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z, p = xp_promote(z, p, force_floating=True, xp=xp)
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo)
+ bw = float(bw)
+
+ degree = _relative_degree(z, p)
+
+ # Scale poles and zeros to desired bandwidth
+ z_lp = z * bw/2
+ p_lp = p * bw/2
+
+ # Square root needs to produce complex result, not NaN
+ z_lp = xp.astype(z_lp, xp.complex128)
+ p_lp = xp.astype(p_lp, xp.complex128)
+
+ # Duplicate poles and zeros and shift from baseband to +wo and -wo
+ z_bp = xp.concat((z_lp + xp.sqrt(z_lp**2 - wo**2),
+ z_lp - xp.sqrt(z_lp**2 - wo**2)))
+ p_bp = xp.concat((p_lp + xp.sqrt(p_lp**2 - wo**2),
+ p_lp - xp.sqrt(p_lp**2 - wo**2)))
+
+ # Move degree zeros to origin, leaving degree zeros at infinity for BPF
+ z_bp = xp.concat((z_bp, xp.zeros(degree)))
+
+ # Cancel out gain change from frequency scaling
+ k_bp = k * bw**degree
+
+ return z_bp, p_bp, k_bp
+
+
+def lp2bs_zpk(z, p, k, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandstop filter.
+
+ Return an analog band-stop filter with center frequency `wo` and
+ stopband width `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired stopband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired stopband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed band-stop filter transfer function.
+ p : ndarray
+ Poles of the transformed band-stop filter transfer function.
+ k : float
+ System gain of the transformed band-stop filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, bilinear
+ lp2bs
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2}
+
+ This is the "wideband" transformation, producing a stopband with
+ geometric (log frequency) symmetry about `wo`.
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Transform a low-pass filter represented in 'zpk' (Zero-Pole-Gain) form
+ into a bandstop filter represented in 'zpk' form, with a center frequency wo and
+ bandwidth bw.
+
+ >>> from scipy.signal import lp2bs_zpk
+ >>> z = [ ]
+ >>> p = [ 0.7 , -1 ]
+ >>> k = 9
+ >>> wo = 0.5
+ >>> bw = 10
+ >>> lp2bs_zpk(z, p, k, wo, bw)
+ ( array([0.+0.5j, 0.+0.5j, 0.-0.5j, 0.-0.5j]),
+ array([14.2681928 +0.j, -0.02506281+0.j, 0.01752149+0.j, -9.97493719+0.j]),
+ -12.857142857142858)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z, p = xp_promote(z, p, force_floating=True, xp=xp)
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo)
+ bw = float(bw)
+
+ degree = _relative_degree(z, p)
+
+ # Invert to a highpass filter with desired bandwidth
+ z_hp = (bw/2) / z
+ p_hp = (bw/2) / p
+
+ # Square root needs to produce complex result, not NaN
+ z_hp = xp.astype(z_hp, xp.complex128)
+ p_hp = xp.astype(p_hp, xp.complex128)
+
+ # Duplicate poles and zeros and shift from baseband to +wo and -wo
+ z_bs = xp.concat((z_hp + xp.sqrt(z_hp**2 - wo**2),
+ z_hp - xp.sqrt(z_hp**2 - wo**2)))
+ p_bs = xp.concat((p_hp + xp.sqrt(p_hp**2 - wo**2),
+ p_hp - xp.sqrt(p_hp**2 - wo**2)))
+
+ # Move any zeros that were at infinity to the center of the stopband
+ z_bs = xp.concat((z_bs, xp.full(degree, +1j*wo)))
+ z_bs = xp.concat((z_bs, xp.full(degree, -1j*wo)))
+
+ # Cancel out gain change caused by inversion
+ k_bs = k * xp.real(xp.prod(-z) / xp.prod(-p))
+
+ return z_bs, p_bs, k_bs
+
+
+def butter(N, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Butterworth digital and analog filter design.
+
+ Design an Nth-order digital or analog Butterworth filter and return
+ the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter. For 'bandpass' and 'bandstop' filters,
+ the resulting order of the final second-order sections ('sos')
+ matrix is ``2*N``, with `N` the number of biquad sections
+ of the desired system.
+ Wn : array_like
+ The critical frequency or frequencies. For lowpass and highpass
+ filters, Wn is a scalar; for bandpass and bandstop filters,
+ Wn is a length-2 sequence.
+
+ For a Butterworth filter, this is the point at which the gain
+ drops to 1/sqrt(2) that of the passband (the "-3 dB point").
+
+ For digital filters, if `fs` is not specified, `Wn` units are
+ normalized from 0 to 1, where 1 is the Nyquist frequency (`Wn` is
+ thus in half cycles / sample and defined as 2*critical frequencies
+ / `fs`). If `fs` is specified, `Wn` is in the same units as `fs`.
+
+ For analog filters, `Wn` is an angular frequency (e.g. rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ buttord, buttap
+
+ Notes
+ -----
+ The Butterworth filter has maximally flat frequency response in the
+ passband.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ If the transfer function form ``[b, a]`` is requested, numerical
+ problems can occur since the conversion between roots and
+ the polynomial coefficients is a numerically sensitive operation,
+ even for N >= 4. It is recommended to work with the SOS
+ representation.
+
+ .. warning::
+ Designing high-order and narrowband IIR filters in TF form can
+ result in unstable or incorrect filtering due to floating point
+ numerical precision issues. Consider inspecting output filter
+ characteristics `freqz` or designing the filters with second-order
+ sections via ``output='sos'``.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.butter(4, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Butterworth filter frequency response')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.butter(10, 15, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 15 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.tight_layout()
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, btype=btype, analog=analog,
+ output=output, ftype='butter', fs=fs)
+
+
+def cheby1(N, rp, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Chebyshev type I digital and analog filter design.
+
+ Design an Nth-order digital or analog Chebyshev type I filter and
+ return the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ rp : float
+ The maximum ripple allowed below unity gain in the passband.
+ Specified in decibels, as a positive number.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+ For Type I filters, this is the point in the transition band at which
+ the gain first drops below -`rp`.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ cheb1ord, cheb1ap
+
+ Notes
+ -----
+ The Chebyshev type I filter maximizes the rate of cutoff between the
+ frequency response's passband and stopband, at the expense of ripple in
+ the passband and increased ringing in the step response.
+
+ Type I filters roll off faster than Type II (`cheby2`), but Type II
+ filters do not have any ripple in the passband.
+
+ The equiripple passband has N maxima or minima (for example, a
+ 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is
+ unity for odd-order filters, or -rp dB for even-order filters.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.cheby1(4, 5, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev Type I frequency response (rp=5)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-5, color='green') # rp
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.cheby1(10, 1, 15, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 15 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.tight_layout()
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, rp=rp, btype=btype, analog=analog,
+ output=output, ftype='cheby1', fs=fs)
+
+
+def cheby2(N, rs, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Chebyshev type II digital and analog filter design.
+
+ Design an Nth-order digital or analog Chebyshev type II filter and
+ return the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ rs : float
+ The minimum attenuation required in the stop band.
+ Specified in decibels, as a positive number.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+ For Type II filters, this is the point in the transition band at which
+ the gain first reaches -`rs`.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ cheb2ord, cheb2ap
+
+ Notes
+ -----
+ The Chebyshev type II filter maximizes the rate of cutoff between the
+ frequency response's passband and stopband, at the expense of ripple in
+ the stopband and increased ringing in the step response.
+
+ Type II filters do not roll off as fast as Type I (`cheby1`).
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.cheby2(4, 40, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev Type II frequency response (rs=40)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-40, color='green') # rs
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.cheby2(12, 20, 17, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 17 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog,
+ output=output, ftype='cheby2', fs=fs)
+
+
+def ellip(N, rp, rs, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Elliptic (Cauer) digital and analog filter design.
+
+ Design an Nth-order digital or analog elliptic filter and return
+ the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ rp : float
+ The maximum ripple allowed below unity gain in the passband.
+ Specified in decibels, as a positive number.
+ rs : float
+ The minimum attenuation required in the stop band.
+ Specified in decibels, as a positive number.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+ For elliptic filters, this is the point in the transition band at
+ which the gain first drops below -`rp`.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ ellipord, ellipap
+
+ Notes
+ -----
+ Also known as Cauer or Zolotarev filters, the elliptical filter maximizes
+ the rate of transition between the frequency response's passband and
+ stopband, at the expense of ripple in both, and increased ringing in the
+ step response.
+
+ As `rp` approaches 0, the elliptical filter becomes a Chebyshev
+ type II filter (`cheby2`). As `rs` approaches 0, it becomes a Chebyshev
+ type I filter (`cheby1`). As both approach 0, it becomes a Butterworth
+ filter (`butter`).
+
+ The equiripple passband has N maxima or minima (for example, a
+ 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is
+ unity for odd-order filters, or -rp dB for even-order filters.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Elliptic filter frequency response (rp=5, rs=40)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-40, color='green') # rs
+ >>> plt.axhline(-5, color='green') # rp
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.ellip(8, 1, 100, 17, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 17 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.tight_layout()
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, rs=rs, rp=rp, btype=btype, analog=analog,
+ output=output, ftype='elliptic', fs=fs)
+
+
+def bessel(N, Wn, btype='low', analog=False, output='ba', norm='phase',
+ fs=None):
+ """
+ Bessel/Thomson digital and analog filter design.
+
+ Design an Nth-order digital or analog Bessel filter and return the
+ filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies (defined
+ by the `norm` parameter).
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned. (See Notes.)
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba'.
+ norm : {'phase', 'delay', 'mag'}, optional
+ Critical frequency normalization:
+
+ ``phase``
+ The filter is normalized such that the phase response reaches its
+ midpoint at angular (e.g. rad/s) frequency `Wn`. This happens for
+ both low-pass and high-pass filters, so this is the
+ "phase-matched" case.
+
+ The magnitude response asymptotes are the same as a Butterworth
+ filter of the same order with a cutoff of `Wn`.
+
+ This is the default, and matches MATLAB's implementation.
+
+ ``delay``
+ The filter is normalized such that the group delay in the passband
+ is 1/`Wn` (e.g., seconds). This is the "natural" type obtained by
+ solving Bessel polynomials.
+
+ ``mag``
+ The filter is normalized such that the gain magnitude is -3 dB at
+ angular frequency `Wn`.
+
+ .. versionadded:: 0.18.0
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ Notes
+ -----
+ Also known as a Thomson filter, the analog Bessel filter has maximally
+ flat group delay and maximally linear phase response, with very little
+ ringing in the step response. [1]_
+
+ The Bessel is inherently an analog filter. This function generates digital
+ Bessel filters using the bilinear transform, which does not preserve the
+ phase response of the analog filter. As such, it is only approximately
+ correct at frequencies below about fs/4. To get maximally-flat group
+ delay at higher frequencies, the analog Bessel filter must be transformed
+ using phase-preserving techniques.
+
+ See `besselap` for implementation details and references.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ References
+ ----------
+ .. [1] Thomson, W.E., "Delay Networks having Maximally Flat Frequency
+ Characteristics", Proceedings of the Institution of Electrical
+ Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490.
+
+ Examples
+ --------
+ Plot the phase-normalized frequency response, showing the relationship
+ to the Butterworth's cutoff frequency (green):
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.butter(4, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(np.abs(h)), color='silver', ls='dashed')
+ >>> b, a = signal.bessel(4, 100, 'low', analog=True, norm='phase')
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(np.abs(h)))
+ >>> plt.title('Bessel filter magnitude response (with Butterworth)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.show()
+
+ and the phase midpoint:
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, np.unwrap(np.angle(h)))
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-np.pi, color='red') # phase midpoint
+ >>> plt.title('Bessel filter phase response')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Phase [rad]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.show()
+
+ Plot the magnitude-normalized frequency response, showing the -3 dB cutoff:
+
+ >>> b, a = signal.bessel(3, 10, 'low', analog=True, norm='mag')
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(np.abs(h)))
+ >>> plt.axhline(-3, color='red') # -3 dB magnitude
+ >>> plt.axvline(10, color='green') # cutoff frequency
+ >>> plt.title('Amplitude-normalized Bessel filter frequency response')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.show()
+
+ Plot the delay-normalized filter, showing the maximally-flat group delay
+ at 0.1 seconds:
+
+ >>> b, a = signal.bessel(5, 1/0.1, 'low', analog=True, norm='delay')
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.figure()
+ >>> plt.semilogx(w[1:], -np.diff(np.unwrap(np.angle(h)))/np.diff(w))
+ >>> plt.axhline(0.1, color='red') # 0.1 seconds group delay
+ >>> plt.title('Bessel filter group delay')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Group delay [s]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.show()
+
+ """
+ return iirfilter(N, Wn, btype=btype, analog=analog,
+ output=output, ftype='bessel_'+norm, fs=fs)
+
+
+def maxflat():
+ pass
+
+
+def yulewalk():
+ pass
+
+
+def band_stop_obj(wp, ind, passb, stopb, gpass, gstop, type):
+ """
+ Band Stop Objective Function for order minimization.
+
+ Returns the non-integer order for an analog band stop filter.
+
+ Parameters
+ ----------
+ wp : scalar
+ Edge of passband `passb`.
+ ind : int, {0, 1}
+ Index specifying which `passb` edge to vary (0 or 1).
+ passb : ndarray
+ Two element sequence of fixed passband edges.
+ stopb : ndarray
+ Two element sequence of fixed stopband edges.
+ gpass : float
+ Amount of ripple in the passband in dB.
+ gstop : float
+ Amount of attenuation in stopband in dB.
+ type : {'butter', 'cheby', 'ellip'}
+ Type of filter.
+
+ Returns
+ -------
+ n : scalar
+ Filter order (possibly non-integer).
+
+ Notes
+ -----
+ Band-stop filters are used in applications where certain frequency
+ components need to be blocked while others are allowed; for instance,
+ removing noise at specific frequencies while allowing the desired signal
+ to pass through. The order of a filter often determines its complexity and
+ accuracy. Determining the right order can be a challenge. This function
+ aims to provide an appropriate order for an analog band stop filter.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> from scipy.signal import band_stop_obj
+ >>> wp = 2
+ >>> ind = 1
+ >>> passb = np.array([1, 3])
+ >>> stopb = np.array([0.5, 4])
+ >>> gstop = 30
+ >>> gpass = 3
+ >>> filter_type = 'butter'
+ >>> band_stop_obj(wp, ind, passb, stopb, gpass, gstop, filter_type)
+ np.float64(-2.758504160760643)
+
+ """
+
+ _validate_gpass_gstop(gpass, gstop)
+
+ passbC = passb.copy()
+ passbC[ind] = wp
+ nat = (stopb * (passbC[0] - passbC[1]) /
+ (stopb ** 2 - passbC[0] * passbC[1]))
+ nat = min(abs(nat))
+
+ if type == 'butter':
+ GSTOP = 10 ** (0.1 * abs(gstop))
+ GPASS = 10 ** (0.1 * abs(gpass))
+ n = (np.log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * np.log10(nat)))
+ elif type == 'cheby':
+ GSTOP = 10 ** (0.1 * abs(gstop))
+ GPASS = 10 ** (0.1 * abs(gpass))
+ n = np.arccosh(np.sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / np.arccosh(nat)
+ elif type == 'ellip':
+ GSTOP = 10 ** (0.1 * gstop)
+ GPASS = 10 ** (0.1 * gpass)
+ arg1 = np.sqrt((GPASS - 1.0) / (GSTOP - 1.0))
+ arg0 = 1.0 / nat
+ d0 = special.ellipk([arg0 ** 2, 1 - arg0 ** 2])
+ d1 = special.ellipk([arg1 ** 2, 1 - arg1 ** 2])
+ n = (d0[0] * d1[1] / (d0[1] * d1[0]))
+ else:
+ raise ValueError(f"Incorrect type: {type}")
+ return n
+
+
+def _pre_warp(wp, ws, analog, *, xp):
+ # Pre-warp frequencies for digital filter design
+ if not analog:
+ passb = xp.tan(xp.pi * wp / 2.0)
+ stopb = xp.tan(xp.pi * ws / 2.0)
+ else:
+ passb, stopb = wp, ws
+ return passb, stopb
+
+
+def _validate_wp_ws(wp, ws, fs, analog, *, xp):
+ wp = xpx.atleast_nd(wp, ndim=1, xp=xp)
+ ws = xpx.atleast_nd(ws, ndim=1, xp=xp)
+ wp, ws = xp_promote(wp, ws, force_floating=True, xp=xp)
+
+ if fs is not None:
+ if analog:
+ raise ValueError("fs cannot be specified for an analog filter")
+ wp = 2 * wp / fs
+ ws = 2 * ws / fs
+
+ filter_type = 2 * (wp.shape[0] - 1) + 1
+ if wp[0] >= ws[0]:
+ filter_type += 1
+
+ return wp, ws, filter_type
+
+
+def _find_nat_freq(stopb, passb, gpass, gstop, filter_type, filter_kind, *, xp):
+ if filter_type == 1: # low
+ nat = stopb / passb
+ elif filter_type == 2: # high
+ nat = passb / stopb
+ elif filter_type == 3: # stop
+
+ passb, stopb = np.asarray(passb), np.asarray(stopb) # XXX fminbound array API
+ wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12,
+ args=(0, passb, stopb, gpass, gstop,
+ filter_kind),
+ disp=0)
+ wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1],
+ args=(1, passb, stopb, gpass, gstop,
+ filter_kind),
+ disp=0)
+ passb = [float(wp0), float(wp1)]
+ passb, stopb = xp.asarray(passb), xp.asarray(stopb)
+ nat = ((stopb * (passb[0] - passb[1])) /
+ (stopb ** 2 - passb[0] * passb[1]))
+ elif filter_type == 4: # pass
+ nat = ((stopb ** 2 - passb[0] * passb[1]) /
+ (stopb * (passb[0] - passb[1])))
+ else:
+ raise ValueError(f"should not happen: {filter_type =}.")
+
+ nat = xp.min(xp.abs(nat))
+ return nat, passb
+
+
+def _postprocess_wn(WN, analog, fs, *, xp):
+ wn = WN if analog else xp.atan(WN) * 2.0 / xp.pi
+ if wn.shape[0] == 1:
+ wn = wn[0]
+ if fs is not None:
+ wn = wn * fs / 2
+ return wn
+
+
+def buttord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Butterworth filter order selection.
+
+ Return the order of the lowest order digital or analog Butterworth filter
+ that loses no more than `gpass` dB in the passband and has at least
+ `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float or array-like
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for a Butterworth filter which meets specs.
+ wn : ndarray or float
+ The Butterworth natural frequency (i.e. the "3dB frequency"). Should
+ be used with `butter` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `butter`.
+
+ See Also
+ --------
+ butter : Filter design using order and critical points
+ cheb1ord : Find order and critical points from passband and stopband spec
+ cheb2ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design an analog bandpass filter with passband within 3 dB from 20 to
+ 50 rad/s, while rejecting at least -40 dB below 14 and above 60 rad/s.
+ Plot its frequency response, showing the passband and stopband
+ constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.buttord([20, 50], [14, 60], 3, 40, True)
+ >>> b, a = signal.butter(N, Wn, 'band', True)
+ >>> w, h = signal.freqs(b, a, np.logspace(1, 2, 500))
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Butterworth bandpass filter fit to constraints')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([1, 14, 14, 1], [-40, -40, 99, 99], '0.9', lw=0) # stop
+ >>> plt.fill([20, 20, 50, 50], [-99, -3, -3, -99], '0.9', lw=0) # pass
+ >>> plt.fill([60, 60, 1e9, 1e9], [99, -40, -40, 99], '0.9', lw=0) # stop
+ >>> plt.axis([10, 100, -60, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ _validate_gpass_gstop(gpass, gstop)
+ fs = _validate_fs(fs, allow_none=True)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(
+ stopb, passb, gpass, gstop, filter_type, 'butter', xp=xp
+ )
+
+ GSTOP = 10 ** (0.1 * builtins.abs(gstop))
+ GPASS = 10 ** (0.1 * builtins.abs(gpass))
+ ord = int(
+ math.ceil(math.log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * math.log10(nat)))
+ )
+
+ # Find the Butterworth natural frequency WN (or the "3dB" frequency")
+ # to give exactly gpass at passb.
+ try:
+ W0 = (GPASS - 1.0) ** (-1.0 / (2.0 * ord))
+ except ZeroDivisionError:
+ W0 = 1.0
+ warnings.warn("Order is zero...check input parameters.",
+ RuntimeWarning, stacklevel=2)
+
+ # now convert this frequency back from lowpass prototype
+ # to the original analog filter
+
+ if filter_type == 1: # low
+ WN = W0 * passb
+ elif filter_type == 2: # high
+ WN = passb / W0
+ elif filter_type == 3: # stop
+ discr = xp.sqrt((passb[1] - passb[0]) ** 2 +
+ 4 * W0 ** 2 * passb[0] * passb[1])
+ WN0 = ((passb[1] - passb[0]) + discr) / (2 * W0)
+ WN1 = ((passb[1] - passb[0]) - discr) / (2 * W0)
+ WN = xp.asarray([float(WN0), float(WN1)])
+ WN = xp.sort(xp.abs(WN))
+
+ elif filter_type == 4: # pass
+ W0 = xp.asarray([-W0, W0], dtype=xp.float64)
+ WN = (-W0 * (passb[1] - passb[0]) / 2.0 +
+ xp.sqrt(W0 ** 2 / 4.0 * (passb[1] - passb[0]) ** 2 +
+ passb[0] * passb[1]))
+ WN = xp.sort(xp.abs(WN))
+ else:
+ raise ValueError(f"Bad type: {filter_type}")
+
+ wn = _postprocess_wn(WN, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+def cheb1ord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Chebyshev type I filter order selection.
+
+ Return the order of the lowest order digital or analog Chebyshev Type I
+ filter that loses no more than `gpass` dB in the passband and has at
+ least `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for a Chebyshev type I filter that meets specs.
+ wn : ndarray or float
+ The Chebyshev natural frequency (the "3dB frequency") for use with
+ `cheby1` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `cheby1`.
+
+ See Also
+ --------
+ cheby1 : Filter design using order and critical points
+ buttord : Find order and critical points from passband and stopband spec
+ cheb2ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design a digital lowpass filter such that the passband is within 3 dB up
+ to 0.2*(fs/2), while rejecting at least -40 dB above 0.3*(fs/2). Plot its
+ frequency response, showing the passband and stopband constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.cheb1ord(0.2, 0.3, 3, 40)
+ >>> b, a = signal.cheby1(N, 3, Wn, 'low')
+ >>> w, h = signal.freqz(b, a)
+ >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev I lowpass filter fit to constraints')
+ >>> plt.xlabel('Normalized frequency')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([.01, 0.2, 0.2, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop
+ >>> plt.fill([0.3, 0.3, 2, 2], [ 9, -40, -40, 9], '0.9', lw=0) # pass
+ >>> plt.axis([0.08, 1, -60, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ fs = _validate_fs(fs, allow_none=True)
+ _validate_gpass_gstop(gpass, gstop)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby', xp=xp)
+
+ GSTOP = 10 ** (0.1 * builtins.abs(gstop))
+ GPASS = 10 ** (0.1 * builtins.abs(gpass))
+ v_pass_stop = math.acosh(math.sqrt((GSTOP - 1.0) / (GPASS - 1.0)))
+ ord = int(xp.ceil(v_pass_stop / xp.acosh(nat)))
+
+ # Natural frequencies are just the passband edges
+ wn = _postprocess_wn(passb, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+def cheb2ord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Chebyshev type II filter order selection.
+
+ Return the order of the lowest order digital or analog Chebyshev Type II
+ filter that loses no more than `gpass` dB in the passband and has at least
+ `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for a Chebyshev type II filter that meets specs.
+ wn : ndarray or float
+ The Chebyshev natural frequency (the "3dB frequency") for use with
+ `cheby2` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `cheby2`.
+
+ See Also
+ --------
+ cheby2 : Filter design using order and critical points
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design a digital bandstop filter which rejects -60 dB from 0.2*(fs/2) to
+ 0.5*(fs/2), while staying within 3 dB below 0.1*(fs/2) or above
+ 0.6*(fs/2). Plot its frequency response, showing the passband and
+ stopband constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ >>> b, a = signal.cheby2(N, 60, Wn, 'stop')
+ >>> w, h = signal.freqz(b, a)
+ >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev II bandstop filter fit to constraints')
+ >>> plt.xlabel('Normalized frequency')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([.01, .1, .1, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop
+ >>> plt.fill([.2, .2, .5, .5], [ 9, -60, -60, 9], '0.9', lw=0) # pass
+ >>> plt.fill([.6, .6, 2, 2], [-99, -3, -3, -99], '0.9', lw=0) # stop
+ >>> plt.axis([0.06, 1, -80, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ fs = _validate_fs(fs, allow_none=True)
+ _validate_gpass_gstop(gpass, gstop)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby', xp=xp)
+
+ GSTOP = 10 ** (0.1 * builtins.abs(gstop))
+ GPASS = 10 ** (0.1 * builtins.abs(gpass))
+ v_pass_stop = math.acosh(math.sqrt((GSTOP - 1.0) / (GPASS - 1.0)))
+ ord = int(xp.ceil(v_pass_stop / xp.acosh(nat)))
+
+ # Find frequency where analog response is -gpass dB.
+ # Then convert back from low-pass prototype to the original filter.
+
+ new_freq = math.cosh(1.0 / ord * v_pass_stop)
+ new_freq = 1.0 / new_freq
+
+ if filter_type == 1:
+ nat = passb / new_freq
+ elif filter_type == 2:
+ nat = passb * new_freq
+ elif filter_type == 3:
+ nat0 = (new_freq / 2.0 * (passb[0] - passb[1]) +
+ math.sqrt(new_freq ** 2 * (passb[1] - passb[0]) ** 2 / 4.0 +
+ passb[1] * passb[0]))
+ nat1 = passb[1] * passb[0] / nat0
+ nat = xp.asarray([float(nat0), float(nat1)])
+ elif filter_type == 4:
+ nat0 = (1.0 / (2.0 * new_freq) * (passb[0] - passb[1]) +
+ math.sqrt((passb[1] - passb[0]) ** 2 / (4.0 * new_freq ** 2) +
+ passb[1] * passb[0]))
+ nat1 = passb[0] * passb[1] / nat0
+ nat = xp.asarray([float(nat0), float(nat1)])
+
+ wn = _postprocess_wn(nat, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+_POW10_LOG10 = math.log(10)
+
+
+def _pow10m1(x):
+ """10 ** x - 1 for x near 0"""
+ return math.expm1(_POW10_LOG10 * x)
+
+
+def ellipord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Elliptic (Cauer) filter order selection.
+
+ Return the order of the lowest order digital or analog elliptic filter
+ that loses no more than `gpass` dB in the passband and has at least
+ `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for an Elliptic (Cauer) filter that meets specs.
+ wn : ndarray or float
+ The Chebyshev natural frequency (the "3dB frequency") for use with
+ `ellip` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `ellip`.
+
+ See Also
+ --------
+ ellip : Filter design using order and critical points
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, cheb2ord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design an analog highpass filter such that the passband is within 3 dB
+ above 30 rad/s, while rejecting -60 dB at 10 rad/s. Plot its
+ frequency response, showing the passband and stopband constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.ellipord(30, 10, 3, 60, True)
+ >>> b, a = signal.ellip(N, 3, 60, Wn, 'high', True)
+ >>> w, h = signal.freqs(b, a, np.logspace(0, 3, 500))
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Elliptical highpass filter fit to constraints')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([.1, 10, 10, .1], [1e4, 1e4, -60, -60], '0.9', lw=0) # stop
+ >>> plt.fill([30, 30, 1e9, 1e9], [-99, -3, -3, -99], '0.9', lw=0) # pass
+ >>> plt.axis([1, 300, -80, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ fs = _validate_fs(fs, allow_none=True)
+ _validate_gpass_gstop(gpass, gstop)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'ellip', xp=xp)
+
+ arg1_sq = _pow10m1(0.1 * gpass) / _pow10m1(0.1 * gstop)
+ arg0 = 1.0 / nat
+ arg0 = np.asarray(arg0)
+ d0 = special.ellipk(arg0 ** 2), special.ellipkm1(arg0 ** 2)
+ d1 = special.ellipk(arg1_sq), special.ellipkm1(arg1_sq)
+ ord = int(np.ceil(d0[0] * d1[1] / (d0[1] * d1[0])))
+
+ wn = _postprocess_wn(passb, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+def buttap(N, *, xp=None, device=None):
+ """Return (z,p,k) for analog prototype of Nth-order Butterworth filter.
+
+ The filter will have an angular (e.g., rad/s) cutoff frequency of 1.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[float64]
+ Zeros of the transfer function. Is always an empty array.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ butter : Filter design function using this prototype
+
+ """
+ if xp is None:
+ xp = np_compat
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ z = xp.asarray([], device=device, dtype=xp.float64)
+ m = xp.arange(-N+1, N, 2, device=device, dtype=xp.float64)
+ # Middle value is 0 to ensure an exactly real pole
+ p = -xp.exp(1j * xp.pi * m / (2 * N))
+ k = 1.0
+ return z, p, k
+
+
+def cheb1ap(N, rp, *, xp=None, device=None):
+ """
+ Return (z,p,k) for Nth-order Chebyshev type I analog lowpass filter.
+
+ The returned filter prototype has `rp` decibels of ripple in the passband.
+
+ The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
+ defined as the point at which the gain first drops below ``-rp``.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ rp : float
+ The ripple intensity
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[float64]
+ Zeros of the transfer function. Is always an empty array.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ cheby1 : Filter design function using this prototype
+
+ """
+ if xp is None:
+ xp = np_compat
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ elif N == 0:
+ # Avoid divide-by-zero error
+ # Even order filters have DC gain of -rp dB
+ return (
+ xp.asarray([], device=device, dtype=xp.float64),
+ xp.asarray([], device=device, dtype=xp.complex128), 10**(-rp/20)
+ )
+ z = xp.asarray([], device=device, dtype=xp.float64)
+
+ # Ripple factor (epsilon)
+ eps = math.sqrt(10 ** (0.1 * rp) - 1.0)
+ mu = 1.0 / N * math.asinh(1 / eps)
+
+ # Arrange poles in an ellipse on the left half of the S-plane
+ m = xp.arange(-N+1, N, 2, dtype=xp.float64, device=device)
+ theta = xp.pi * m / (2*N)
+ p = -xp.sinh(mu + 1j*theta)
+
+ k = xp.real(xp.prod(-p, axis=0))
+ if N % 2 == 0:
+ k = k / math.sqrt(1 + eps * eps)
+
+ return z, p, k
+
+
+def cheb2ap(N, rs, *, xp=None, device=None):
+ """
+ Return (z,p,k) for Nth-order Chebyshev type II analog lowpass filter.
+
+ The returned filter prototype has attenuation of at least ``rs`` decibels
+ in the stopband.
+
+ The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
+ defined as the point at which the attenuation first reaches ``rs``.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ rs : float
+ The attenuation in the stopband
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[complex128]
+ Zeros of the transfer function.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ cheby2 : Filter design function using this prototype
+
+ """
+ if xp is None:
+ xp = np_compat
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ elif N == 0:
+ # Avoid divide-by-zero warning
+ return (
+ xp.asarray([], device=device, dtype=xp.complex128),
+ xp.asarray([], device=device, dtype=xp.complex128),
+ 1.0
+ )
+
+ # Ripple factor (epsilon)
+ de = 1.0 / math.sqrt(10 ** (0.1 * rs) - 1)
+ mu = math.asinh(1.0 / de) / N
+
+ if N % 2:
+ m = xp.concat(
+ (xp.arange(-N + 1, 0, 2, dtype=xp.float64, device=device),
+ xp.arange(2, N, 2, dtype=xp.float64, device=device)
+ )
+ )
+ else:
+ m = xp.arange(-N+1, N, 2, dtype=xp.float64, device=device)
+
+ z = 1j / xp.sin(m * xp.pi / (2 * N))
+
+ # Poles around the unit circle like Butterworth
+ m1 = xp.arange(-N+1, N, 2, dtype=xp.float64, device=device)
+ theta1 = xp.pi * m1 / (2 * N)
+ p = -1 / xp.sinh(mu + 1j*theta1)
+
+ k = xp.real(xp.prod(-p, axis=0) / xp.prod(-z, axis=0))
+ return z, p, k
+
+
+EPSILON = 2e-16
+
+# number of terms in solving degree equation
+_ELLIPDEG_MMAX = 7
+
+
+def _ellipdeg(n, m1):
+ """Solve degree equation using nomes
+
+ Given n, m1, solve
+ n * K(m) / K'(m) = K1(m1) / K1'(m1)
+ for m
+
+ See [1], Eq. (49)
+
+ References
+ ----------
+ .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
+ https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
+ """
+ K1 = special.ellipk(m1)
+ K1p = special.ellipkm1(m1)
+
+ q1 = np.exp(-np.pi * K1p / K1)
+ q = q1 ** (1/n)
+
+ mnum = np.arange(_ELLIPDEG_MMAX + 1)
+ mden = np.arange(1, _ELLIPDEG_MMAX + 2)
+
+ num = np.sum(q ** (mnum * (mnum+1)))
+ den = 1 + 2 * np.sum(q ** (mden**2))
+
+ return 16 * q * (num / den) ** 4
+
+
+# Maximum number of iterations in Landen transformation recursion
+# sequence. 10 is conservative; unit tests pass with 4, Orfanidis
+# (see _arc_jac_cn [1]) suggests 5.
+_ARC_JAC_SN_MAXITER = 10
+
+
+def _arc_jac_sn(w, m):
+ """Inverse Jacobian elliptic sn
+
+ Solve for z in w = sn(z, m)
+
+ Parameters
+ ----------
+ w : complex scalar
+ argument
+
+ m : scalar
+ modulus; in interval [0, 1]
+
+
+ See [1], Eq. (56)
+
+ References
+ ----------
+ .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
+ https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
+
+ """
+
+ def _complement(kx):
+ # (1-k**2) ** 0.5; the expression below
+ # works for small kx
+ return ((1 - kx) * (1 + kx)) ** 0.5
+
+ k = m ** 0.5
+
+ if k > 1:
+ return np.nan
+ elif k == 1:
+ return np.arctanh(w)
+
+ ks = [k]
+ niter = 0
+ while ks[-1] != 0:
+ k_ = ks[-1]
+ k_p = _complement(k_)
+ ks.append((1 - k_p) / (1 + k_p))
+ niter += 1
+ if niter > _ARC_JAC_SN_MAXITER:
+ raise ValueError('Landen transformation not converging')
+
+ K = np.prod(1 + np.array(ks[1:])) * np.pi/2
+
+ wns = [w]
+
+ for kn, knext in zip(ks[:-1], ks[1:]):
+ wn = wns[-1]
+ wnext = (2 * wn /
+ ((1 + knext) * (1 + _complement(kn * wn))))
+ wns.append(wnext)
+
+ u = 2 / np.pi * np.arcsin(wns[-1])
+
+ z = K * u
+ return z
+
+
+def _arc_jac_sc1(w, m):
+ """Real inverse Jacobian sc, with complementary modulus
+
+ Solve for z in w = sc(z, 1-m)
+
+ w - real scalar
+
+ m - modulus
+
+ From [1], sc(z, m) = -i * sn(i * z, 1 - m)
+
+ References
+ ----------
+ # noqa: E501
+ .. [1] https://functions.wolfram.com/EllipticFunctions/JacobiSC/introductions/JacobiPQs/ShowAll.html,
+ "Representations through other Jacobi functions"
+
+ """
+
+ zcomplex = _arc_jac_sn(1j * w, m)
+ if abs(zcomplex.real) > 1e-14:
+ raise ValueError
+
+ return zcomplex.imag
+
+
+def ellipap(N, rp, rs, *, xp=None, device=None):
+ """Return (z,p,k) of Nth-order elliptic analog lowpass filter.
+
+ The filter is a normalized prototype that has `rp` decibels of ripple
+ in the passband and a stopband `rs` decibels down.
+
+ The filter's angular (e.g., rad/s) cutoff frequency is normalized to 1,
+ defined as the point at which the gain first drops below ``-rp``.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ rp : float
+ The passband ripple intensity
+ rs : float
+ The stopband attenuation
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[complex128]
+ Zeros of the transfer function.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ ellip : Filter design function using this prototype
+
+ References
+ ----------
+ .. [1] Lutovac, Tosic, and Evans, "Filter Design for Signal Processing",
+ Chapters 5 and 12.
+
+ .. [2] Orfanidis, "Lecture Notes on Elliptic Filter Design",
+ https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
+
+ """
+ if xp is None:
+ xp = np_compat
+
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ elif N == 0:
+ # Avoid divide-by-zero warning
+ # Even order filters have DC gain of -rp dB
+ return (
+ xp.asarray([], device=device, dtype=xp.complex128),
+ xp.asarray([], device=device, dtype=xp.complex128),
+ 10**(-rp/20)
+ )
+ elif N == 1:
+ p = -math.sqrt(1.0 / _pow10m1(0.1 * rp))
+ k = -p
+ z = []
+ return (
+ xp.asarray(z, device=device, dtype=xp.complex128),
+ xp.asarray(p, device=device, dtype=xp.complex128), k
+ )
+
+ eps_sq = _pow10m1(0.1 * rp)
+
+ eps = math.sqrt(eps_sq)
+ ck1_sq = eps_sq / _pow10m1(0.1 * rs)
+ if ck1_sq == 0:
+ raise ValueError("Cannot design a filter with given rp and rs"
+ " specifications.")
+
+ # do computations with numpy, xp.asarray the return values
+
+ val = special.ellipk(ck1_sq), special.ellipkm1(ck1_sq)
+
+ m = _ellipdeg(N, ck1_sq)
+
+ capk = special.ellipk(m)
+
+ j = np.arange(1 - N % 2, N, 2)
+ jj = len(j)
+
+ [s, c, d, phi] = special.ellipj(j * capk / N, m * np.ones(jj))
+ snew = np.compress(abs(s) > EPSILON, s, axis=-1)
+ z = 1.0 / (np.sqrt(m) * snew)
+ z = 1j * z
+ z = np.concatenate((z, np.conjugate(z)))
+
+ r = _arc_jac_sc1(1. / eps, ck1_sq)
+ v0 = capk * r / (N * val[0])
+
+ [sv, cv, dv, phi] = special.ellipj(v0, 1 - m)
+ p = -(c * d * sv * cv + 1j * s * dv) / (1 - (d * sv) ** 2.0)
+
+ if N % 2:
+ newp = np.compress(
+ abs(p.imag) > EPSILON * np.sqrt(np.sum(p * np.conjugate(p), axis=0).real),
+ p, axis=-1
+ )
+ p = np.concatenate((p, np.conjugate(newp)))
+ else:
+ p = np.concatenate((p, np.conjugate(p)))
+
+ k = (np.prod(-p, axis=0) / np.prod(-z, axis=0)).real
+ if N % 2 == 0:
+ k = k / np.sqrt(1 + eps_sq)
+
+ return (
+ xp.asarray(z, device=device, dtype=xp.complex128),
+ xp.asarray(p, device=device, dtype=xp.complex128), float(k)
+ )
+
+
+# TODO: Make this a real public function scipy.misc.ff
+def _falling_factorial(x, n):
+ r"""
+ Return the factorial of `x` to the `n` falling.
+
+ This is defined as:
+
+ .. math:: x^\underline n = (x)_n = x (x-1) \cdots (x-n+1)
+
+ This can more efficiently calculate ratios of factorials, since:
+
+ n!/m! == falling_factorial(n, n-m)
+
+ where n >= m
+
+ skipping the factors that cancel out
+
+ the usual factorial n! == ff(n, n)
+ """
+ val = 1
+ for k in range(x - n + 1, x + 1):
+ val *= k
+ return val
+
+
+def _bessel_poly(n, reverse=False):
+ """
+ Return the coefficients of Bessel polynomial of degree `n`
+
+ If `reverse` is true, a reverse Bessel polynomial is output.
+
+ Output is a list of coefficients:
+ [1] = 1
+ [1, 1] = 1*s + 1
+ [1, 3, 3] = 1*s^2 + 3*s + 3
+ [1, 6, 15, 15] = 1*s^3 + 6*s^2 + 15*s + 15
+ [1, 10, 45, 105, 105] = 1*s^4 + 10*s^3 + 45*s^2 + 105*s + 105
+ etc.
+
+ Output is a Python list of arbitrary precision long ints, so n is only
+ limited by your hardware's memory.
+
+ Sequence is http://oeis.org/A001498, and output can be confirmed to
+ match http://oeis.org/A001498/b001498.txt :
+
+ .. code_block:: python
+
+ from scipy.signal._filter_design import _bessel_poly
+ i = 0
+ for n in range(51):
+ for x in _bessel_poly(n, reverse=True):
+ print(i, x)
+ i += 1
+
+ """
+ if abs(int(n)) != n:
+ raise ValueError("Polynomial order must be a nonnegative integer")
+ else:
+ n = int(n) # np.int32 doesn't work, for instance
+
+ out = []
+ for k in range(n + 1):
+ num = _falling_factorial(2*n - k, n)
+ den = 2**(n - k) * math.factorial(k)
+ out.append(num // den)
+
+ if reverse:
+ return out[::-1]
+ else:
+ return out
+
+
+def _campos_zeros(n):
+ """
+ Return approximate zero locations of Bessel polynomials y_n(x) for order
+ `n` using polynomial fit (Campos-Calderon 2011)
+ """
+ if n == 1:
+ return np.asarray([-1+0j])
+
+ s = npp_polyval(n, [0, 0, 2, 0, -3, 1])
+ b3 = npp_polyval(n, [16, -8]) / s
+ b2 = npp_polyval(n, [-24, -12, 12]) / s
+ b1 = npp_polyval(n, [8, 24, -12, -2]) / s
+ b0 = npp_polyval(n, [0, -6, 0, 5, -1]) / s
+
+ r = npp_polyval(n, [0, 0, 2, 1])
+ a1 = npp_polyval(n, [-6, -6]) / r
+ a2 = 6 / r
+
+ k = np.arange(1, n+1)
+ x = npp_polyval(k, [0, a1, a2])
+ y = npp_polyval(k, [b0, b1, b2, b3])
+
+ return x + 1j*y
+
+
+def _aberth(f, fp, x0, tol=1e-15, maxiter=50):
+ """
+ Given a function `f`, its first derivative `fp`, and a set of initial
+ guesses `x0`, simultaneously find the roots of the polynomial using the
+ Aberth-Ehrlich method.
+
+ ``len(x0)`` should equal the number of roots of `f`.
+
+ (This is not a complete implementation of Bini's algorithm.)
+ """
+
+ N = len(x0)
+
+ x = np.array(x0, complex)
+ beta = np.empty_like(x0)
+
+ for iteration in range(maxiter):
+ alpha = -f(x) / fp(x) # Newton's method
+
+ # Model "repulsion" between zeros
+ for k in range(N):
+ beta[k] = np.sum(1/(x[k] - x[k+1:]))
+ beta[k] += np.sum(1/(x[k] - x[:k]))
+
+ x += alpha / (1 + alpha * beta)
+
+ if not all(np.isfinite(x)):
+ raise RuntimeError('Root-finding calculation failed')
+
+ # Mekwi: The iterative process can be stopped when |hn| has become
+ # less than the largest error one is willing to permit in the root.
+ if all(abs(alpha) <= tol):
+ break
+ else:
+ raise Exception('Zeros failed to converge')
+
+ return x
+
+
+def _bessel_zeros(N):
+ """
+ Find zeros of ordinary Bessel polynomial of order `N`, by root-finding of
+ modified Bessel function of the second kind
+ """
+ if N == 0:
+ return np.asarray([])
+
+ # Generate starting points
+ x0 = _campos_zeros(N)
+
+ # Zeros are the same for exp(1/x)*K_{N+0.5}(1/x) and Nth-order ordinary
+ # Bessel polynomial y_N(x)
+ def f(x):
+ return special.kve(N+0.5, 1/x)
+
+ # First derivative of above
+ def fp(x):
+ return (special.kve(N-0.5, 1/x)/(2*x**2) -
+ special.kve(N+0.5, 1/x)/(x**2) +
+ special.kve(N+1.5, 1/x)/(2*x**2))
+
+ # Starting points converge to true zeros
+ x = _aberth(f, fp, x0)
+
+ # Improve precision using Newton's method on each
+ for i in range(len(x)):
+ x[i] = optimize.newton(f, x[i], fp, tol=1e-15)
+
+ # Average complex conjugates to make them exactly symmetrical
+ x = np.mean((x, x[::-1].conj()), 0)
+
+ # Zeros should sum to -1
+ if abs(np.sum(x) + 1) > 1e-15:
+ raise RuntimeError('Generated zeros are inaccurate')
+
+ return x
+
+
+def _norm_factor(p, k):
+ """
+ Numerically find frequency shift to apply to delay-normalized filter such
+ that -3 dB point is at 1 rad/sec.
+
+ `p` is an array_like of polynomial poles
+ `k` is a float gain
+
+ First 10 values are listed in "Bessel Scale Factors" table,
+ "Bessel Filters Polynomials, Poles and Circuit Elements 2003, C. Bond."
+ """
+ p = np.asarray(p, dtype=np.complex128)
+
+ def G(w):
+ """
+ Gain of filter
+ """
+ return np.abs(k / np.prod(1j*w - p))
+
+ def cutoff(w):
+ """
+ When gain = -3 dB, return 0
+ """
+ return G(w) - 1/math.sqrt(2)
+
+ return optimize.newton(cutoff, 1.5)
+
+
+def besselap(N, norm='phase', *, xp=None, device=None):
+ """
+ Return (z,p,k) for analog prototype of an Nth-order Bessel filter.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ norm : {'phase', 'delay', 'mag'}, optional
+ Frequency normalization:
+
+ ``phase``
+ The filter is normalized such that the phase response reaches its
+ midpoint at an angular (e.g., rad/s) cutoff frequency of 1. This
+ happens for both low-pass and high-pass filters, so this is the
+ "phase-matched" case. [6]_
+
+ The magnitude response asymptotes are the same as a Butterworth
+ filter of the same order with a cutoff of `Wn`.
+
+ This is the default, and matches MATLAB's implementation.
+
+ ``delay``
+ The filter is normalized such that the group delay in the passband
+ is 1 (e.g., 1 second). This is the "natural" type obtained by
+ solving Bessel polynomials
+
+ ``mag``
+ The filter is normalized such that the gain magnitude is -3 dB at
+ angular frequency 1. This is called "frequency normalization" by
+ Bond. [1]_
+
+ .. versionadded:: 0.18.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[float64]
+ Zeros of the transfer function. Is always an empty array.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function. For phase-normalized, this is always 1.
+
+ See Also
+ --------
+ bessel : Filter design function using this prototype
+
+ Notes
+ -----
+ To find the pole locations, approximate starting points are generated [2]_
+ for the zeros of the ordinary Bessel polynomial [3]_, then the
+ Aberth-Ehrlich method [4]_ [5]_ is used on the Kv(x) Bessel function to
+ calculate more accurate zeros, and these locations are then inverted about
+ the unit circle.
+
+ References
+ ----------
+ .. [1] C.R. Bond, "Bessel Filter Constants",
+ http://www.crbond.com/papers/bsf.pdf
+ .. [2] Campos and Calderon, "Approximate closed-form formulas for the
+ zeros of the Bessel Polynomials", :arXiv:`1105.0957`.
+ .. [3] Thomson, W.E., "Delay Networks having Maximally Flat Frequency
+ Characteristics", Proceedings of the Institution of Electrical
+ Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490.
+ .. [4] Aberth, "Iteration Methods for Finding all Zeros of a Polynomial
+ Simultaneously", Mathematics of Computation, Vol. 27, No. 122,
+ April 1973
+ .. [5] Ehrlich, "A modified Newton method for polynomials", Communications
+ of the ACM, Vol. 10, Issue 2, pp. 107-108, Feb. 1967,
+ :doi:`10.1145/363067.363115`.
+ .. [6] Miller and Bohn, "A Bessel Filter Crossover, and Its Relation to
+ Others", RaneNote 147, 1998,
+ https://www.ranecommercial.com/legacy/note147.html
+
+ """
+ if xp is None:
+ xp = np_compat
+
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+
+ N = int(N) # calculation below doesn't always fit in np.int64
+ if N == 0:
+ p = []
+ k = 1
+ else:
+ # Find roots of reverse Bessel polynomial
+ p = 1/_bessel_zeros(N)
+
+ a_last = _falling_factorial(2*N, N) // 2**N
+
+ # Shift them to a different normalization if required
+ if norm in ('delay', 'mag'):
+ # Normalized for group delay of 1
+ k = a_last
+ if norm == 'mag':
+ # -3 dB magnitude point is at 1 rad/sec
+ norm_factor = _norm_factor(p, k)
+ p /= norm_factor
+ k = norm_factor**-N * a_last
+ elif norm == 'phase':
+ # Phase-matched (1/2 max phase shift at 1 rad/sec)
+ # Asymptotes are same as Butterworth filter
+ p *= 10**(-math.log10(a_last)/N)
+ k = 1
+ else:
+ raise ValueError('normalization not understood')
+
+ z = xp.asarray([], device=device, dtype=xp.float64)
+ return (
+ z,
+ xp.asarray(p, device=device, dtype=xp.complex128),
+ float(k)
+ )
+
+
+def iirnotch(w0, Q, fs=2.0, *, xp=None, device=None):
+ """
+ Design second-order IIR notch digital filter.
+
+ A notch filter is a band-stop filter with a narrow bandwidth
+ (high quality factor). It rejects a narrow frequency band and
+ leaves the rest of the spectrum little changed.
+
+ Parameters
+ ----------
+ w0 : float
+ Frequency to remove from a signal. If `fs` is specified, this is in
+ the same units as `fs`. By default, it is a normalized scalar that must
+ satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the
+ sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ notch filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+
+ See Also
+ --------
+ iirpeak
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ References
+ ----------
+ .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing",
+ Prentice-Hall, 1996
+
+ Examples
+ --------
+ Design and plot filter to remove the 60 Hz component from a
+ signal sampled at 200 Hz, using a quality factor Q = 30
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> fs = 200.0 # Sample frequency (Hz)
+ >>> f0 = 60.0 # Frequency to be removed from signal (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design notch filter
+ >>> b, a = signal.iirnotch(f0, Q, fs)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6))
+ >>> ax[0].plot(freq, 20*np.log10(abs(h)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 100])
+ >>> ax[0].set_ylim([-25, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 100])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+ """
+
+ return _design_notch_peak_filter(w0, Q, "notch", fs, xp=xp, device=device)
+
+
+def iirpeak(w0, Q, fs=2.0, *, xp=None, device=None):
+ """
+ Design second-order IIR peak (resonant) digital filter.
+
+ A peak filter is a band-pass filter with a narrow bandwidth
+ (high quality factor). It rejects components outside a narrow
+ frequency band.
+
+ Parameters
+ ----------
+ w0 : float
+ Frequency to be retained in a signal. If `fs` is specified, this is in
+ the same units as `fs`. By default, it is a normalized scalar that must
+ satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the
+ sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ peak filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+
+ See Also
+ --------
+ iirnotch
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ References
+ ----------
+ .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing",
+ Prentice-Hall, 1996
+
+ Examples
+ --------
+ Design and plot filter to remove the frequencies other than the 300 Hz
+ component from a signal sampled at 1000 Hz, using a quality factor Q = 30
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> fs = 1000.0 # Sample frequency (Hz)
+ >>> f0 = 300.0 # Frequency to be retained (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design peak filter
+ >>> b, a = signal.iirpeak(f0, Q, fs)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6))
+ >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 500])
+ >>> ax[0].set_ylim([-50, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 500])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+ """
+
+ return _design_notch_peak_filter(w0, Q, "peak", fs, xp=xp, device=device)
+
+
+def _design_notch_peak_filter(w0, Q, ftype, fs=2.0, *, xp=None, device=None):
+ """
+ Design notch or peak digital filter.
+
+ Parameters
+ ----------
+ w0 : float
+ Normalized frequency to remove from a signal. If `fs` is specified,
+ this is in the same units as `fs`. By default, it is a normalized
+ scalar that must satisfy ``0 < w0 < 1``, with ``w0 = 1``
+ corresponding to half of the sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ notch filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ ftype : str
+ The type of IIR filter to design:
+
+ - notch filter : ``notch``
+ - peak filter : ``peak``
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0:
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+ """
+ if xp is None:
+ xp = np_compat
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Guarantee that the inputs are floats
+ w0 = float(w0)
+ Q = float(Q)
+ w0 = 2 * w0 / fs
+
+ # Checks if w0 is within the range
+ if w0 > 1.0 or w0 < 0.0:
+ raise ValueError("w0 should be such that 0 < w0 < 1")
+
+ # Get bandwidth
+ bw = w0/Q
+
+ # Normalize inputs
+ bw = bw * xp.pi
+ w0 = w0 * xp.pi
+
+ if ftype not in ("notch", "peak"):
+ raise ValueError("Unknown ftype.")
+
+ # Compute beta according to Eqs. 11.3.4 (p.575) and 11.3.19 (p.579) from
+ # reference [1]. Due to assuming a -3 dB attenuation value, i.e, assuming
+ # gb = 1 / np.sqrt(2), the following terms simplify to:
+ # (np.sqrt(1.0 - gb**2.0) / gb) = 1
+ # (gb / np.sqrt(1.0 - gb**2.0)) = 1
+ beta = math.tan(bw / 2.0)
+
+ # Compute gain: formula 11.3.6 (p.575) from reference [1]
+ gain = 1.0 / (1.0 + beta)
+
+ # Compute numerator b and denominator a
+ # formulas 11.3.7 (p.575) and 11.3.21 (p.579)
+ # from reference [1]
+ if ftype == "notch":
+ b = gain * xp.asarray([1.0, -2.0*math.cos(w0), 1.0], device=device)
+ else:
+ b = (1.0 - gain) * xp.asarray([1.0, 0.0, -1.0], device=device)
+ a = xp.asarray([1.0, -2.0 * gain * math.cos(w0), (2.0*gain - 1.0)], device=device)
+
+ return b, a
+
+
+def iircomb(w0, Q, ftype='notch', fs=2.0, *, pass_zero=False, xp=None, device=None):
+ """
+ Design IIR notching or peaking digital comb filter.
+
+ A notching comb filter consists of regularly-spaced band-stop filters with
+ a narrow bandwidth (high quality factor). Each rejects a narrow frequency
+ band and leaves the rest of the spectrum little changed.
+
+ A peaking comb filter consists of regularly-spaced band-pass filters with
+ a narrow bandwidth (high quality factor). Each rejects components outside
+ a narrow frequency band.
+
+ Parameters
+ ----------
+ w0 : float
+ The fundamental frequency of the comb filter (the spacing between its
+ peaks). This must evenly divide the sampling frequency. If `fs` is
+ specified, this is in the same units as `fs`. By default, it is
+ a normalized scalar that must satisfy ``0 < w0 < 1``, with
+ ``w0 = 1`` corresponding to half of the sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ notch filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ ftype : {'notch', 'peak'}
+ The type of comb filter generated by the function. If 'notch', then
+ the Q factor applies to the notches. If 'peak', then the `Q` factor
+ applies to the peaks. Default is 'notch'.
+ fs : float, optional
+ The sampling frequency of the signal. Default is 2.0.
+ pass_zero : bool, optional
+ If False (default), the notches (nulls) of the filter are centered on
+ frequencies ``[0, w0, 2*w0, ...]``, and the peaks are centered on the
+ midpoints ``[w0/2, 3*w0/2, 5*w0/2, ...]``. If True, the peaks are centered
+ on ``[0, w0, 2*w0, ...]`` (passing zero frequency) and vice versa.
+
+ .. versionadded:: 1.9.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+
+ Raises
+ ------
+ ValueError
+ If `w0` is less than or equal to 0 or greater than or equal to
+ ``fs/2``, if `fs` is not divisible by `w0`, if `ftype`
+ is not 'notch' or 'peak'
+
+ See Also
+ --------
+ iirnotch
+ iirpeak
+
+ Notes
+ -----
+ For implementation details, see [1]_. The TF implementation of the
+ comb filter is numerically stable even at higher orders due to the
+ use of a single repeated pole, which won't suffer from precision loss.
+
+ References
+ ----------
+ .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing",
+ Prentice-Hall, 1996, ch. 11, "Digital Filter Design"
+
+ Examples
+ --------
+ Design and plot notching comb filter at 20 Hz for a
+ signal sampled at 200 Hz, using quality factor Q = 30
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> fs = 200.0 # Sample frequency (Hz)
+ >>> f0 = 20.0 # Frequency to be removed from signal (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design notching comb filter
+ >>> b, a = signal.iircomb(f0, Q, ftype='notch', fs=fs)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> response = abs(h)
+ >>> # To avoid divide by zero when graphing
+ >>> response[response == 0] = 1e-20
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
+ >>> ax[0].plot(freq, 20*np.log10(abs(response)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 100])
+ >>> ax[0].set_ylim([-30, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.mod(np.angle(h, deg=True) + 180, 360) - 180, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 100])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+
+ Design and plot peaking comb filter at 250 Hz for a
+ signal sampled at 1000 Hz, using quality factor Q = 30
+
+ >>> fs = 1000.0 # Sample frequency (Hz)
+ >>> f0 = 250.0 # Frequency to be retained (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design peaking filter
+ >>> b, a = signal.iircomb(f0, Q, ftype='peak', fs=fs, pass_zero=True)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> response = abs(h)
+ >>> # To avoid divide by zero when graphing
+ >>> response[response == 0] = 1e-20
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
+ >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 500])
+ >>> ax[0].set_ylim([-80, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.mod(np.angle(h)*180/np.pi + 180, 360) - 180, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 500])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+ """
+ if xp is None:
+ xp = np_compat
+
+ # Convert w0, Q, and fs to float
+ w0 = float(w0)
+ Q = float(Q)
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Check for invalid cutoff frequency or filter type
+ ftype = ftype.lower()
+ if not 0 < w0 < fs / 2:
+ raise ValueError(f"w0 must be between 0 and {fs / 2}"
+ f" (Nyquist), but given {w0}.")
+ if ftype not in ('notch', 'peak'):
+ raise ValueError('ftype must be either notch or peak.')
+
+ # Compute the order of the filter
+ N = round(fs / w0)
+
+ # Check for cutoff frequency divisibility
+ if abs(w0 - fs/N)/fs > 1e-14:
+ raise ValueError('fs must be divisible by w0.')
+
+ # Compute frequency in radians and filter bandwidth
+ # Eq. 11.3.1 (p. 574) from reference [1]
+ w0 = (2 * xp.pi * w0) / fs
+ w_delta = w0 / Q
+
+ # Define base gain values depending on notch or peak filter
+ # Compute -3dB attenuation
+ # Eqs. 11.4.1 and 11.4.2 (p. 582) from reference [1]
+ if ftype == 'notch':
+ G0, G = 1, 0
+ elif ftype == 'peak':
+ G0, G = 0, 1
+
+ # Compute beta according to Eq. 11.5.3 (p. 591) from reference [1]. Due to
+ # assuming a -3 dB attenuation value, i.e, assuming GB = 1 / np.sqrt(2),
+ # the following term simplifies to:
+ # np.sqrt((GB**2 - G0**2) / (G**2 - GB**2)) = 1
+ beta = math.tan(N * w_delta / 4)
+
+ # Compute filter coefficients
+ # Eq 11.5.1 (p. 590) variables a, b, c from reference [1]
+ ax = (1 - beta) / (1 + beta)
+ bx = (G0 + G * beta) / (1 + beta)
+ cx = (G0 - G * beta) / (1 + beta)
+
+ # Last coefficients are negative to get peaking comb that passes zero or
+ # notching comb that doesn't.
+ negative_coef = ((ftype == 'peak' and pass_zero) or
+ (ftype == 'notch' and not pass_zero))
+
+ # Compute numerator coefficients
+ # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1]
+ # b - cz^-N or b + cz^-N
+ b = xp.zeros(N + 1, device=device)
+ sgn = -1. if negative_coef else 1
+ xpx.at(b, 0).set(bx)
+ xpx.at(b, -1).set(sgn * cx)
+
+ # Compute denominator coefficients
+ # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1]
+ # 1 - az^-N or 1 + az^-N
+ a = xp.zeros(N + 1, device=device)
+ xpx.at(a, 0).set(1.)
+ xpx.at(a, -1).set(sgn * ax)
+
+ return b, a
+
+
+def _hz_to_erb(hz):
+ """
+ Utility for converting from frequency (Hz) to the
+ Equivalent Rectangular Bandwidth (ERB) scale
+ ERB = frequency / EarQ + minBW
+ """
+ EarQ = 9.26449
+ minBW = 24.7
+ return hz / EarQ + minBW
+
+
+def gammatone(freq, ftype, order=None, numtaps=None, fs=None, *, xp=None, device=None):
+ """
+ Gammatone filter design.
+
+ This function computes the coefficients of an FIR or IIR gammatone
+ digital filter [1]_.
+
+ Parameters
+ ----------
+ freq : float
+ Center frequency of the filter (expressed in the same units
+ as `fs`).
+ ftype : {'fir', 'iir'}
+ The type of filter the function generates. If 'fir', the function
+ will generate an Nth order FIR gammatone filter. If 'iir', the
+ function will generate an 8th order digital IIR filter, modeled as
+ as 4th order gammatone filter.
+ order : int, optional
+ The order of the filter. Only used when ``ftype='fir'``.
+ Default is 4 to model the human auditory system. Must be between
+ 0 and 24.
+ numtaps : int, optional
+ Length of the filter. Only used when ``ftype='fir'``.
+ Default is ``fs*0.015`` if `fs` is greater than 1000,
+ 15 if `fs` is less than or equal to 1000.
+ fs : float, optional
+ The sampling frequency of the signal. `freq` must be between
+ 0 and ``fs/2``. Default is 2.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials of the filter.
+
+ Raises
+ ------
+ ValueError
+ If `freq` is less than or equal to 0 or greater than or equal to
+ ``fs/2``, if `ftype` is not 'fir' or 'iir', if `order` is less than
+ or equal to 0 or greater than 24 when ``ftype='fir'``
+
+ See Also
+ --------
+ firwin
+ iirfilter
+
+ References
+ ----------
+ .. [1] Slaney, Malcolm, "An Efficient Implementation of the
+ Patterson-Holdsworth Auditory Filter Bank", Apple Computer
+ Technical Report 35, 1993, pp.3-8, 34-39.
+
+ Examples
+ --------
+ 16-sample 4th order FIR Gammatone filter centered at 440 Hz
+
+ >>> from scipy import signal
+ >>> signal.gammatone(440, 'fir', numtaps=16, fs=16000)
+ (array([ 0.00000000e+00, 2.22196719e-07, 1.64942101e-06, 4.99298227e-06,
+ 1.01993969e-05, 1.63125770e-05, 2.14648940e-05, 2.29947263e-05,
+ 1.76776931e-05, 2.04980537e-06, -2.72062858e-05, -7.28455299e-05,
+ -1.36651076e-04, -2.19066855e-04, -3.18905076e-04, -4.33156712e-04]),
+ [1.0])
+
+ IIR Gammatone filter centered at 440 Hz
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> fc, fs = 440, 16000
+ >>> b, a = signal.gammatone(fc, 'iir', fs=fs)
+ >>> w, h = signal.freqz(b, a)
+ >>> plt.plot(w * fs / (2 * np.pi), 20 * np.log10(abs(h)))
+ >>> plt.xscale('log')
+ >>> plt.title('Gammatone filter frequency response')
+ >>> plt.xlabel('Frequency [Hz]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(fc, color='green') # cutoff frequency
+ >>> plt.show()
+ """
+ if xp is None:
+ xp = np_compat
+
+ # Converts freq to float
+ freq = float(freq)
+
+ # Set sampling rate if not passed
+ if fs is None:
+ fs = 2
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Check for invalid cutoff frequency or filter type
+ ftype = ftype.lower()
+ filter_types = ['fir', 'iir']
+ if not 0 < freq < fs / 2:
+ raise ValueError(f"The frequency must be between 0 and {fs / 2}"
+ f" (Nyquist), but given {freq}.")
+ if ftype not in filter_types:
+ raise ValueError('ftype must be either fir or iir.')
+
+ # Calculate FIR gammatone filter
+ if ftype == 'fir':
+ # Set order and numtaps if not passed
+ if order is None:
+ order = 4
+ order = operator.index(order)
+
+ if numtaps is None:
+ numtaps = max(int(fs * 0.015), 15)
+ numtaps = operator.index(numtaps)
+
+ # Check for invalid order
+ if not 0 < order <= 24:
+ raise ValueError("Invalid order: order must be > 0 and <= 24.")
+
+ # Gammatone impulse response settings
+ t = xp.arange(numtaps, device=device, dtype=xp_default_dtype(xp)) / fs
+ bw = 1.019 * _hz_to_erb(freq)
+
+ # Calculate the FIR gammatone filter
+ b = (t ** (order - 1)) * xp.exp(-2 * xp.pi * bw * t)
+ b = b * xp.cos(2 * xp.pi * freq * t)
+
+ # Scale the FIR filter so the frequency response is 1 at cutoff
+ scale_factor = 2 * (2 * xp.pi * bw) ** (order)
+ scale_factor /= float_factorial(order - 1)
+ scale_factor /= fs
+ b = b * scale_factor
+ a = xp.asarray([1.0], device=device)
+
+ # Calculate IIR gammatone filter
+ elif ftype == 'iir':
+ # Raise warning if order and/or numtaps is passed
+ if order is not None:
+ warnings.warn('order is not used for IIR gammatone filter.', stacklevel=2)
+ if numtaps is not None:
+ warnings.warn('numtaps is not used for IIR gammatone filter.', stacklevel=2)
+
+ # Gammatone impulse response settings
+ T = 1./fs
+ bw = 2 * math.pi * 1.019 * _hz_to_erb(freq)
+ fr = 2 * freq * math.pi * T
+ bwT = bw * T
+
+ # Calculate the gain to normalize the volume at the center frequency
+ g1 = -2 * cmath.exp(2j * fr) * T
+ g2 = 2 * cmath.exp(-(bwT) + 1j * fr) * T
+ g3 = math.sqrt(3 + 2 ** (3 / 2)) * math.sin(fr)
+ g4 = math.sqrt(3 - 2 ** (3 / 2)) * math.sin(fr)
+ g5 = cmath.exp(2j * fr)
+
+ g = g1 + g2 * (math.cos(fr) - g4)
+ g *= (g1 + g2 * (math.cos(fr) + g4))
+ g *= (g1 + g2 * (math.cos(fr) - g3))
+ g *= (g1 + g2 * (math.cos(fr) + g3))
+ g /= ((-2 / math.exp(2 * bwT) - 2 * g5 + 2 * (1 + g5) / math.exp(bwT)) ** 4)
+ g = math.hypot(g.real, g.imag)
+
+ # Create empty filter coefficient lists
+ b = [None] * 5 #np.empty(5)
+ a = [None] * 9 # np.empty(9)
+
+ # Calculate the numerator coefficients
+ b[0] = (T ** 4) / g
+ b[1] = -4 * T ** 4 * math.cos(fr) / math.exp(bw * T) / g
+ b[2] = 6 * T ** 4 * math.cos(2 * fr) / math.exp(2 * bw * T) / g
+ b[3] = -4 * T ** 4 * math.cos(3 * fr) / math.exp(3 * bw * T) / g
+ b[4] = T ** 4 * math.cos(4 * fr) / math.exp(4 * bw * T) / g
+
+ # Calculate the denominator coefficients
+ a[0] = 1
+ a[1] = -8 * math.cos(fr) / math.exp(bw * T)
+ a[2] = 4 * (4 + 3 * math.cos(2 * fr)) / math.exp(2 * bw * T)
+ a[3] = -8 * (6 * math.cos(fr) + math.cos(3 * fr))
+ a[3] /= math.exp(3 * bw * T)
+ a[4] = 2 * (18 + 16 * math.cos(2 * fr) + math.cos(4 * fr))
+ a[4] /= math.exp(4 * bw * T)
+ a[5] = -8 * (6 * math.cos(fr) + math.cos(3 * fr))
+ a[5] /= math.exp(5 * bw * T)
+ a[6] = 4 * (4 + 3 * math.cos(2 * fr)) / math.exp(6 * bw * T)
+ a[7] = -8 * math.cos(fr) / math.exp(7 * bw * T)
+ a[8] = math.exp(-8 * bw * T)
+
+ return xp.asarray(b, device=device), xp.asarray(a, device=device)
+
+
+filter_dict = {'butter': [buttap, buttord],
+ 'butterworth': [buttap, buttord],
+
+ 'cauer': [ellipap, ellipord],
+ 'elliptic': [ellipap, ellipord],
+ 'ellip': [ellipap, ellipord],
+
+ 'bessel': [besselap],
+ 'bessel_phase': [besselap],
+ 'bessel_delay': [besselap],
+ 'bessel_mag': [besselap],
+
+ 'cheby1': [cheb1ap, cheb1ord],
+ 'chebyshev1': [cheb1ap, cheb1ord],
+ 'chebyshevi': [cheb1ap, cheb1ord],
+
+ 'cheby2': [cheb2ap, cheb2ord],
+ 'chebyshev2': [cheb2ap, cheb2ord],
+ 'chebyshevii': [cheb2ap, cheb2ord],
+ }
+
+band_dict = {'band': 'bandpass',
+ 'bandpass': 'bandpass',
+ 'pass': 'bandpass',
+ 'bp': 'bandpass',
+
+ 'bs': 'bandstop',
+ 'bandstop': 'bandstop',
+ 'bands': 'bandstop',
+ 'stop': 'bandstop',
+
+ 'l': 'lowpass',
+ 'low': 'lowpass',
+ 'lowpass': 'lowpass',
+ 'lp': 'lowpass',
+
+ 'high': 'highpass',
+ 'highpass': 'highpass',
+ 'h': 'highpass',
+ 'hp': 'highpass',
+ }
+
+bessel_norms = {'bessel': 'phase',
+ 'bessel_phase': 'phase',
+ 'bessel_delay': 'delay',
+ 'bessel_mag': 'mag'}
+
+
+########## complete the docstrings, on import
+_xp_device_snippet = {'xp_device_snippet':
+"""\
+xp : array_namespace, optional
+ Optional array namespace.
+ Should be compatible with the array API standard, or supported by array-api-compat.
+ Default: ``numpy``
+device : any
+ optional device specification for output. Should match one of the
+ supported device specification in ``xp``.
+"""
+}
+
+
+_names = ["buttap", "cheb1ap", "cheb2ap", "ellipap", "besselap",
+ "iirnotch", "iirpeak", "iircomb", "gammatone",
+]
+for name in _names:
+ window = vars()[name]
+ window.__doc__ = doccer.docformat(window.__doc__, _xp_device_snippet)
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_fir_filter_design.py b/.venv/lib/python3.12/site-packages/scipy/signal/_fir_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..23d229c323d85bec7d796a66009a416251e68d1d
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_fir_filter_design.py
@@ -0,0 +1,1553 @@
+"""Functions for FIR filter design."""
+
+from math import ceil, log, log2
+import warnings
+from typing import Literal
+
+import numpy as np
+from scipy.fft import irfft, fft, ifft
+from scipy.linalg import (toeplitz, hankel, solve, LinAlgError, LinAlgWarning,
+ lstsq)
+from scipy.signal._arraytools import _validate_fs
+from .windows import get_window
+from . import _sigtools
+
+from scipy._lib._array_api import array_namespace, xp_size, xp_default_dtype
+import scipy._external.array_api_extra as xpx
+
+
+__all__ = ['kaiser_beta', 'kaiser_atten', 'kaiserord',
+ 'firwin', 'firwin2', 'firwin_2d', 'remez', 'firls', 'minimum_phase']
+
+
+# Some notes on function parameters:
+#
+# `cutoff` and `width` are given as numbers between 0 and 1. These are
+# relative frequencies, expressed as a fraction of the Nyquist frequency.
+# For example, if the Nyquist frequency is 2 KHz, then width=0.15 is a width
+# of 300 Hz.
+#
+# The `order` of a FIR filter is one less than the number of taps.
+# This is a potential source of confusion, so in the following code,
+# we will always use the number of taps as the parameterization of
+# the 'size' of the filter. The "number of taps" means the number
+# of coefficients, which is the same as the length of the impulse
+# response of the filter.
+
+
+def kaiser_beta(a):
+ """Compute the Kaiser parameter `beta`, given the attenuation `a`.
+
+ Parameters
+ ----------
+ a : float
+ The desired attenuation in the stopband and maximum ripple in
+ the passband, in dB. This should be a *positive* number.
+
+ Returns
+ -------
+ beta : float
+ The `beta` parameter to be used in the formula for a Kaiser window.
+
+ References
+ ----------
+ Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476.
+
+ Examples
+ --------
+ Suppose we want to design a lowpass filter, with 65 dB attenuation
+ in the stop band. The Kaiser window parameter to be used in the
+ window method is computed by ``kaiser_beta(65)``:
+
+ >>> from scipy.signal import kaiser_beta
+ >>> kaiser_beta(65)
+ 6.20426
+
+ """
+ if a > 50:
+ beta = 0.1102 * (a - 8.7)
+ elif a > 21:
+ beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21)
+ else:
+ beta = 0.0
+ return beta
+
+
+def kaiser_atten(numtaps, width):
+ """Compute the attenuation of a Kaiser FIR filter.
+
+ Given the number of taps `N` and the transition width `width`, compute the
+ attenuation `a` in dB, given by Kaiser's formula:
+
+ a = 2.285 * (N - 1) * pi * width + 7.95
+
+ Parameters
+ ----------
+ numtaps : int
+ The number of taps in the FIR filter.
+ width : float
+ The desired width of the transition region between passband and
+ stopband (or, in general, at any discontinuity) for the filter,
+ expressed as a fraction of the Nyquist frequency.
+
+ Returns
+ -------
+ a : float
+ The attenuation of the ripple, in dB.
+
+ See Also
+ --------
+ kaiserord, kaiser_beta
+
+ Examples
+ --------
+ Suppose we want to design a FIR filter using the Kaiser window method
+ that will have 211 taps and a transition width of 9 Hz for a signal that
+ is sampled at 480 Hz. Expressed as a fraction of the Nyquist frequency,
+ the width is 9/(0.5*480) = 0.0375. The approximate attenuation (in dB)
+ is computed as follows:
+
+ >>> from scipy.signal import kaiser_atten
+ >>> kaiser_atten(211, 0.0375)
+ 64.48099630593983
+
+ """
+ a = 2.285 * (numtaps - 1) * np.pi * width + 7.95
+ return a
+
+
+def kaiserord(ripple, width):
+ """
+ Determine the filter window parameters for the Kaiser window method.
+
+ The parameters returned by this function are generally used to create
+ a finite impulse response filter using the window method, with either
+ `firwin` or `firwin2`.
+
+ Parameters
+ ----------
+ ripple : float
+ Upper bound for the deviation (in dB) of the magnitude of the
+ filter's frequency response from that of the desired filter (not
+ including frequencies in any transition intervals). That is, if w
+ is the frequency expressed as a fraction of the Nyquist frequency,
+ A(w) is the actual frequency response of the filter and D(w) is the
+ desired frequency response, the design requirement is that::
+
+ abs(A(w) - D(w))) < 10**(-ripple/20)
+
+ for 0 <= w <= 1 and w not in a transition interval.
+ width : float
+ Width of transition region, normalized so that 1 corresponds to pi
+ radians / sample. That is, the frequency is expressed as a fraction
+ of the Nyquist frequency.
+
+ Returns
+ -------
+ numtaps : int
+ The length of the Kaiser window.
+ beta : float
+ The beta parameter for the Kaiser window.
+
+ See Also
+ --------
+ kaiser_beta, kaiser_atten
+
+ Notes
+ -----
+ There are several ways to obtain the Kaiser window:
+
+ - ``signal.windows.kaiser(numtaps, beta, sym=True)``
+ - ``signal.get_window(beta, numtaps)``
+ - ``signal.get_window(('kaiser', beta), numtaps)``
+
+ The empirical equations discovered by Kaiser are used.
+
+ References
+ ----------
+ Oppenheim, Schafer, "Discrete-Time Signal Processing", pp.475-476.
+
+ Examples
+ --------
+ We will use the Kaiser window method to design a lowpass FIR filter
+ for a signal that is sampled at 1000 Hz.
+
+ We want at least 65 dB rejection in the stop band, and in the pass
+ band the gain should vary no more than 0.5%.
+
+ We want a cutoff frequency of 175 Hz, with a transition between the
+ pass band and the stop band of 24 Hz. That is, in the band [0, 163],
+ the gain varies no more than 0.5%, and in the band [187, 500], the
+ signal is attenuated by at least 65 dB.
+
+ >>> import numpy as np
+ >>> from scipy.signal import kaiserord, firwin, freqz
+ >>> import matplotlib.pyplot as plt
+ >>> fs = 1000.0
+ >>> cutoff = 175
+ >>> width = 24
+
+ The Kaiser method accepts just a single parameter to control the pass
+ band ripple and the stop band rejection, so we use the more restrictive
+ of the two. In this case, the pass band ripple is 0.005, or 46.02 dB,
+ so we will use 65 dB as the design parameter.
+
+ Use `kaiserord` to determine the length of the filter and the
+ parameter for the Kaiser window.
+
+ >>> numtaps, beta = kaiserord(65, width/(0.5*fs))
+ >>> numtaps
+ 167
+ >>> beta
+ 6.20426
+
+ Use `firwin` to create the FIR filter.
+
+ >>> taps = firwin(numtaps, cutoff, window=('kaiser', beta),
+ ... scale=False, fs=fs)
+
+ Compute the frequency response of the filter. ``w`` is the array of
+ frequencies, and ``h`` is the corresponding complex array of frequency
+ responses.
+
+ >>> w, h = freqz(taps, worN=8000)
+ >>> w *= 0.5*fs/np.pi # Convert w to Hz.
+
+ Compute the deviation of the magnitude of the filter's response from
+ that of the ideal lowpass filter. Values in the transition region are
+ set to ``nan``, so they won't appear in the plot.
+
+ >>> ideal = w < cutoff # The "ideal" frequency response.
+ >>> deviation = np.abs(np.abs(h) - ideal)
+ >>> deviation[(w > cutoff - 0.5*width) & (w < cutoff + 0.5*width)] = np.nan
+
+ Plot the deviation. A close look at the left end of the stop band shows
+ that the requirement for 65 dB attenuation is violated in the first lobe
+ by about 0.125 dB. This is not unusual for the Kaiser window method.
+
+ >>> plt.plot(w, 20*np.log10(np.abs(deviation)))
+ >>> plt.xlim(0, 0.5*fs)
+ >>> plt.ylim(-90, -60)
+ >>> plt.grid(alpha=0.25)
+ >>> plt.axhline(-65, color='r', ls='--', alpha=0.3)
+ >>> plt.xlabel('Frequency (Hz)')
+ >>> plt.ylabel('Deviation from ideal (dB)')
+ >>> plt.title('Lowpass Filter Frequency Response')
+ >>> plt.show()
+
+ """
+ A = abs(ripple) # in case somebody is confused as to what's meant
+ if A < 8:
+ # Formula for N is not valid in this range.
+ raise ValueError("Requested maximum ripple attenuation "
+ f"{A:f} is too small for the Kaiser formula.")
+ beta = kaiser_beta(A)
+
+ # Kaiser's formula (as given in Oppenheim and Schafer) is for the filter
+ # order, so we have to add 1 to get the number of taps.
+ numtaps = (A - 7.95) / 2.285 / (np.pi * width) + 1
+
+ return int(ceil(numtaps)), beta
+
+
+def firwin(numtaps, cutoff, *, width=None, window='hamming', pass_zero=True,
+ scale=True, fs=None):
+ r"""FIR filter design using the window method.
+
+ This function computes the coefficients of a finite impulse response
+ filter. The filter will have linear phase; it will be Type I if
+ `numtaps` is odd and Type II if `numtaps` is even.
+
+ Type II filters always have zero response at the Nyquist frequency, so a
+ ValueError exception is raised if firwin is called with `numtaps` even and
+ having a passband whose right end is at the Nyquist frequency.
+
+ Parameters
+ ----------
+ numtaps : int
+ Length of the filter (number of coefficients, i.e., the filter
+ order + 1). `numtaps` must be odd if a passband includes the
+ Nyquist frequency.
+ cutoff : float or 1-D array_like
+ Cutoff frequency of filter (expressed in the same units as `fs`)
+ or an array of cutoff frequencies (that is, band edges). In the
+ former case, as a float, the cutoff frequency should correspond
+ with the half-amplitude point, where the attenuation will be -6 dB.
+ In the latter case, the frequencies in `cutoff` should be positive
+ and monotonically increasing between 0 and `fs/2`. The values 0
+ and `fs/2` must not be included in `cutoff`. It should be noted
+ that this is different from the behavior of `~scipy.signal.iirdesign`,
+ where the cutoff is the half-power point (-3 dB).
+ width : float or None, optional
+ If not ``None``, then a `~scipy.signal.windows.kaiser` window is calculated
+ where `width` specifies the approximate width of the transition region
+ (expressed in the same unit as `fs`). This is achieved by utilizing
+ `~scipy.signal.kaiser_atten` to calculate an attenuation which is passed to
+ `~scipy.signal.kaiser_beta` for determining the β parameter for the kaiser
+ window. In this case, the `window` argument is ignored.
+ window : str or tuple of str and parameter values, optional
+ Desired window to use. Default is ``'hamming'``. The window will be symmetric,
+ unless a suffix ``'_periodic'`` is appended to the window name (e.g.,
+ ``'hamming_perodic'``) Consult `~scipy.signal.get_window` for a list of windows
+ and required parameters.
+ pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
+ Toggles the zero frequency bin (or DC gain) to be in the passband (``True``) or
+ in the stopband (``False``). ``'bandstop'``, ``'lowpass'`` are synonyms for
+ ``True`` and ``'bandpass'``, ``'highpass'`` are synonyms for ``False``.
+ ``'lowpass'``, ``'highpass'`` additionally require `cutoff` to be a scalar
+ value or a length-one array. Default: ``True``.
+
+ .. versionadded:: 1.3.0
+ Support for string arguments.
+ scale : bool, optional
+ Set to ``True`` to scale the coefficients so that the frequency response is
+ exactly unity at a certain frequency. That frequency is either:
+
+ - 0 (DC) if the first passband starts at 0 (i.e., `pass_zero` is ``True``)
+ - `fs/2` (the Nyquist frequency) if the first passband ends at `fs/2`
+ (i.e., the filter is a single band highpass filter); center of first
+ passband otherwise
+
+ fs : float, optional
+ The sampling frequency of the signal. Each frequency in `cutoff`
+ must be between 0 and ``fs/2``. Default is 2.
+
+ Returns
+ -------
+ h : ndarray
+ FIR filter coefficients as 1d array with `numtaps` entries.
+
+ Raises
+ ------
+ ValueError
+ If any value in `cutoff` is less than or equal to 0 or greater
+ than or equal to ``fs/2``, if the values in `cutoff` are not strictly
+ monotonically increasing, or if `numtaps` is even but a passband
+ includes the Nyquist frequency.
+
+ See Also
+ --------
+ firwin2: Window method FIR filter design specifying gain-frequency pairs.
+ firwin_2d: 2D FIR filter design using the window method.
+ firls: FIR filter design using least-squares error minimization.
+ minimum_phase: Convert a FIR filter to minimum phase
+ remez: Calculate the minimax optimal filter using the Remez exchange algorithm.
+
+ Examples
+ --------
+ The following example calculates frequency responses of a 30 Hz low-pass filter
+ with various numbers of taps. The transition region width is 20 Hz. The upper plot
+ shows the gain and the lower plot the phase. The vertical dashed line marks the
+ corner frequency and the gray background the transition region.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> fs = 200 # sampling frequency and number of taps
+ >>> f_c, width = 30, 20 # corner frequency (-6 dB gain)
+ >>> taps = [20, 40, 60] # number of taps
+ ...
+ >>> fg, (ax0, ax1) = plt.subplots(2, 1, sharex='all', layout="constrained",
+ ... figsize=(5, 4))
+ >>> ax0.set_title(rf"Response of ${f_c}\,$Hz low-pass Filter with " +
+ ... rf"${width}\,$Hz transition region")
+ >>> ax0.set(ylabel="Gain in dB", xlim=(0, fs/2))
+ >>> ax1.set(xlabel=rf"Frequency $f\,$ in hertz (sampling frequency $f_S={fs}\,$Hz)",
+ ... ylabel="Phase in Degrees")
+ ...
+ >>> for n in taps: # calculate filter and plot response:
+ ... bb = signal.firwin(n, f_c, width=width, fs=fs)
+ ... f, H = signal.freqz(bb, fs=fs) # calculate frequency response
+ ... H_dB, H_ph = 20 * np.log10(abs(H)), np.rad2deg(np.unwrap(np.angle(H)))
+ ... H_ph[H_dB<-150] = np.nan
+ ... ax0.plot(f, H_dB, alpha=.5, label=rf"{n} taps")
+ ... ax1.plot(f, H_ph, alpha=.5, label=rf"{n} taps")
+ >>> for ax_ in (ax0, ax1):
+ ... ax_.axvspan(f_c-width/2, f_c+width/2,color='gray', alpha=.25)
+ ... ax_.axvline(f_c, color='gray', linestyle='--', alpha=.5)
+ ... ax_.grid()
+ ... ax_.legend()
+ >>> plt.show()
+
+ The plots show that with increasing number of taps, the suppression in the stopband
+ increases and the (negative) slope of the phase steepens, which signifies a longer
+ signal delay in the filter. Note that the plots contain numeric artifacts caused by
+ the limited frequency resolution: The phase jumps are not real---in reality the
+ phase is a straight line with a constant negative slope. Furthermore, the gains
+ contain zero values (i.e., -∞ dB), which are also not depicted.
+
+ The second example determines the frequency responses of a 30 Hz low-pass filter
+ with 40 taps. This time the width of the transition region varies:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> fs = 200 # sampling frequency and number of taps
+ >>> n, f_c = 40, 30 # number of taps and corner frequency (-6 dB gain)
+ >>> widths = (2, 10, 25) # width of transition region
+ ...
+ >>> fg, ax = plt.subplots(1, 1, layout="constrained",)
+ >>> ax.set(title=rf"Response of {n}-tap ${f_c}\,$Hz low-pass Filter",
+ ... xlabel=rf"Frequency $f\,$ in hertz (sampling frequency $f_S={fs}\,$Hz)",
+ ... ylabel="Gain in dB", xlim=(0, fs/2))
+ >>> ax.axvline(f_c, color='gray', linestyle='--', alpha=.7) # mark corner frequency
+ ...
+ >>> for width in widths: # calculate filter and plot response:
+ ... bb = signal.firwin(n, f_c, width=width, fs=fs)
+ ... f, H = signal.freqz(bb, fs=fs) # calculate frequency response
+ ... H_dB= 20 * np.log10(abs(H)) # convert to dB
+ ... ax.plot(f, H_dB, alpha=.5, label=rf"width$={width}\,$Hz")
+ ...
+ >>> ax.grid()
+ >>> ax.legend()
+ >>> plt.show()
+
+ It can be seen in the plot above that with increasing width of the transition
+ region the suppression in the stopband increases. Since the phase does not vary, it
+ is not depicted.
+
+ Instead of defining a transition region width, a window function can also be
+ specified. The plot below depicts the response of an 80 tap band-pass filter having
+ a passband ranging form 40 Hz to 60 Hz (denoted by a gray background) with
+ different windows:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> fs, n = 200, 80 # sampling frequency and number of taps
+ >>> cutoff = [40, 60] # corner frequencies (-6 dB gain)
+ >>> windows = ('boxcar', 'hamming', 'hann', 'blackman')
+ ...
+ >>> fg, ax = plt.subplots(1, 1, layout="constrained") # set up plotting
+ >>> ax.set(title=rf"Response of {n}-tap Filter with ${cutoff}\,$Hz passband",
+ ... xlabel=rf"Frequency $f\,$ in hertz (sampling frequency $f_S={fs}\,$Hz)",
+ ... ylabel="Gain in dB", xlim=(0, fs/2))
+ >>> ax.axvspan(*cutoff, color='gray', alpha=.25) # mark passband
+ ...
+ >>> for win in windows: # calculate filter and plot response:
+ ... bb = signal.firwin(n, cutoff, window=win, pass_zero=False, fs=fs)
+ ... f, H = signal.freqz(bb, fs=fs) # calculate frequency response
+ ... H_dB = 20 * np.log10(abs(H)) # convert to dB
+ ... ax.plot(f, H_dB, alpha=.5, label=win)
+ ...
+ >>> ax.grid()
+ >>> ax.legend()
+ >>> plt.show()
+
+ The plot shows that the choice of window mainly influences the balance of the
+ suppression in the stopband against the width of the transition region. Note that
+ utilizing the `~scipy.signal.windows.boxcar` window corresponds to just truncating
+ the ideal infinite impulse response to the length of `numtaps` samples.
+
+ The last example illustrates how to use the `cutoff` and `pass_zero` parameters to
+ create a low-pass, a high-pass, a band-stop and a band-pass filter. The desired
+ ideal frequency gain is drawn as a gray dashed line whereas the response of the FIR
+ filter is depicted as a blue continuous line:
+
+ >>> from itertools import product
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> cutoffs = [0.5, (.25, .75)] # cutoff parameters
+ >>> fg, axx = plt.subplots(4, 1, sharex='all', layout="constrained",
+ ... figsize=(5, 4))
+ >>> for ax, (cutoff, pass_zero) in zip(axx, product(cutoffs, (True, False))):
+ ... ax.set(title=f"firwin(41, {cutoff=}, {pass_zero=}, fs=2)", ylabel="Gain")
+ ... ax.set_yticks([0.5], minor=True) # mark gain of 0.5 (= -6 dB)
+ ... ax.grid(which='minor', axis='y')
+ ...
+ ... bb = signal.firwin(41, cutoff, pass_zero=pass_zero, fs=2)
+ ... ff, HH = signal.freqz(bb, fs=2)
+ ... ax.plot(ff, abs(HH), 'C0-', label="FIR Response")
+ ...
+ ... f_d = np.hstack(([0], np.atleast_1d(cutoff), [1]))
+ ... H_d = np.tile([1, 0] if pass_zero else [0, 1], 2)[:len(f_d)]
+ ... H_d[-1] = H_d[-2] # account for symmetry at Nyquist frequency
+ ... ax.step(f_d, H_d, 'k--', where='post', alpha=.3, label="Desired Response")
+ >>> axx[-1].set(xlabel=r"Frequency $f\,$ in hertz (sampling frequency $f_S=2\,$Hz)",
+ ... xlim=(0, 1))
+ >>> plt.show()
+ """
+ # NB: scipy's version of array_namespace returns `np_compat` for int or floats
+ xp = array_namespace(cutoff)
+
+ # The major enhancements to this function added in November 2010 were
+ # developed by Tom Krauss (see ticket #902).
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 2 if fs is None else fs
+
+ nyq = 0.5 * fs
+
+ cutoff = xp.asarray(cutoff, dtype=xp_default_dtype(xp))
+ cutoff = xpx.atleast_nd(cutoff, ndim=1, xp=xp) / float(nyq)
+
+ # Check for invalid input.
+ if cutoff.ndim > 1:
+ raise ValueError("The cutoff argument must be at most "
+ "one-dimensional.")
+ if xp_size(cutoff) == 0:
+ raise ValueError("At least one cutoff frequency must be given.")
+ if xp.min(cutoff) <= 0 or xp.max(cutoff) >= 1:
+ raise ValueError("Invalid cutoff frequency: frequencies must be "
+ "greater than 0 and less than fs/2.")
+ if xp.any(cutoff[1:] - cutoff[:-1] <= 0):
+ raise ValueError("Invalid cutoff frequencies: the frequencies "
+ "must be strictly increasing.")
+
+ if width is not None:
+ # A width was given. Find the beta parameter of the Kaiser window
+ # and set `window`. This overrides the value of `window` passed in.
+ atten = kaiser_atten(numtaps, float(width) / nyq)
+ beta = kaiser_beta(atten)
+ window = ('kaiser', beta)
+
+ if pass_zero in ('bandstop', 'lowpass'):
+ if pass_zero == 'lowpass':
+ if xp_size(cutoff) != 1:
+ raise ValueError('cutoff must have one element if '
+ f'pass_zero=="lowpass", got {cutoff.shape}')
+ elif xp_size(cutoff) <= 1:
+ raise ValueError('cutoff must have at least two elements if '
+ f'pass_zero=="bandstop", got {cutoff.shape}')
+ pass_zero = True
+ elif pass_zero in ('bandpass', 'highpass'):
+ if pass_zero == 'highpass':
+ if xp_size(cutoff) != 1:
+ raise ValueError('cutoff must have one element if '
+ f'pass_zero=="highpass", got {cutoff.shape}')
+ elif xp_size(cutoff) <= 1:
+ raise ValueError('cutoff must have at least two elements if '
+ f'pass_zero=="bandpass", got {cutoff.shape}')
+ pass_zero = False
+ elif not (pass_zero is True or pass_zero is False):
+ raise ValueError(f"Parameter {pass_zero=} not in (True, False, 'bandpass', " +
+ "'lowpass', 'highpass', 'bandstop')")
+
+ pass_nyquist = (xp_size(cutoff) % 2 == 0) == pass_zero
+ if pass_nyquist and numtaps % 2 == 0:
+ raise ValueError("A filter with an even number of coefficients must "
+ "have zero response at the Nyquist frequency.")
+
+ # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff
+ # is even, and each pair in cutoff corresponds to passband.
+ cutoff = xp.concat((xp.zeros(int(pass_zero)), cutoff, xp.ones(int(pass_nyquist))))
+
+
+ # `bands` is a 2-D array; each row gives the left and right edges of
+ # a passband.
+ bands = xp.reshape(cutoff, (-1, 2))
+
+ # Build up the coefficients.
+ alpha = 0.5 * (numtaps - 1)
+ m = xp.arange(0, numtaps, dtype=cutoff.dtype) - alpha
+ h = 0
+ for j in range(bands.shape[0]):
+ left, right = bands[j, 0], bands[j, 1]
+ h += right * xpx.sinc(right * m, xp=xp)
+ h -= left * xpx.sinc(left * m, xp=xp)
+
+ # Get and apply the window function.
+ win = get_window(window, numtaps, fftbins=False, xp=xp)
+ h *= win
+
+ # Now handle scaling if desired.
+ if scale:
+ # Get the first passband.
+ left, right = bands[0, ...]
+ if left == 0:
+ scale_frequency = 0.0
+ elif right == 1:
+ scale_frequency = 1.0
+ else:
+ scale_frequency = 0.5 * (left + right)
+ c = xp.cos(xp.pi * m * scale_frequency)
+ s = xp.sum(h * c)
+ h /= s
+
+ return h
+
+
+# Original version of firwin2 from scipy ticket #457, submitted by "tash".
+#
+# Rewritten by Warren Weckesser, 2010.
+def firwin2(numtaps, freq, gain, *, nfreqs=None, window='hamming',
+ antisymmetric=False, fs=None):
+ """
+ FIR filter design using the window method.
+
+ From the given frequencies `freq` and corresponding gains `gain`,
+ this function constructs an FIR filter with linear phase and
+ (approximately) the given frequency response.
+
+ Parameters
+ ----------
+ numtaps : int
+ The number of taps in the FIR filter. `numtaps` must be less than
+ `nfreqs`.
+ freq : array_like, 1-D
+ The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being
+ Nyquist. The Nyquist frequency is half `fs`.
+ The values in `freq` must be nondecreasing. A value can be repeated
+ once to implement a discontinuity. The first value in `freq` must
+ be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must
+ not be repeated.
+ gain : array_like
+ The filter gains at the frequency sampling points. Certain
+ constraints to gain values, depending on the filter type, are applied,
+ see Notes for details.
+ nfreqs : int, optional
+ The size of the interpolation mesh used to construct the filter.
+ For most efficient behavior, this should be a power of 2 plus 1
+ (e.g, 129, 257, etc). The default is one more than the smallest
+ power of 2 that is not less than `numtaps`. `nfreqs` must be greater
+ than `numtaps`.
+ window : str or (str, float) or float, or None, optional
+ Desired window to use. Default is ``'hamming'``. The window will be symmetric,
+ unless a suffix ``'_periodic'`` is appended to the window name (e.g.,
+ ``'hamming_perodic'``) Consult `~scipy.signal.get_window` for a list of windows
+ and required parameters. If ``None``, no window function is applied.
+ antisymmetric : bool, optional
+ Whether resulting impulse response is symmetric/antisymmetric.
+ See Notes for more details.
+ fs : float, optional
+ The sampling frequency of the signal. Each frequency in `cutoff`
+ must be between 0 and ``fs/2``. Default is 2.
+
+ Returns
+ -------
+ taps : ndarray
+ The filter coefficients of the FIR filter, as a 1-D array of length
+ `numtaps`.
+
+ See Also
+ --------
+ firls
+ firwin
+ minimum_phase
+ remez
+
+ Notes
+ -----
+ From the given set of frequencies and gains, the desired response is
+ constructed in the frequency domain. The inverse FFT is applied to the
+ desired response to create the associated convolution kernel, and the
+ first `numtaps` coefficients of this kernel, scaled by `window`, are
+ returned.
+
+ The FIR filter will have linear phase. The type of filter is determined by
+ the value of 'numtaps` and `antisymmetric` flag.
+ There are four possible combinations:
+
+ - odd `numtaps`, `antisymmetric` is False, type I filter is produced
+ - even `numtaps`, `antisymmetric` is False, type II filter is produced
+ - odd `numtaps`, `antisymmetric` is True, type III filter is produced
+ - even `numtaps`, `antisymmetric` is True, type IV filter is produced
+
+ Magnitude response of all but type I filters are subjects to following
+ constraints:
+
+ - type II -- zero at the Nyquist frequency
+ - type III -- zero at zero and Nyquist frequencies
+ - type IV -- zero at zero frequency
+
+ .. versionadded:: 0.9.0
+
+ References
+ ----------
+ .. [1] Oppenheim, A. V. and Schafer, R. W., "Discrete-Time Signal
+ Processing", Prentice-Hall, Englewood Cliffs, New Jersey (1989).
+ (See, for example, Section 7.4.)
+
+ .. [2] Smith, Steven W., "The Scientist and Engineer's Guide to Digital
+ Signal Processing", Ch. 17. http://www.dspguide.com/ch17/1.htm
+
+ Examples
+ --------
+ A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and
+ that decreases linearly on [0.5, 1.0] from 1 to 0:
+
+ >>> from scipy import signal
+ >>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0])
+ >>> print(taps[72:78])
+ [-0.02286961 -0.06362756 0.57310236 0.57310236 -0.06362756 -0.02286961]
+
+ """
+ xp = array_namespace(freq, gain)
+ freq, gain = xp.asarray(freq), xp.asarray(gain)
+
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 2 if fs is None else fs
+ nyq = 0.5 * fs
+
+ if freq.shape[0] != gain.shape[0]:
+ raise ValueError('freq and gain must be of same length.')
+
+ if nfreqs is not None and numtaps >= nfreqs:
+ raise ValueError(
+ f'ntaps must be less than nfreqs, but firwin2 was called with '
+ f'ntaps={numtaps} and nfreqs={nfreqs}'
+ )
+
+ if freq[0] != 0 or freq[-1] != nyq:
+ raise ValueError('freq must start with 0 and end with fs/2.')
+ d = freq[1:] - freq[:-1]
+ if xp.any(d < 0):
+ raise ValueError('The values in freq must be nondecreasing.')
+ d2 = d[:-1] + d[1:]
+ if xp.any(d2 == 0):
+ raise ValueError('A value in freq must not occur more than twice.')
+ if freq[1] == 0:
+ raise ValueError('Value 0 must not be repeated in freq')
+ if freq[-2] == nyq:
+ raise ValueError('Value fs/2 must not be repeated in freq')
+
+ if antisymmetric:
+ if numtaps % 2 == 0:
+ ftype = 4
+ else:
+ ftype = 3
+ else:
+ if numtaps % 2 == 0:
+ ftype = 2
+ else:
+ ftype = 1
+
+ if ftype == 2 and gain[-1] != 0.0:
+ raise ValueError("A Type II filter must have zero gain at the "
+ "Nyquist frequency.")
+ elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0):
+ raise ValueError("A Type III filter must have zero gain at zero "
+ "and Nyquist frequencies.")
+ elif ftype == 4 and gain[0] != 0.0:
+ raise ValueError("A Type IV filter must have zero gain at zero "
+ "frequency.")
+
+ if nfreqs is None:
+ nfreqs = 1 + 2 ** int(ceil(log(numtaps, 2)))
+
+ if xp.any(d == 0):
+ # Tweak any repeated values in freq so that interp works.
+ freq = xp.asarray(freq, copy=True)
+ eps = xp.finfo(xp_default_dtype(xp)).eps * nyq
+ for k in range(freq.shape[0] - 1):
+ if freq[k] == freq[k + 1]:
+ freq[k] = freq[k] - eps
+ freq[k + 1] = freq[k + 1] + eps
+ # Check if freq is strictly increasing after tweak
+ d = freq[1:] - freq[:-1]
+ if xp.any(d <= 0):
+ raise ValueError("freq cannot contain numbers that are too close "
+ "(within eps * (fs/2): "
+ f"{eps}) to a repeated value")
+
+ # Linearly interpolate the desired response on a uniform mesh `x`.
+ x = np.linspace(0.0, nyq, nfreqs)
+ fx = np.interp(x, np.asarray(freq), np.asarray(gain)) # XXX array-api-extra#193
+ x = xp.asarray(x)
+ fx = xp.asarray(fx)
+
+ # Adjust the phases of the coefficients so that the first `ntaps` of the
+ # inverse FFT are the desired filter coefficients.
+ shift = xp.exp(-(numtaps - 1) / 2. * 1j * xp.pi * x / nyq)
+ if ftype > 2:
+ shift *= 1j
+
+ fx2 = fx * shift
+
+ # Use irfft to compute the inverse FFT.
+ out_full = irfft(fx2)
+
+ if window is not None:
+ # Create the window to apply to the filter coefficients.
+ wind = get_window(window, numtaps, fftbins=False, xp=xp)
+ else:
+ wind = 1
+
+ # Keep only the first `numtaps` coefficients in `out`, and multiply by
+ # the window.
+ out = out_full[:numtaps] * wind
+
+ if ftype == 3:
+ out[xp_size(out) // 2] = 0.0
+
+ return out
+
+
+def remez(numtaps, bands, desired, *, weight=None, type='bandpass',
+ maxiter=25, grid_density=16, fs=None):
+ """
+ Calculate the minimax optimal filter using the Remez exchange algorithm.
+
+ Calculate the filter-coefficients for the finite impulse response
+ (FIR) filter whose transfer function minimizes the maximum error
+ between the desired gain and the realized gain in the specified
+ frequency bands using the Remez exchange algorithm.
+
+ Parameters
+ ----------
+ numtaps : int
+ The desired number of taps in the filter. The number of taps is
+ the number of terms in the filter, or the filter order plus one.
+ bands : array_like
+ A monotonic sequence containing the band edges.
+ All elements must be non-negative and less than half the sampling
+ frequency as given by `fs`.
+ desired : array_like
+ A sequence half the size of bands containing the desired gain
+ in each of the specified bands.
+ weight : array_like, optional
+ A relative weighting to give to each band region. The length of
+ `weight` has to be half the length of `bands`.
+ type : {'bandpass', 'differentiator', 'hilbert'}, optional
+ The type of filter:
+
+ * 'bandpass' : flat response in bands. This is the default.
+ * 'differentiator' : frequency proportional response in bands.
+ * 'hilbert' : filter with odd symmetry, that is, type III
+ (for even order) or type IV (for odd order) linear phase filters.
+
+ maxiter : int, optional
+ Maximum number of iterations of the algorithm. Default is 25.
+ grid_density : int, optional
+ Grid density. The dense grid used in `remez` is of size
+ ``(numtaps + 1) * grid_density``. Default is 16.
+ fs : float, optional
+ The sampling frequency of the signal. Default is 1.
+
+ Returns
+ -------
+ out : ndarray
+ A rank-1 array containing the coefficients of the optimal
+ (in a minimax sense) filter.
+
+ See Also
+ --------
+ firls
+ firwin
+ firwin2
+ minimum_phase
+
+ References
+ ----------
+ .. [1] J. H. McClellan and T. W. Parks, "A unified approach to the
+ design of optimum FIR linear phase digital filters",
+ IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.
+ .. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer
+ Program for Designing Optimum FIR Linear Phase Digital
+ Filters", IEEE Trans. Audio Electroacoust., vol. AU-21,
+ pp. 506-525, 1973.
+
+ Examples
+ --------
+ In these examples, `remez` is used to design low-pass, high-pass,
+ band-pass and band-stop filters. The parameters that define each filter
+ are the filter order, the band boundaries, the transition widths of the
+ boundaries, the desired gains in each band, and the sampling frequency.
+
+ We'll use a sample frequency of 22050 Hz in all the examples. In each
+ example, the desired gain in each band is either 0 (for a stop band)
+ or 1 (for a pass band).
+
+ `freqz` is used to compute the frequency response of each filter, and
+ the utility function ``plot_response`` defined below is used to plot
+ the response.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> fs = 22050 # Sample rate, Hz
+
+ >>> def plot_response(w, h, title):
+ ... "Utility function to plot response functions"
+ ... fig = plt.figure()
+ ... ax = fig.add_subplot(111)
+ ... ax.plot(w, 20*np.log10(np.abs(h)))
+ ... ax.set_ylim(-40, 5)
+ ... ax.grid(True)
+ ... ax.set_xlabel('Frequency (Hz)')
+ ... ax.set_ylabel('Gain (dB)')
+ ... ax.set_title(title)
+
+ The first example is a low-pass filter, with cutoff frequency 8 kHz.
+ The filter length is 325, and the transition width from pass to stop
+ is 100 Hz.
+
+ >>> cutoff = 8000.0 # Desired cutoff frequency, Hz
+ >>> trans_width = 100 # Width of transition from pass to stop, Hz
+ >>> numtaps = 325 # Size of the FIR filter.
+ >>> taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5*fs],
+ ... [1, 0], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "Low-pass Filter")
+ >>> plt.show()
+
+ This example shows a high-pass filter:
+
+ >>> cutoff = 2000.0 # Desired cutoff frequency, Hz
+ >>> trans_width = 250 # Width of transition from pass to stop, Hz
+ >>> numtaps = 125 # Size of the FIR filter.
+ >>> taps = signal.remez(numtaps, [0, cutoff - trans_width, cutoff, 0.5*fs],
+ ... [0, 1], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "High-pass Filter")
+ >>> plt.show()
+
+ This example shows a band-pass filter with a pass-band from 2 kHz to
+ 5 kHz. The transition width is 260 Hz and the length of the filter
+ is 63, which is smaller than in the other examples:
+
+ >>> band = [2000, 5000] # Desired pass band, Hz
+ >>> trans_width = 260 # Width of transition from pass to stop, Hz
+ >>> numtaps = 63 # Size of the FIR filter.
+ >>> edges = [0, band[0] - trans_width, band[0], band[1],
+ ... band[1] + trans_width, 0.5*fs]
+ >>> taps = signal.remez(numtaps, edges, [0, 1, 0], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "Band-pass Filter")
+ >>> plt.show()
+
+ The low order leads to higher ripple and less steep transitions.
+
+ The next example shows a band-stop filter.
+
+ >>> band = [6000, 8000] # Desired stop band, Hz
+ >>> trans_width = 200 # Width of transition from pass to stop, Hz
+ >>> numtaps = 175 # Size of the FIR filter.
+ >>> edges = [0, band[0] - trans_width, band[0], band[1],
+ ... band[1] + trans_width, 0.5*fs]
+ >>> taps = signal.remez(numtaps, edges, [1, 0, 1], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "Band-stop Filter")
+ >>> plt.show()
+
+ """
+ xp = array_namespace(bands, desired, weight)
+ bands = np.asarray(bands)
+ desired = np.asarray(desired)
+ if weight is not None:
+ weight = np.asarray(weight)
+
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 1.0 if fs is None else fs
+
+ # Convert type
+ try:
+ tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type]
+ except KeyError as e:
+ raise ValueError("Type must be 'bandpass', 'differentiator', "
+ "or 'hilbert'") from e
+
+ # Convert weight
+ if weight is None:
+ weight = [1] * len(desired)
+
+ bands = np.asarray(bands).copy()
+ result = _sigtools._remez(numtaps, bands, desired, weight, tnum, fs,
+ maxiter, grid_density)
+ return xp.asarray(result)
+
+
+def firls(numtaps, bands, desired, *, weight=None, fs=None):
+ """
+ FIR filter design using least-squares error minimization.
+
+ Calculate the filter coefficients for the linear-phase finite
+ impulse response (FIR) filter which has the best approximation
+ to the desired frequency response described by `bands` and
+ `desired` in the least squares sense (i.e., the integral of the
+ weighted mean-squared error within the specified bands is
+ minimized).
+
+ Parameters
+ ----------
+ numtaps : int
+ The number of taps in the FIR filter. `numtaps` must be odd.
+ bands : array_like
+ A monotonic nondecreasing sequence containing the band edges in
+ Hz. All elements must be non-negative and less than or equal to
+ the Nyquist frequency given by `nyq`. The bands are specified as
+ frequency pairs, thus, if using a 1D array, its length must be
+ even, e.g., `np.array([0, 1, 2, 3, 4, 5])`. Alternatively, the
+ bands can be specified as an nx2 sized 2D array, where n is the
+ number of bands, e.g, `np.array([[0, 1], [2, 3], [4, 5]])`.
+ desired : array_like
+ A sequence the same size as `bands` containing the desired gain
+ at the start and end point of each band.
+ weight : array_like, optional
+ A relative weighting to give to each band region when solving
+ the least squares problem. `weight` has to be half the size of
+ `bands`.
+ fs : float, optional
+ The sampling frequency of the signal. Each frequency in `bands`
+ must be between 0 and ``fs/2`` (inclusive). Default is 2.
+
+ Returns
+ -------
+ coeffs : ndarray
+ Coefficients of the optimal (in a least squares sense) FIR filter.
+
+ See Also
+ --------
+ firwin
+ firwin2
+ minimum_phase
+ remez
+
+ Notes
+ -----
+ This implementation follows the algorithm given in [1]_.
+ As noted there, least squares design has multiple advantages:
+
+ 1. Optimal in a least-squares sense.
+ 2. Simple, non-iterative method.
+ 3. The general solution can obtained by solving a linear
+ system of equations.
+ 4. Allows the use of a frequency dependent weighting function.
+
+ This function constructs a Type I linear phase FIR filter, which
+ contains an odd number of `coeffs` satisfying for :math:`n < numtaps`:
+
+ .. math:: coeffs(n) = coeffs(numtaps - 1 - n)
+
+ The odd number of coefficients and filter symmetry avoid boundary
+ conditions that could otherwise occur at the Nyquist and 0 frequencies
+ (e.g., for Type II, III, or IV variants).
+
+ .. versionadded:: 0.18
+
+ References
+ ----------
+ .. [1] Ivan Selesnick, Linear-Phase Fir Filter Design By Least Squares.
+ OpenStax CNX. Aug 9, 2005.
+ https://eeweb.engineering.nyu.edu/iselesni/EL713/firls/firls.pdf
+
+ Examples
+ --------
+ We want to construct a band-pass filter. Note that the behavior in the
+ frequency ranges between our stop bands and pass bands is unspecified,
+ and thus may overshoot depending on the parameters of our filter:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> fig, axs = plt.subplots(2)
+ >>> fs = 10.0 # Hz
+ >>> desired = (0, 0, 1, 1, 0, 0)
+ >>> for bi, bands in enumerate(((0, 1, 2, 3, 4, 5), (0, 1, 2, 4, 4.5, 5))):
+ ... fir_firls = signal.firls(73, bands, desired, fs=fs)
+ ... fir_remez = signal.remez(73, bands, desired[::2], fs=fs)
+ ... fir_firwin2 = signal.firwin2(73, bands, desired, fs=fs)
+ ... hs = list()
+ ... ax = axs[bi]
+ ... for fir in (fir_firls, fir_remez, fir_firwin2):
+ ... freq, response = signal.freqz(fir)
+ ... hs.append(ax.semilogy(0.5*fs*freq/np.pi, np.abs(response))[0])
+ ... for band, gains in zip(zip(bands[::2], bands[1::2]),
+ ... zip(desired[::2], desired[1::2])):
+ ... ax.semilogy(band, np.maximum(gains, 1e-7), 'k--', linewidth=2)
+ ... if bi == 0:
+ ... ax.legend(hs, ('firls', 'remez', 'firwin2'),
+ ... loc='lower center', frameon=False)
+ ... else:
+ ... ax.set_xlabel('Frequency (Hz)')
+ ... ax.grid(True)
+ ... ax.set(title='Band-pass %d-%d Hz' % bands[2:4], ylabel='Magnitude')
+ ...
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(bands, desired)
+ bands = np.asarray(bands)
+ desired = np.asarray(desired)
+
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 2 if fs is None else fs
+ nyq = 0.5 * fs
+
+ numtaps = int(numtaps)
+ if numtaps % 2 == 0 or numtaps < 1:
+ raise ValueError("numtaps must be odd and >= 1")
+ M = (numtaps-1) // 2
+
+ # normalize bands 0->1 and make it 2 columns
+ nyq = float(nyq)
+ if nyq <= 0:
+ raise ValueError(f'nyq must be positive, got {nyq} <= 0.')
+ bands = np.asarray(bands).flatten() / nyq
+ if len(bands) % 2 != 0:
+ raise ValueError("bands must contain frequency pairs.")
+ if (bands < 0).any() or (bands > 1).any():
+ raise ValueError("bands must be between 0 and 1 relative to Nyquist")
+ bands = bands.reshape((-1, 2))
+
+ # check remaining params
+ desired = np.asarray(desired).flatten()
+ if bands.size != desired.size:
+ raise ValueError(
+ f"desired must have one entry per frequency, got {desired.size} "
+ f"gains for {bands.size} frequencies."
+ )
+ desired = desired.reshape((-1, 2))
+ if (np.diff(bands) <= 0).any() or (np.diff(bands[:, 0]) < 0).any():
+ raise ValueError("bands must be monotonically nondecreasing and have "
+ "width > 0.")
+ if (bands[:-1, 1] > bands[1:, 0]).any():
+ raise ValueError("bands must not overlap.")
+ if (desired < 0).any():
+ raise ValueError("desired must be non-negative.")
+ if weight is None:
+ weight = np.ones(len(desired))
+ weight = np.asarray(weight).flatten()
+ if len(weight) != len(desired):
+ raise ValueError("weight must be the same size as the number of "
+ f"band pairs ({len(bands)}).")
+ if (weight < 0).any():
+ raise ValueError("weight must be non-negative.")
+
+ # Set up the linear matrix equation to be solved, Qa = b
+
+ # We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n)
+ # where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel.
+
+ # We omit the factor of 0.5 above, instead adding it during coefficient
+ # calculation.
+
+ # We also omit the 1/π from both Q and b equations, as they cancel
+ # during solving.
+
+ # We have that:
+ # q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π)
+ # Using our normalization ω=πf and with a constant weight W over each
+ # interval f1->f2 we get:
+ # q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf
+ # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
+ n = np.arange(numtaps)[:, np.newaxis, np.newaxis]
+ q = np.dot(np.diff(np.sinc(bands * n) * bands, axis=2)[:, :, 0], weight)
+
+ # Now we assemble our sum of Toeplitz and Hankel
+ Q1 = toeplitz(q[:M+1])
+ Q2 = hankel(q[:M+1], q[M:])
+ Q = Q1 + Q2
+
+ # Now for b(n) we have that:
+ # b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π)
+ # Using our normalization ω=πf and with a constant weight W over each
+ # interval and a linear term for D(ω) we get (over each f1->f2 interval):
+ # b(n) = W ∫ (mf+c)cos(πnf)df
+ # = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2
+ # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
+ n = n[:M + 1] # only need this many coefficients here
+ # Choose m and c such that we are at the start and end weights
+ m = (np.diff(desired, axis=1) / np.diff(bands, axis=1))
+ c = desired[:, [0]] - bands[:, [0]] * m
+ b = bands * (m*bands + c) * np.sinc(bands * n)
+ # Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0
+ b[0] -= m * bands * bands / 2.
+ b[1:] += m * np.cos(n[1:] * np.pi * bands) / (np.pi * n[1:]) ** 2
+ b = np.dot(np.diff(b, axis=2)[:, :, 0], weight)
+
+ # Now we can solve the equation
+ try: # try the fast way
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always')
+ a = solve(Q, b, assume_a="pos", check_finite=False)
+ for ww in w:
+ if (ww.category == LinAlgWarning and
+ str(ww.message).startswith('Ill-conditioned matrix')):
+ raise LinAlgError(str(ww.message))
+ except LinAlgError: # in case Q is rank deficient
+ # This is faster than pinvh, even though we don't explicitly use
+ # the symmetry here. gelsy was faster than gelsd and gelss in
+ # some non-exhaustive tests.
+ a = lstsq(Q, b, lapack_driver='gelsy')[0]
+
+ # make coefficients symmetric (linear phase)
+ coeffs = np.hstack((a[:0:-1], 2 * a[0], a[1:]))
+ return xp.asarray(coeffs)
+
+
+def _dhtm(mag, xp):
+ """Compute the modified 1-D discrete Hilbert transform
+
+ Parameters
+ ----------
+ mag : ndarray
+ The magnitude spectrum. Should be 1-D with an even length, and
+ preferably a fast length for FFT/IFFT.
+ """
+ # Adapted based on code by Niranjan Damera-Venkata,
+ # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`)
+ sig = xp.zeros(mag.shape[0])
+ # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5
+ midpt = mag.shape[0] // 2
+ sig = xpx.at(sig)[1:midpt].set(1.0)
+ sig = xpx.at(sig)[midpt+1:].set(-1.0)
+ # eventually if we want to support complex filters, we will need a
+ # np.abs() on the mag inside the log, and should remove the .real
+ recon = xp.real(ifft(mag * xp.exp(fft(sig * ifft(xp.log(mag))))))
+ return recon
+
+
+def minimum_phase(h,
+ method: Literal['homomorphic', 'hilbert'] = 'homomorphic',
+ n_fft: int | None = None, *, half: bool = True):
+ """Convert a linear-phase FIR filter to minimum phase.
+
+ Parameters
+ ----------
+ h : array
+ Linear-phase FIR filter coefficients.
+ method : {'hilbert', 'homomorphic'}
+ The provided methods are:
+
+ - 'homomorphic' (default):
+ This method [4]_ [5]_ works best with filters with an
+ odd number of taps, and the resulting minimum phase filter
+ will have a magnitude response that approximates the square
+ root of the original filter's magnitude response using half
+ the number of taps when ``half=True`` (default), or the
+ original magnitude spectrum using the same number of taps
+ when ``half=False``.
+ - 'hilbert'
+ This method [1]_ is designed to be used with equiripple
+ filters (e.g., from `remez`) with unity or zero gain
+ regions.
+
+ n_fft : int
+ The number of points to use for the FFT. Should be at least a
+ few times larger than the signal length (see Notes).
+ half : bool
+ If ``True``, create a filter that is half the length of the original, with a
+ magnitude spectrum that is the square root of the original. If ``False``,
+ create a filter that is the same length as the original, with a magnitude
+ spectrum that is designed to match the original (only supported when
+ ``method='homomorphic'``).
+
+ .. versionadded:: 1.14.0
+
+ Returns
+ -------
+ h_minimum : array
+ The minimum-phase version of the filter, with length
+ ``(len(h) + 1) // 2`` when ``half is True`` or ``len(h)`` otherwise.
+
+ See Also
+ --------
+ firwin
+ firwin2
+ remez
+
+ Notes
+ -----
+ Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection
+ of an FFT length to estimate the complex cepstrum of the filter.
+
+ In the case of the Hilbert method, the deviation from the ideal
+ spectrum ``epsilon`` is related to the number of stopband zeros
+ ``n_stop`` and FFT length ``n_fft`` as::
+
+ epsilon = 2. * n_stop / n_fft
+
+ For example, with 100 stopband zeros and a FFT length of 2048,
+ ``epsilon = 0.0976``. If we conservatively assume that the number of
+ stopband zeros is one less than the filter length, we can take the FFT
+ length to be the next power of 2 that satisfies ``epsilon=0.01`` as::
+
+ n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01)))
+
+ This gives reasonable results for both the Hilbert and homomorphic
+ methods, and gives the value used when ``n_fft=None``.
+
+ Alternative implementations exist for creating minimum-phase filters,
+ including zero inversion [2]_ and spectral factorization [3]_ [4]_.
+ For more information, see `this DSPGuru page
+ `__.
+
+ References
+ ----------
+ .. [1] N. Damera-Venkata and B. L. Evans, "Optimal design of real and
+ complex minimum phase digital FIR filters," Acoustics, Speech,
+ and Signal Processing, 1999. Proceedings., 1999 IEEE International
+ Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3.
+ :doi:`10.1109/ICASSP.1999.756179`
+ .. [2] X. Chen and T. W. Parks, "Design of optimal minimum phase FIR
+ filters by direct factorization," Signal Processing,
+ vol. 10, no. 4, pp. 369-383, Jun. 1986.
+ .. [3] T. Saramaki, "Finite Impulse Response Filter Design," in
+ Handbook for Digital Signal Processing, chapter 4,
+ New York: Wiley-Interscience, 1993.
+ .. [4] J. S. Lim, Advanced Topics in Signal Processing.
+ Englewood Cliffs, N.J.: Prentice Hall, 1988.
+ .. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck,
+ "Discrete-Time Signal Processing," 3rd edition.
+ Upper Saddle River, N.J.: Pearson, 2009.
+
+ Examples
+ --------
+ Create an optimal linear-phase low-pass filter `h` with a transition band of
+ [0.2, 0.3] (assuming a Nyquist frequency of 1):
+
+ >>> import numpy as np
+ >>> from scipy.signal import remez, minimum_phase, freqz, group_delay
+ >>> import matplotlib.pyplot as plt
+ >>> freq = [0, 0.2, 0.3, 1.0]
+ >>> desired = [1, 0]
+ >>> h_linear = remez(151, freq, desired, fs=2)
+
+ Convert it to minimum phase:
+
+ >>> h_hil = minimum_phase(h_linear, method='hilbert')
+ >>> h_hom = minimum_phase(h_linear, method='homomorphic')
+ >>> h_hom_full = minimum_phase(h_linear, method='homomorphic', half=False)
+
+ Compare the impulse and frequency response of the four filters:
+
+ >>> fig0, ax0 = plt.subplots(figsize=(6, 3), tight_layout=True)
+ >>> fig1, axs = plt.subplots(3, sharex='all', figsize=(6, 6), tight_layout=True)
+ >>> ax0.set_title("Impulse response")
+ >>> ax0.set(xlabel='Samples', ylabel='Amplitude', xlim=(0, len(h_linear) - 1))
+ >>> axs[0].set_title("Frequency Response")
+ >>> axs[0].set(xlim=(0, .65), ylabel="Magnitude / dB")
+ >>> axs[1].set(ylabel="Phase / rad")
+ >>> axs[2].set(ylabel="Group Delay / samples", ylim=(-31, 81),
+ ... xlabel='Normalized Frequency (Nyqist frequency: 1)')
+ >>> for h, lb in ((h_linear, f'Linear ({len(h_linear)})'),
+ ... (h_hil, f'Min-Hilbert ({len(h_hil)})'),
+ ... (h_hom, f'Min-Homomorphic ({len(h_hom)})'),
+ ... (h_hom_full, f'Min-Homom. Full ({len(h_hom_full)})')):
+ ... w_H, H = freqz(h, fs=2)
+ ... w_gd, gd = group_delay((h, 1), fs=2)
+ ...
+ ... alpha = 1.0 if lb == 'linear' else 0.5 # full opacity for 'linear' line
+ ... ax0.plot(h, '.-', alpha=alpha, label=lb)
+ ... axs[0].plot(w_H, 20 * np.log10(np.abs(H)), alpha=alpha)
+ ... axs[1].plot(w_H, np.unwrap(np.angle(H)), alpha=alpha, label=lb)
+ ... axs[2].plot(w_gd, gd, alpha=alpha)
+ >>> ax0.grid(True)
+ >>> ax0.legend(title='Filter Phase (Order)')
+ >>> axs[1].legend(title='Filter Phase (Order)', loc='lower right')
+ >>> for ax_ in axs: # shade transition band:
+ ... ax_.axvspan(freq[1], freq[2], color='y', alpha=.25)
+ ... ax_.grid(True)
+ >>> plt.show()
+
+ The impulse response and group delay plot depict the 75 sample delay of the linear
+ phase filter `h`. The phase should also be linear in the stop band--due to the small
+ magnitude, numeric noise dominates there. Furthermore, the plots show that the
+ minimum phase filters clearly show a reduced (negative) phase slope in the pass and
+ transition band. The plots also illustrate that the filter with parameters
+ ``method='homomorphic', half=False`` has same order and magnitude response as the
+ linear filter `h` whereas the other minimum phase filters have only half the order
+ and the square root of the magnitude response.
+ """
+ xp = array_namespace(h)
+
+ h = xp.asarray(h)
+ if xp.isdtype(h.dtype, "complex floating"):
+ raise ValueError('Complex filters not supported')
+ if h.ndim != 1 or h.shape[0] <= 2:
+ raise ValueError('h must be 1-D and at least 2 samples long')
+ n_half = h.shape[0] // 2
+
+ if not xp.any(xp.flip(h[-n_half:]) - h[:n_half] <= 1e-8 + 1e-6*abs(h[:n_half])):
+ warnings.warn('h does not appear to by symmetric, conversion may fail',
+ RuntimeWarning, stacklevel=2)
+ if not isinstance(method, str) or method not in \
+ ('homomorphic', 'hilbert',):
+ raise ValueError(f'method must be "homomorphic" or "hilbert", got {method!r}')
+ if method == "hilbert" and not half:
+ raise ValueError("`half=False` is only supported when `method='homomorphic'`")
+ if n_fft is None:
+ n_fft = 2 ** int(ceil(log2(2 * (h.shape[0] - 1) / 0.01)))
+ n_fft = int(n_fft)
+ if n_fft < h.shape[0]:
+ raise ValueError(f'n_fft must be at least len(h)=={len(h)}')
+
+ if method == 'hilbert':
+ w = xp.arange(n_fft, dtype=xp.float64) * (2 * xp.pi / n_fft * n_half)
+ H = xp.real(fft(h, n_fft) * xp.exp(1j * w))
+ dp = max(H) - 1
+ ds = 0 - min(H)
+ S = 4. / (xp.sqrt(1+dp+ds) + xp.sqrt(1-dp+ds)) ** 2
+ H += ds
+ H *= S
+ H = xp.sqrt(H)
+ H += 1e-10 # ensure that the log does not explode
+ h_minimum = _dhtm(H, xp)
+ else: # method == 'homomorphic'
+ # zero-pad; calculate the DFT
+ h_temp = xp.abs(fft(h, n_fft))
+ # take 0.25*log(|H|**2) = 0.5*log(|H|)
+ h_temp += 1e-7 * xp.min(h_temp[h_temp > 0]) # don't let log blow up
+ h_temp = xp.log(h_temp)
+ if half: # halving of magnitude spectrum optional
+ h_temp *= 0.5
+ # IDFT
+ h_temp = xp.real(ifft(h_temp))
+ # multiply pointwise by the homomorphic filter
+ # lmin[n] = 2u[n] - d[n]
+ # i.e., double the positive frequencies and zero out the negative ones;
+ # Oppenheim+Shafer 3rd ed p991 eq13.42b and p1004 fig13.7
+ win = xp.zeros(n_fft, dtype=h_temp.dtype)
+ win = xpx.at(win)[0].set(1)
+ stop = n_fft // 2
+ win = xpx.at(win)[1:stop].set(2)
+ # Nyquist freq: odd use 2, even use 1
+ win = xpx.at(win)[stop].set(1 + (n_fft % 2))
+ h_temp *= win
+ h_temp = ifft(xp.exp(fft(h_temp)))
+ h_minimum = xp.real(h_temp)
+ n_out = (n_half + h.shape[0] % 2) if half else h.shape[0]
+ return h_minimum[:n_out]
+
+
+def firwin_2d(hsize, window, *, fc=None, fs=2, circular=False,
+ pass_zero=True, scale=True):
+ """
+ 2D FIR filter design using the window method.
+
+ This function computes the coefficients of a 2D finite impulse response
+ filter. The filter is separable with linear phase; it will be designed
+ as a product of two 1D filters with dimensions defined by `hsize`.
+ Additionally, it can create approximately circularly symmetric 2-D windows.
+
+ Parameters
+ ----------
+ hsize : tuple or list of length 2
+ Lengths of the filter in each dimension. `hsize[0]` specifies the
+ number of coefficients in the row direction and `hsize[1]` specifies
+ the number of coefficients in the column direction.
+ window : tuple or list of length 2 or str
+ Desired window to use for each 1D filter or a single window type for creating
+ circularly symmetric 2-D windows. Each element should be a string or tuple of
+ string and parameter values. The generated windows will be symmetric, unless a
+ suffix ``'_periodic'`` is appended to the window name (e.g.,
+ ``'hamming_perodic'``). Consult `~scipy.signal.get_window` for a list of windows
+ and required parameters.
+ fc : float or 1-D array_like, optional
+ Cutoff frequency of the filter in the same units as `fs`. This defines
+ the frequency at which the filter's gain drops to approximately -6 dB
+ (half power) in a low-pass or high-pass filter. For multi-band filters,
+ `fc` can be an array of cutoff frequencies (i.e., band edges) in the
+ range [0, fs/2], with each band specified in pairs. Required if
+ `circular` is False.
+ fs : float, optional
+ The sampling frequency of the signal. Default is 2.
+ circular : bool, optional
+ Whether to create a circularly symmetric 2-D window. Default is ``False``.
+ pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
+ This parameter is directly passed to `firwin` for each scalar frequency axis.
+ Hence, if ``True``, the DC gain, i.e., the gain at frequency (0, 0), is 1.
+ If ``False``, the DC gain is 0 at frequency (0, 0) if `circular` is ``True``.
+ If `circular` is ``False`` the frequencies (0, f1) and (f0, 0) will
+ have gain 0.
+ It can also be a string argument for the desired filter type
+ (equivalent to ``btype`` in IIR design functions).
+ scale : bool, optional
+ This parameter is directly passed to `firwin` for each scalar frequency axis.
+ Set to ``True`` to scale the coefficients so that the frequency
+ response is exactly unity at a certain frequency on one frequency axis.
+ That frequency is either:
+
+ - 0 (DC) if the first passband starts at 0 (i.e. pass_zero is ``True``)
+ - `fs`/2 (the Nyquist frequency) if the first passband ends at `fs`/2
+ (i.e., the filter is a single band highpass filter);
+ center of first passband otherwise
+
+ Returns
+ -------
+ filter_2d : (hsize[0], hsize[1]) ndarray
+ Coefficients of 2D FIR filter.
+
+ Raises
+ ------
+ ValueError
+ - If `hsize` and `window` are not 2-element tuples or lists.
+ - If `cutoff` is None when `circular` is True.
+ - If `cutoff` is outside the range [0, `fs`/2] and `circular` is ``False``.
+ - If any of the elements in `window` are not recognized.
+ RuntimeError
+ If `firwin` fails to converge when designing the filter.
+
+ See Also
+ --------
+ firwin: FIR filter design using the window method for 1d arrays.
+ get_window: Return a window of a given length and type.
+
+ Examples
+ --------
+ Generate a 5x5 low-pass filter with cutoff frequency 0.1:
+
+ >>> import numpy as np
+ >>> from scipy.signal import get_window
+ >>> from scipy.signal import firwin_2d
+ >>> hsize = (5, 5)
+ >>> window = (("kaiser", 5.0), ("kaiser", 5.0))
+ >>> fc = 0.1
+ >>> filter_2d = firwin_2d(hsize, window, fc=fc)
+ >>> filter_2d
+ array([[0.00025366, 0.00401662, 0.00738617, 0.00401662, 0.00025366],
+ [0.00401662, 0.06360159, 0.11695714, 0.06360159, 0.00401662],
+ [0.00738617, 0.11695714, 0.21507283, 0.11695714, 0.00738617],
+ [0.00401662, 0.06360159, 0.11695714, 0.06360159, 0.00401662],
+ [0.00025366, 0.00401662, 0.00738617, 0.00401662, 0.00025366]])
+
+ Generate a circularly symmetric 5x5 low-pass filter with Hamming window:
+
+ >>> filter_2d = firwin_2d((5, 5), 'hamming', fc=fc, circular=True)
+ >>> filter_2d
+ array([[-0.00020354, -0.00020354, -0.00020354, -0.00020354, -0.00020354],
+ [-0.00020354, 0.01506844, 0.09907658, 0.01506844, -0.00020354],
+ [-0.00020354, 0.09907658, -0.00020354, 0.09907658, -0.00020354],
+ [-0.00020354, 0.01506844, 0.09907658, 0.01506844, -0.00020354],
+ [-0.00020354, -0.00020354, -0.00020354, -0.00020354, -0.00020354]])
+
+ Generate Plots comparing the product of two 1d filters with a circular
+ symmetric filter:
+
+ >>> import matplotlib.pyplot as plt
+ >>> hsize, fc = (50, 50), 0.05
+ >>> window = (("kaiser", 5.0), ("kaiser", 5.0))
+ >>> filter0_2d = firwin_2d(hsize, window, fc=fc)
+ >>> filter1_2d = firwin_2d((50, 50), 'hamming', fc=fc, circular=True)
+ ...
+ >>> fg, (ax0, ax1) = plt.subplots(1, 2, tight_layout=True, figsize=(6.5, 3.5))
+ >>> ax0.set_title("Product of 2 Windows")
+ >>> im0 = ax0.imshow(filter0_2d, cmap='viridis', origin='lower', aspect='equal')
+ >>> fg.colorbar(im0, ax=ax0, shrink=0.7)
+ >>> ax1.set_title("Circular Window")
+ >>> im1 = ax1.imshow(filter1_2d, cmap='plasma', origin='lower', aspect='equal')
+ >>> fg.colorbar(im1, ax=ax1, shrink=0.7)
+ >>> plt.show()
+ """
+ if len(hsize) != 2:
+ raise ValueError("hsize must be a 2-element tuple or list")
+
+ if circular:
+ if fc is None:
+ raise ValueError("Cutoff frequency `fc` must be "
+ "provided when `circular` is True")
+
+ n_r = max(hsize[0], hsize[1]) * 8 # oversample 1d window by factor 8
+
+ win_r = firwin(n_r, cutoff=fc, window=window, fs=fs)
+
+ f1, f2 = np.meshgrid(np.linspace(-1, 1, hsize[0]), np.linspace(-1, 1, hsize[1]))
+ r = np.sqrt(f1**2 + f2**2)
+
+ win_2d = np.interp(r, np.linspace(0, 1, n_r), win_r)
+ return win_2d
+
+ if len(window) != 2:
+ raise ValueError("window must be a 2-element tuple or list")
+
+ row_filter = firwin(hsize[0], cutoff=fc, window=window[0], fs=fs)
+ col_filter = firwin(hsize[1], cutoff=fc, window=window[1], fs=fs)
+
+ return np.outer(row_filter, col_filter)
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_lti_conversion.py b/.venv/lib/python3.12/site-packages/scipy/signal/_lti_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..22074ba4b47a822f00301a2114aaec3a94bce7b8
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_lti_conversion.py
@@ -0,0 +1,583 @@
+"""
+ltisys -- a collection of functions to convert linear time invariant systems
+from one representation to another.
+"""
+
+import numpy as np
+from numpy import (r_, eye, atleast_2d, poly, dot,
+ asarray, zeros, array, outer)
+from scipy import linalg
+
+from scipy._lib._array_api import (array_namespace, xp_size, xp_promote,
+ xp_result_type)
+import scipy._external.array_api_extra as xpx
+from ._filter_design import tf2zpk, zpk2tf, normalize
+
+
+__all__ = ['tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk',
+ 'cont2discrete']
+
+
+def tf2ss(num, den):
+ r"""Transfer function to state-space representation.
+
+ Parameters
+ ----------
+ num, den : array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of descending degree. The
+ denominator needs to be at least as long as the numerator.
+
+ Returns
+ -------
+ A, B, C, D : ndarray
+ State space representation of the system, in controller canonical
+ form.
+
+ Examples
+ --------
+ Convert the transfer function:
+
+ .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ to the state-space representation:
+
+ .. math::
+
+ \dot{\textbf{x}}(t) =
+ \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
+
+ \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
+
+ >>> from scipy.signal import tf2ss
+ >>> A, B, C, D = tf2ss(num, den)
+ >>> A
+ array([[-2., -1.],
+ [ 1., 0.]])
+ >>> B
+ array([[ 1.],
+ [ 0.]])
+ >>> C
+ array([[ 1., 2.]])
+ >>> D
+ array([[ 1.]])
+ """
+ # Controller canonical state-space representation.
+ # if M+1 = len(num) and K+1 = len(den) then we must have M <= K
+ # states are found by asserting that X(s) = U(s) / D(s)
+ # then Y(s) = N(s) * X(s)
+ #
+ # A, B, C, and D follow quite naturally.
+ #
+ num, den = normalize(num, den) # Strips zeros, checks arrays
+ nn = len(num.shape)
+ if nn == 1:
+ num = asarray([num], num.dtype)
+ M = num.shape[1]
+ K = len(den)
+ if M > K:
+ msg = "Improper transfer function. `num` is longer than `den`."
+ raise ValueError(msg)
+ if M == 0 or K == 0: # Null system
+ return (array([], float), array([], float), array([], float),
+ array([], float))
+
+ # pad numerator to have same number of columns has denominator
+ num = np.hstack((np.zeros((num.shape[0], K - M), dtype=num.dtype), num))
+
+ if num.shape[-1] > 0:
+ D = atleast_2d(num[:, 0])
+
+ else:
+ # We don't assign it an empty array because this system
+ # is not 'null'. It just doesn't have a non-zero D
+ # matrix. Thus, it should have a non-zero shape so that
+ # it can be operated on by functions like 'ss2tf'
+ D = array([[0]], float)
+
+ if K == 1:
+ D = D.reshape(num.shape)
+
+ return (zeros((1, 1)), zeros((1, D.shape[1])),
+ zeros((D.shape[0], 1)), D)
+
+ frow = -array([den[1:]])
+ A = r_[frow, eye(K - 2, K - 1)]
+ B = eye(K - 1, 1)
+ C = num[:, 1:] - outer(num[:, 0], den[1:])
+ D = D.reshape((C.shape[0], B.shape[1]))
+
+ return A, B, C, D
+
+
+def abcd_normalize(A=None, B=None, C=None, D=None):
+ r"""Check state-space matrices compatibility and ensure they are 2d arrays.
+
+ First, the input matrices are converted into two-dimensional arrays with
+ appropriate dtype as needed. Then the dimensions n, q, p are determined by
+ investigating the array shapes. If an input is ``None``, or has size zero, it is
+ set to an array of zeros of compatible shape. Finally, it is verified that all
+ parameter shapes are compatible with each other. If that fails, a ``ValueError`` is
+ raised. Note that the dimensions n, q, p are allowed to be zero.
+
+ Parameters
+ ----------
+ A : array_like, optional
+ Two-dimensional array of shape (n, n).
+ B : array_like, optional
+ Two-dimensional array of shape (n, p).
+ C : array_like, optional
+ Two-dimensional array of shape (q, n).
+ D : array_like, optional
+ Two-dimensional array of shape (q, p).
+
+ Returns
+ -------
+ A, B, C, D : array
+ State-space matrices as two-dimensional arrays with identical dtype.
+ The result dtype is determined based on the standard
+ `dtype promotion rules `_
+ except for when the inputs are all of integer dtype, in which case the returned
+ arrays will have the default floating point dtype of ``float64``.
+
+ Raises
+ ------
+ ValueError
+ If the dimensions n, q, or p could not be determined or if the shapes are
+ incompatible with each other.
+
+ Notes
+ -----
+ If a matrix is not modified, the original matrix (not a copy) is returned.
+
+ The :ref:`tutorial_signal_state_space_representation` section of the
+ :ref:`user_guide` presents the corresponding definitions of continuous-time and
+ disrcete time state space systems.
+
+ See Also
+ --------
+ StateSpace: Linear Time Invariant system in state-space form.
+ dlti: Discrete-time linear time invariant system base class.
+ tf2ss: Transfer function to state-space representation.
+ ss2tf: State-space to transfer function.
+ ss2zpk: State-space representation to zero-pole-gain representation.
+ cont2discrete: Transform a continuous to a discrete state-space system.
+
+ Examples
+ --------
+ The following example demonstrates that the passed lists are converted into
+ two-dimensional arrays:
+
+ >>> from scipy.signal import abcd_normalize
+ >>> AA, BB, CC, DD = abcd_normalize(A=[[1, 2], [3, 4]], B=[[-1], [5]],
+ ... C=[[4, 5]], D=2.5)
+ >>> AA.shape, BB.shape, CC.shape, DD.shape
+ ((2, 2), (2, 1), (1, 2), (1, 1))
+
+ In the following, the missing parameter C is assumed to be an array of zeros
+ with shape (1, 2):
+
+ >>> from scipy.signal import abcd_normalize
+ >>> AA, BB, CC, DD = abcd_normalize(A=[[1, 2], [3, 4]], B=[[-1], [5]], D=2.5)
+ >>> AA.shape, BB.shape, CC.shape, DD.shape
+ ((2, 2), (2, 1), (1, 2), (1, 1))
+ >>> CC
+ array([[0., 0.]])
+
+ """
+ if A is None and B is None and C is None:
+ raise ValueError("Dimension n is undefined for parameters A = B = C = None!")
+ if B is None and D is None:
+ raise ValueError("Dimension p is undefined for parameters B = D = None!")
+ if C is None and D is None:
+ raise ValueError("Dimension q is undefined for parameters C = D = None!")
+
+ xp = array_namespace(A, B, C, D)
+ A, B, C, D = xp_promote(A, B, C, D, xp=xp, force_floating=True)
+ dtype = xp_result_type(A, B, C, D, xp=xp)
+
+ # convert inputs into 2d arrays (zero-size 2d array if None):
+ A, B, C, D = (
+ xpx.atleast_nd(xp.asarray(M_), ndim=2, xp=xp)
+ if M_ is not None else xp.zeros((0, 0), dtype=dtype)
+ for M_ in (A, B, C, D)
+ )
+
+ n = A.shape[0] or B.shape[0] or C.shape[1] # try finding non-zero dimensions
+ p = B.shape[1] or D.shape[1]
+ q = C.shape[0] or D.shape[0]
+
+ # Create zero matrices as needed:
+ A = xp.zeros((n, n), dtype=dtype) if xp_size(A) == 0 else A
+ B = xp.zeros((n, p), dtype=dtype) if xp_size(B) == 0 else B
+ C = xp.zeros((q, n), dtype=dtype) if xp_size(C) == 0 else C
+ D = xp.zeros((q, p), dtype=dtype) if xp_size(D) == 0 else D
+
+ if A.shape != (n, n):
+ raise ValueError(f"Parameter A has shape {A.shape} but should be ({n}, {n})!")
+ if B.shape != (n, p):
+ raise ValueError(f"Parameter B has shape {B.shape} but should be ({n}, {p})!")
+ if C.shape != (q, n):
+ raise ValueError(f"Parameter C has shape {C.shape} but should be ({q}, {n})!")
+ if D.shape != (q, p):
+ raise ValueError(f"Parameter D has shape {D.shape} but should be ({q}, {p})!")
+
+ return A, B, C, D
+
+
+def ss2tf(A, B, C, D, input=0):
+ r"""State-space to transfer function.
+
+ A, B, C, D defines a linear state-space system with `p` inputs,
+ `q` outputs, and `n` state variables.
+
+ Parameters
+ ----------
+ A : array_like
+ State (or system) matrix of shape ``(n, n)``
+ B : array_like
+ Input matrix of shape ``(n, p)``
+ C : array_like
+ Output matrix of shape ``(q, n)``
+ D : array_like
+ Feedthrough (or feedforward) matrix of shape ``(q, p)``
+ input : int, optional
+ For multiple-input systems, the index of the input to use.
+
+ Returns
+ -------
+ num : 2-D ndarray
+ Numerator(s) of the resulting transfer function(s). `num` has one row
+ for each of the system's outputs. Each row is a sequence representation
+ of the numerator polynomial.
+ den : 1-D ndarray
+ Denominator of the resulting transfer function(s). `den` is a sequence
+ representation of the denominator polynomial.
+
+ Notes
+ -----
+ Before calculating `num` and `den`, the function `abcd_normalize` is called to
+ convert the parameters `A`, `B`, `C`, `D` into two-dimesional arrays of the
+ same dtype. The resulting dtype will be based on NumPy's dtype promotion rules,
+ except in the case where each of `A`, `B`, `C`, and `D` has integer dtype, in which
+ case the resulting dtype will be the default floating point dtype of ``float64``.
+
+ The :ref:`tutorial_signal_state_space_representation` section of the
+ :ref:`user_guide` presents the corresponding definitions of continuous-time and
+ disrcete time state space systems.
+
+ Examples
+ --------
+ Convert the state-space representation:
+
+ .. math::
+
+ \dot{\textbf{x}}(t) =
+ \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
+
+ \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
+
+ >>> A = [[-2, -1], [1, 0]]
+ >>> B = [[1], [0]] # 2-D column vector
+ >>> C = [[1, 2]] # 2-D row vector
+ >>> D = 1
+
+ to the transfer function:
+
+ .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
+
+ >>> from scipy.signal import ss2tf
+ >>> ss2tf(A, B, C, D)
+ (array([[1., 3., 3.]]), array([ 1., 2., 1.]))
+ """
+ # transfer function is C (sI - A)**(-1) B + D
+
+ # Check consistency and make them all floating point 2d arrays:
+ A, B, C, D = abcd_normalize(A, B, C, D)
+
+ nout, nin = D.shape
+ if input >= nin:
+ raise ValueError("System does not have the input specified.")
+
+ # make SIMO from possibly MIMO system.
+ B = B[:, input:input + 1]
+ D = D[:, input:input + 1]
+
+ try:
+ den = poly(A)
+ except ValueError:
+ den = 1
+
+ if (B.size == 0) and (C.size == 0):
+ num = np.ravel(D)
+ if (D.size == 0) and (A.size == 0):
+ den = []
+ return num, den
+
+ num_states = A.shape[0]
+ type_test = A[:, 0] + B[:, 0] + C[0, :] + D + 0.0
+ num = np.empty((nout, num_states + 1), type_test.dtype)
+ for k in range(nout):
+ Ck = atleast_2d(C[k, :])
+ num[k] = poly(A - dot(B, Ck)) + (D[k] - 1) * den
+
+ return num, den
+
+
+def zpk2ss(z, p, k):
+ """Zero-pole-gain representation to state-space representation.
+
+ Parameters
+ ----------
+ z, p : sequence
+ Zeros and poles.
+ k : float
+ System gain.
+
+ Returns
+ -------
+ A, B, C, D : ndarray
+ State space representation of the system, in controller canonical
+ form.
+
+ """
+ return tf2ss(*zpk2tf(z, p, k))
+
+
+def ss2zpk(A, B, C, D, input=0):
+ """State-space representation to zero-pole-gain representation.
+
+ A, B, C, D defines a linear state-space system with `p` inputs,
+ `q` outputs, and `n` state variables.
+
+ Parameters
+ ----------
+ A : array_like
+ State (or system) matrix of shape ``(n, n)``
+ B : array_like
+ Input matrix of shape ``(n, p)``
+ C : array_like
+ Output matrix of shape ``(q, n)``
+ D : array_like
+ Feedthrough (or feedforward) matrix of shape ``(q, p)``
+ input : int, optional
+ For multiple-input systems, the index of the input to use.
+
+ Returns
+ -------
+ z, p : sequence
+ Zeros and poles.
+ k : float
+ System gain.
+
+ """
+ return tf2zpk(*ss2tf(A, B, C, D, input=input))
+
+
+def cont2discrete(system, dt, method="zoh", alpha=None):
+ """
+ Transform a continuous to a discrete state-space system.
+
+ Parameters
+ ----------
+ system : a tuple describing the system or an instance of `lti`
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1: (instance of `lti`)
+ * 2: (num, den)
+ * 3: (zeros, poles, gain)
+ * 4: (A, B, C, D)
+
+ dt : float
+ The discretization time step.
+ method : str, optional
+ Which method to use:
+
+ * gbt: generalized bilinear transformation
+ * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
+ * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
+ * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
+ * zoh: zero-order hold (default)
+ * foh: first-order hold (*versionadded: 1.3.0*)
+ * impulse: equivalent impulse response (*versionadded: 1.3.0*)
+
+ alpha : float within [0, 1], optional
+ The generalized bilinear transformation weighting parameter, which
+ should only be specified with method="gbt", and is ignored otherwise
+
+ Returns
+ -------
+ sysd : tuple containing the discrete system
+ Based on the input type, the output will be of the form
+
+ * (num, den, dt) for transfer function input
+ * (zeros, poles, gain, dt) for zeros-poles-gain input
+ * (A, B, C, D, dt) for state-space system input
+
+ Notes
+ -----
+ By default, the routine uses a Zero-Order Hold (zoh) method to perform
+ the transformation. Alternatively, a generalized bilinear transformation
+ may be used, which includes the common Tustin's bilinear approximation,
+ an Euler's method technique, or a backwards differencing technique.
+
+ The Zero-Order Hold (zoh) method is based on [1]_, the generalized bilinear
+ approximation is based on [2]_ and [3]_, the First-Order Hold (foh) method
+ is based on [4]_.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Discretization#Discretization_of_linear_state_space_models
+
+ .. [2] http://techteach.no/publications/discretetime_signals_systems/discrete.pdf
+
+ .. [3] G. Zhang, X. Chen, and T. Chen, Digital redesign via the generalized
+ bilinear transformation, Int. J. Control, vol. 82, no. 4, pp. 741-754,
+ 2009.
+ (https://www.mypolyuweb.hk/~magzhang/Research/ZCC09_IJC.pdf)
+
+ .. [4] G. F. Franklin, J. D. Powell, and M. L. Workman, Digital control
+ of dynamic systems, 3rd ed. Menlo Park, Calif: Addison-Wesley,
+ pp. 204-206, 1998.
+
+ Examples
+ --------
+ We can transform a continuous state-space system to a discrete one:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import cont2discrete, lti, dlti, dstep
+
+ Define a continuous state-space system.
+
+ >>> A = np.array([[0, 1],[-10., -3]])
+ >>> B = np.array([[0],[10.]])
+ >>> C = np.array([[1., 0]])
+ >>> D = np.array([[0.]])
+ >>> l_system = lti(A, B, C, D)
+ >>> t, x = l_system.step(T=np.linspace(0, 5, 100))
+ >>> fig, ax = plt.subplots()
+ >>> ax.plot(t, x, label='Continuous', linewidth=3)
+
+ Transform it to a discrete state-space system using several methods.
+
+ >>> dt = 0.1
+ >>> for method in ['zoh', 'bilinear', 'euler', 'backward_diff', 'foh', 'impulse']:
+ ... d_system = cont2discrete((A, B, C, D), dt, method=method)
+ ... s, x_d = dstep(d_system)
+ ... ax.step(s, np.squeeze(x_d), label=method, where='post')
+ >>> ax.axis([t[0], t[-1], x[0], 1.4])
+ >>> ax.legend(loc='best')
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ """
+ if hasattr(system, 'to_discrete') and callable(system.to_discrete):
+ return system.to_discrete(dt=dt, method=method, alpha=alpha)
+
+ if len(system) == 2:
+ sysd = cont2discrete(tf2ss(system[0], system[1]), dt, method=method,
+ alpha=alpha)
+ return ss2tf(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,)
+ elif len(system) == 3:
+ sysd = cont2discrete(zpk2ss(system[0], system[1], system[2]), dt,
+ method=method, alpha=alpha)
+ return ss2zpk(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,)
+ elif len(system) == 4:
+ a, b, c, d = system
+ else:
+ raise ValueError("First argument must either be a tuple of 2 (tf), "
+ "3 (zpk), or 4 (ss) arrays.")
+
+ if method == 'gbt':
+ if alpha is None:
+ raise ValueError("Alpha parameter must be specified for the "
+ "generalized bilinear transform (gbt) method")
+ elif alpha < 0 or alpha > 1:
+ raise ValueError("Alpha parameter must be within the interval "
+ "[0,1] for the gbt method")
+
+ if method == 'gbt':
+ # This parameter is used repeatedly - compute once here
+ ima = np.eye(a.shape[0]) - alpha*dt*a
+ ad = linalg.solve(ima, np.eye(a.shape[0]) + (1.0-alpha)*dt*a)
+ bd = linalg.solve(ima, dt*b)
+
+ # Similarly solve for the output equation matrices
+ cd = linalg.solve(ima.transpose(), c.transpose())
+ cd = cd.transpose()
+ dd = d + alpha*np.dot(c, bd)
+
+ elif method == 'bilinear' or method == 'tustin':
+ return cont2discrete(system, dt, method="gbt", alpha=0.5)
+
+ elif method == 'euler' or method == 'forward_diff':
+ return cont2discrete(system, dt, method="gbt", alpha=0.0)
+
+ elif method == 'backward_diff':
+ return cont2discrete(system, dt, method="gbt", alpha=1.0)
+
+ elif method == 'zoh':
+ # Build an exponential matrix
+ em_upper = np.hstack((a, b))
+
+ # Need to stack zeros under the a and b matrices
+ em_lower = np.hstack((np.zeros((b.shape[1], a.shape[0])),
+ np.zeros((b.shape[1], b.shape[1]))))
+
+ em = np.vstack((em_upper, em_lower))
+ ms = linalg.expm(dt * em)
+
+ # Dispose of the lower rows
+ ms = ms[:a.shape[0], :]
+
+ ad = ms[:, 0:a.shape[1]]
+ bd = ms[:, a.shape[1]:]
+
+ cd = c
+ dd = d
+
+ elif method == 'foh':
+ # Size parameters for convenience
+ n = a.shape[0]
+ m = b.shape[1]
+
+ # Build an exponential matrix similar to 'zoh' method
+ em_upper = linalg.block_diag(np.block([a, b]) * dt, np.eye(m))
+ em_lower = zeros((m, n + 2 * m))
+ em = np.block([[em_upper], [em_lower]])
+
+ ms = linalg.expm(em)
+
+ # Get the three blocks from upper rows
+ ms11 = ms[:n, 0:n]
+ ms12 = ms[:n, n:n + m]
+ ms13 = ms[:n, n + m:]
+
+ ad = ms11
+ bd = ms12 - ms13 + ms11 @ ms13
+ cd = c
+ dd = d + c @ ms13
+
+ elif method == 'impulse':
+ if not np.allclose(d, 0):
+ raise ValueError("Impulse method is only applicable "
+ "to strictly proper systems")
+
+ ad = linalg.expm(a * dt)
+ bd = ad @ b * dt
+ cd = c
+ dd = c @ b * dt
+
+ else:
+ raise ValueError(f"Unknown transformation method '{method}'")
+
+ return ad, bd, cd, dd, dt
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_ltisys.py b/.venv/lib/python3.12/site-packages/scipy/signal/_ltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dc430c25c02e66c30d5bd8170610fca36607e8f
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_ltisys.py
@@ -0,0 +1,3851 @@
+"""
+ltisys -- a collection of classes and functions for modeling linear
+time invariant systems.
+"""
+#
+# Author: Travis Oliphant 2001
+#
+# Feb 2010: Warren Weckesser
+# Rewrote lsim2 and added impulse2.
+# Apr 2011: Jeffrey Armstrong
+# Added dlsim, dstep, dimpulse, cont2discrete
+# Aug 2013: Juan Luis Cano
+# Rewrote abcd_normalize.
+# Jan 2015: Irvin Probst irvin DOT probst AT ensta-bretagne DOT fr
+# Added pole placement
+# Mar 2015: Clancy Rowley
+# Rewrote lsim
+# May 2015: Felix Berkenkamp
+# Split lti class into subclasses
+# Merged discrete systems and added dlti
+
+import warnings
+from types import GenericAlias
+
+# np.linalg.qr fails on some tests with LinAlgError: zgeqrf returns -7
+# use scipy's qr until this is solved
+
+from scipy.linalg import qr as s_qr
+from scipy import linalg
+from scipy.interpolate import make_interp_spline
+from ._filter_design import (tf2zpk, zpk2tf, normalize, freqs, freqz, freqs_zpk,
+ freqz_zpk)
+from ._lti_conversion import (tf2ss, abcd_normalize, ss2tf, zpk2ss, ss2zpk,
+ cont2discrete)
+
+import numpy as np
+from numpy import (real, atleast_1d, squeeze, asarray, zeros,
+ dot, transpose, ones, linspace)
+import copy
+
+__all__ = ['lti', 'dlti', 'TransferFunction', 'ZerosPolesGain', 'StateSpace',
+ 'lsim', 'impulse', 'step', 'bode',
+ 'freqresp', 'place_poles', 'dlsim', 'dstep', 'dimpulse',
+ 'dfreqresp', 'dbode']
+
+
+class LinearTimeInvariant:
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def __new__(cls, *system, **kwargs):
+ """Create a new object, don't allow direct instances."""
+ if cls is LinearTimeInvariant:
+ raise NotImplementedError('The LinearTimeInvariant class is not '
+ 'meant to be used directly, use `lti` '
+ 'or `dlti` instead.')
+ return super().__new__(cls)
+
+ def __init__(self):
+ """
+ Initialize the `lti` baseclass.
+
+ The heavy lifting is done by the subclasses.
+ """
+ super().__init__()
+
+ self.inputs = None
+ self.outputs = None
+ self._dt = None
+
+ @property
+ def dt(self):
+ """Return the sampling time of the system, `None` for `lti` systems."""
+ return self._dt
+
+ @property
+ def _dt_dict(self):
+ if self.dt is None:
+ return {}
+ else:
+ return {'dt': self.dt}
+
+ @property
+ def zeros(self):
+ """Zeros of the system."""
+ return self.to_zpk().zeros
+
+ @property
+ def poles(self):
+ """Poles of the system."""
+ return self.to_zpk().poles
+
+ def _as_ss(self):
+ """Convert to `StateSpace` system, without copying.
+
+ Returns
+ -------
+ sys: StateSpace
+ The `StateSpace` system. If the class is already an instance of
+ `StateSpace` then this instance is returned.
+ """
+ if isinstance(self, StateSpace):
+ return self
+ else:
+ return self.to_ss()
+
+ def _as_zpk(self):
+ """Convert to `ZerosPolesGain` system, without copying.
+
+ Returns
+ -------
+ sys: ZerosPolesGain
+ The `ZerosPolesGain` system. If the class is already an instance of
+ `ZerosPolesGain` then this instance is returned.
+ """
+ if isinstance(self, ZerosPolesGain):
+ return self
+ else:
+ return self.to_zpk()
+
+ def _as_tf(self):
+ """Convert to `TransferFunction` system, without copying.
+
+ Returns
+ -------
+ sys: ZerosPolesGain
+ The `TransferFunction` system. If the class is already an instance of
+ `TransferFunction` then this instance is returned.
+ """
+ if isinstance(self, TransferFunction):
+ return self
+ else:
+ return self.to_tf()
+
+
+class lti(LinearTimeInvariant):
+ r"""
+ Continuous-time linear time invariant system base class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `lti` class can be instantiated with either 2, 3 or 4 arguments.
+ The following gives the number of arguments and the corresponding
+ continuous-time subclass that is created:
+
+ * 2: `TransferFunction`: (numerator, denominator)
+ * 3: `ZerosPolesGain`: (zeros, poles, gain)
+ * 4: `StateSpace`: (A, B, C, D)
+
+ Each argument can be an array or a sequence.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, TransferFunction, dlti
+
+ Notes
+ -----
+ `lti` instances do not exist directly. Instead, `lti` creates an instance
+ of one of its subclasses: `StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients for
+ both the numerator and denominator should be specified in descending
+ exponent order (e.g., ``s^2 + 3s + 5`` would be represented as ``[1, 3,
+ 5]``).
+
+ Changing the value of properties that are not directly part of the current
+ system representation (such as the `zeros` of a `StateSpace` system) is
+ very inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ Examples
+ --------
+ >>> from scipy import signal
+
+ >>> signal.lti(1, 2, 3, 4)
+ StateSpaceContinuous(
+ array([[1.]]),
+ array([[2.]]),
+ array([[3.]]),
+ array([[4.]]),
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> signal.lti([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ Construct the transfer function :math:`H(s) = \frac{3s + 4}{1s + 2}`:
+
+ >>> signal.lti([3, 4], [1, 2])
+ TransferFunctionContinuous(
+ array([3., 4.]),
+ array([1., 2.]),
+ dt: None
+ )
+
+ """
+ def __new__(cls, *system):
+ """Create an instance of the appropriate subclass."""
+ if cls is lti:
+ N = len(system)
+ if N == 2:
+ return TransferFunctionContinuous.__new__(
+ TransferFunctionContinuous, *system)
+ elif N == 3:
+ return ZerosPolesGainContinuous.__new__(
+ ZerosPolesGainContinuous, *system)
+ elif N == 4:
+ return StateSpaceContinuous.__new__(StateSpaceContinuous,
+ *system)
+ else:
+ raise ValueError("`system` needs to be an instance of `lti` "
+ "or have 2, 3 or 4 arguments.")
+ # __new__ was called from a subclass, let it call its own functions
+ return super().__new__(cls)
+
+ def __init__(self, *system):
+ """
+ Initialize the `lti` baseclass.
+
+ The heavy lifting is done by the subclasses.
+ """
+ super().__init__(*system)
+
+ def impulse(self, X0=None, T=None, N=None):
+ """
+ Return the impulse response of a continuous-time system.
+
+ Parameters
+ ----------
+ X0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ T : array_like, optional
+ Time points. Computed if not given.
+ N : int, optional
+ The number of time points to compute (if `T` is not given).
+
+ Returns
+ -------
+ T : ndarray
+ A 1-D array of time points.
+ yout : ndarray
+ A 1-D array containing the impulse response of the system (except for
+ singularities at zero).
+
+ See Also
+ --------
+ impulse : Impulse response of continuous-time LTI systems.
+ """
+ return impulse(self, X0=X0, T=T, N=N)
+
+ def step(self, X0=None, T=None, N=None):
+ """
+ Return the step response of a continuous-time system.
+
+ Parameters
+ ----------
+ X0 : array_like, optional
+ Initial state-vector (default is zero).
+ T : array_like, optional
+ Time points (computed if not given).
+ N : int, optional
+ Number of time points to compute if `T` is not given.
+
+ Returns
+ -------
+ T : 1D ndarray
+ Output time points.
+ yout : 1D ndarray
+ Step response of system.
+
+ See Also
+ --------
+ step : Step response of continuous-time LTI systems.
+ """
+ return step(self, X0=X0, T=T, N=N)
+
+ def output(self, U, T, X0=None):
+ """
+ Return the response of a continuous-time system to input `U`.
+
+ Parameters
+ ----------
+ U : array_like
+ An input array describing the input at each time `T`
+ (interpolation is assumed between given times). If there are
+ multiple inputs, then each column of the 2D array
+ represents an input. If U = 0 or None, a zero input is used.
+ T : array_like
+ The time steps at which the input is defined and at which the
+ output is desired. Must be nonnegative, increasing, and equally spaced.
+ X0 : array_like, optional
+ The initial conditions on the state vector (zero by default).
+
+ Returns
+ -------
+ T : 1D ndarray
+ Time values for the output.
+ yout : 1D ndarray
+ System response.
+ xout : ndarray
+ Time evolution of the state vector.
+
+ See Also
+ --------
+ lsim : Simulate output of continuous-time LTI systems.
+ """
+ return lsim(self, U, T, X0=X0)
+
+ def bode(self, w=None, n=100):
+ """
+ Calculate Bode magnitude and phase data of a continuous-time system.
+
+ Parameters
+ ----------
+ w : array_like, optional
+ Array of frequencies (in rad/s). Magnitude and phase data is calculated
+ for every value in this array. If not given a reasonable set will be
+ calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+ Defaults to 100.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [rad/s]
+ mag : 1D ndarray
+ Magnitude array [dB]
+ phase : 1D ndarray
+ Phase array [deg]
+
+ See Also
+ --------
+ bode : Bode plot data for continuous-time LTI systems.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> sys = signal.TransferFunction([1], [1, 1])
+ >>> w, mag, phase = sys.bode()
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, mag) # Bode magnitude plot
+ >>> plt.figure()
+ >>> plt.semilogx(w, phase) # Bode phase plot
+ >>> plt.show()
+
+ """
+ return bode(self, w=w, n=n)
+
+ def freqresp(self, w=None, n=10000):
+ """
+ Calculate the frequency response of a continuous-time system.
+
+ Parameters
+ ----------
+ w : array_like, optional
+ Array of frequencies (in rad/s). Magnitude and phase data is
+ calculated for every value in this array. If not given, a reasonable
+ set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+ Defaults to 10000.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [rad/s]
+ H : 1D ndarray
+ Array of complex magnitude values
+
+ See Also
+ --------
+ freqresp : Frequency response of continuous-time LTI systems.
+ """
+ return freqresp(self, w=w, n=n)
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """Return a discretized version of the current system.
+
+ Parameters
+ ----------
+ dt : float
+ The discretization time step.
+ method : str, optional
+ Which method to use:
+
+ * gbt: generalized bilinear transformation
+ * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
+ * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
+ * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
+ * zoh: zero-order hold (default)
+ * foh: first-order hold
+ * impulse: equivalent impulse response
+
+ alpha : float within [0, 1], optional
+ The generalized bilinear transformation weighting parameter, which
+ should only be specified with method="gbt", and is ignored otherwise
+
+ Returns
+ -------
+ sys: dlti
+ Discrete version of the current system.
+
+ See Also
+ --------
+ cont2discrete
+ """
+ raise NotImplementedError('to_discrete is not implemented for this '
+ 'system class.')
+
+
+class dlti(LinearTimeInvariant):
+ r"""
+ Discrete-time linear time invariant system base class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `dlti` class can be instantiated with either 2, 3 or 4 arguments.
+ The following gives the number of arguments and the corresponding
+ discrete-time subclass that is created:
+
+ * 2: `TransferFunction`: (numerator, denominator)
+ * 3: `ZerosPolesGain`: (zeros, poles, gain)
+ * 4: `StateSpace`: (A, B, C, D)
+
+ Each argument can be an array or a sequence.
+ dt : float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to ``True``
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, TransferFunction, lti
+
+ Notes
+ -----
+ `dlti` instances do not exist directly. Instead, `dlti` creates an instance
+ of one of its subclasses: `StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`.
+
+ Changing the value of properties that are not directly part of the current
+ system representation (such as the `zeros` of a `StateSpace` system) is
+ very inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients for
+ both the numerator and denominator should be specified in descending
+ exponent order (e.g., ``z^2 + 3z + 5`` would be represented as ``[1, 3,
+ 5]``).
+
+ .. versionadded:: 0.18.0
+
+ Examples
+ --------
+ >>> from scipy import signal
+
+ >>> signal.dlti(1, 2, 3, 4)
+ StateSpaceDiscrete(
+ array([[1.]]),
+ array([[2.]]),
+ array([[3.]]),
+ array([[4.]]),
+ dt: True
+ )
+
+ >>> signal.dlti(1, 2, 3, 4, dt=0.1)
+ StateSpaceDiscrete(
+ array([[1.]]),
+ array([[2.]]),
+ array([[3.]]),
+ array([[4.]]),
+ dt: 0.1
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time
+ of 0.1 seconds:
+
+ >>> signal.dlti([1, 2], [3, 4], 5, dt=0.1)
+ ZerosPolesGainDiscrete(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: 0.1
+ )
+
+ Construct the transfer function :math:`H(z) = \frac{3z + 4}{1z + 2}` with
+ a sampling time of 0.1 seconds:
+
+ >>> signal.dlti([3, 4], [1, 2], dt=0.1)
+ TransferFunctionDiscrete(
+ array([3., 4.]),
+ array([1., 2.]),
+ dt: 0.1
+ )
+
+ """
+ def __new__(cls, *system, dt=None):
+ """Create an instance of the appropriate subclass."""
+ if cls is dlti:
+ N = len(system)
+ if N == 2:
+ return TransferFunctionDiscrete.__new__(
+ TransferFunctionDiscrete, *system, dt=dt)
+ elif N == 3:
+ return ZerosPolesGainDiscrete.__new__(ZerosPolesGainDiscrete,
+ *system, dt=dt)
+ elif N == 4:
+ return StateSpaceDiscrete.__new__(StateSpaceDiscrete, *system,
+ dt=dt)
+ else:
+ raise ValueError("`system` needs to be an instance of `dlti` "
+ "or have 2, 3 or 4 arguments.")
+ # __new__ was called from a subclass, let it call its own functions
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """
+ Initialize the `lti` baseclass.
+
+ The heavy lifting is done by the subclasses.
+ """
+ dt = kwargs.pop('dt', True)
+ super().__init__(*system, **kwargs)
+
+ self.dt = dt
+
+ @property
+ def dt(self):
+ """Return the sampling time of the system."""
+ return self._dt
+
+ @dt.setter
+ def dt(self, dt):
+ self._dt = dt
+
+ def impulse(self, x0=None, t=None, n=None):
+ """
+ Return the impulse response of the discrete-time `dlti` system.
+
+ Parameters
+ ----------
+ x0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ t : array_like, optional
+ Time points. Computed if not given.
+ n : int, optional
+ The number of time points to compute (if `t` is not given).
+
+ Returns
+ -------
+ tout : ndarray
+ Time values for the output, as a 1-D array.
+ yout : tuple of ndarray
+ Impulse response of system. Each element of the tuple represents
+ the output of the system based on an impulse in each input.
+
+ See Also
+ --------
+ dimpulse : Impulse response of discrete-time LTI systems.
+ """
+ return dimpulse(self, x0=x0, t=t, n=n)
+
+ def step(self, x0=None, t=None, n=None):
+ """
+ Return the step response of the discrete-time `dlti` system.
+
+ Parameters
+ ----------
+ x0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ t : array_like, optional
+ Time points. Computed if not given.
+ n : int, optional
+ The number of time points to compute (if `t` is not given).
+
+ Returns
+ -------
+ tout : ndarray
+ Output time points, as a 1-D array.
+ yout : tuple of ndarray
+ Step response of system. Each element of the tuple represents
+ the output of the system based on a step response to each input.
+
+ See Also
+ --------
+ dstep : Step response of discrete-time LTI systems.
+ """
+ return dstep(self, x0=x0, t=t, n=n)
+
+ def output(self, u, t, x0=None):
+ """
+ Return the response of the discrete-time system to input `u`.
+
+ Parameters
+ ----------
+ u : array_like
+ An input array describing the input at each time `t` (interpolation is
+ assumed between given times). If there are multiple inputs, then each
+ column of the 2D array represents an input.
+ t : array_like, optional
+ The time steps at which the input is defined. If `t` is given, it
+ must be the same length as `u`, and the final value in `t` determines
+ the number of steps returned in the output.
+ x0 : array_like, optional
+ The initial conditions on the state vector (zero by default).
+
+ Returns
+ -------
+ tout : ndarray
+ Time values for the output, as a 1-D array.
+ yout : ndarray
+ System response, as a 1-D array.
+ xout : ndarray, optional
+ Time-evolution of the state-vector. Only generated if the input is a
+ `StateSpace` system.
+
+ See Also
+ --------
+ dlsim : Simulate output of discrete-time LTI systems.
+ """
+ return dlsim(self, u, t, x0=x0)
+
+ def bode(self, w=None, n=100):
+ r"""
+ Calculate Bode magnitude and phase data of a discrete-time system.
+
+ Parameters
+ ----------
+ w : array_like, optional
+ Array of frequencies normalized to the Nyquist frequency being π, i.e.,
+ having unit radiant / sample. Magnitude and phase data is calculated for
+ every value in this array. If not given, a reasonable set will be
+ calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+ Defaults to 100.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Array of frequencies normalized to the Nyquist frequency being ``np.pi/dt``
+ with ``dt`` being the sampling interval of the `system` parameter.
+ The unit is rad/s assuming ``dt`` is in seconds.
+ mag : 1D ndarray
+ Magnitude array in dB
+ phase : 1D ndarray
+ Phase array in degrees
+
+ See Also
+ --------
+ dbode : Bode plot data for discrete-time LTI systems.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ Construct the transfer function :math:`H(z) = \frac{1}{z^2 + 2z + 3}`
+ with sampling time 0.5s:
+
+ >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.5)
+
+ Equivalent: signal.dbode(sys)
+
+ >>> w, mag, phase = sys.bode()
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, mag) # Bode magnitude plot
+ >>> plt.figure()
+ >>> plt.semilogx(w, phase) # Bode phase plot
+ >>> plt.show()
+
+ """
+ return dbode(self, w=w, n=n)
+
+ def freqresp(self, w=None, n=10000, whole=False):
+ """
+ Calculate the frequency response of a discrete-time system.
+
+ Parameters
+ ----------
+ w : array_like, optional
+ Array of frequencies (in radians/sample). Magnitude and phase data is
+ calculated for every value in this array. If not given a reasonable
+ set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+ whole : bool, optional
+ Normally, if `w` is not given, frequencies are computed from 0 to the
+ Nyquist frequency, pi radians/sample (upper-half of unit-circle). If
+ `whole` is True, compute frequencies from 0 to 2*pi radians/sample.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [radians/sample]
+ H : 1D ndarray
+ Array of complex magnitude values
+
+ See Also
+ --------
+ dfreqresp : Frequency response of discrete-time LTI systems.
+ """
+ return dfreqresp(self, w=w, n=n, whole=whole)
+
+
+class TransferFunction(LinearTimeInvariant):
+ r"""Linear Time Invariant system class in transfer function form.
+
+ Represents the system as the continuous-time transfer function
+ :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j` or the
+ discrete-time transfer function
+ :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where
+ :math:`b` are elements of the numerator `num`, :math:`a` are elements of
+ the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``.
+ `TransferFunction` systems inherit additional
+ functionality from the `lti`, respectively the `dlti` classes, depending on
+ which system representation is used.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `TransferFunction` class can be instantiated with 1 or 2
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 2: array_like: (numerator, denominator)
+ dt : float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `None`
+ (continuous-time). Must be specified as a keyword argument, for
+ example, ``dt=0.1``.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, lti, dlti
+ tf2ss, tf2zpk, tf2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `TransferFunction` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients
+ for both the numerator and denominator should be specified in descending
+ exponent order (e.g. ``s^2 + 3s + 5`` or ``z^2 + 3z + 5`` would be
+ represented as ``[1, 3, 5]``)
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`:
+
+ >>> from scipy import signal
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ >>> signal.TransferFunction(num, den)
+ TransferFunctionContinuous(
+ array([1., 3., 3.]),
+ array([1., 2., 1.]),
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of
+ 0.1 seconds:
+
+ >>> signal.TransferFunction(num, den, dt=0.1)
+ TransferFunctionDiscrete(
+ array([1., 3., 3.]),
+ array([1., 2., 1.]),
+ dt: 0.1
+ )
+
+ """
+ def __new__(cls, *system, dt=None):
+ """Handle object conversion if input is an instance of lti."""
+ if len(system) == 1 and isinstance(system[0], LinearTimeInvariant):
+ return system[0].to_tf()
+
+ # Choose whether to inherit from `lti` or from `dlti`
+ if cls is TransferFunction:
+ if dt is None:
+ return TransferFunctionContinuous.__new__(
+ TransferFunctionContinuous, *system)
+ else:
+ return TransferFunctionDiscrete.__new__(
+ TransferFunctionDiscrete, *system, dt=dt)
+
+ # No special conversion needed
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """Initialize the state space LTI system."""
+ # Conversion of lti instances is handled in __new__
+ if isinstance(system[0], LinearTimeInvariant):
+ return
+
+ # Remove system arguments, not needed by parents anymore
+ super().__init__(**kwargs)
+
+ self._num = None
+ self._den = None
+
+ self.num, self.den = normalize(*system)
+
+ def __repr__(self):
+ """Return representation of the system's transfer function"""
+ return (
+ f'{self.__class__.__name__}(\n'
+ f'{repr(self.num)},\n'
+ f'{repr(self.den)},\n'
+ f'dt: {repr(self.dt)}\n)'
+ )
+
+ @property
+ def num(self):
+ """Numerator of the `TransferFunction` system."""
+ return self._num
+
+ @num.setter
+ def num(self, num):
+ self._num = atleast_1d(num)
+
+ # Update dimensions
+ if len(self.num.shape) > 1:
+ self.outputs, self.inputs = self.num.shape
+ else:
+ self.outputs = 1
+ self.inputs = 1
+
+ @property
+ def den(self):
+ """Denominator of the `TransferFunction` system."""
+ return self._den
+
+ @den.setter
+ def den(self, den):
+ self._den = atleast_1d(den)
+
+ def _copy(self, system):
+ """
+ Copy the parameters of another `TransferFunction` object
+
+ Parameters
+ ----------
+ system : `TransferFunction`
+ The `StateSpace` system that is to be copied
+
+ """
+ self.num = system.num
+ self.den = system.den
+
+ def to_tf(self):
+ """
+ Return a copy of the current `TransferFunction` system.
+
+ Returns
+ -------
+ sys : instance of `TransferFunction`
+ The current system (copy)
+
+ """
+ return copy.deepcopy(self)
+
+ def to_zpk(self):
+ """
+ Convert system representation to `ZerosPolesGain`.
+
+ Returns
+ -------
+ sys : instance of `ZerosPolesGain`
+ Zeros, poles, gain representation of the current system
+
+ """
+ return ZerosPolesGain(*tf2zpk(self.num, self.den),
+ **self._dt_dict)
+
+ def to_ss(self):
+ """
+ Convert system representation to `StateSpace`.
+
+ Returns
+ -------
+ sys : instance of `StateSpace`
+ State space model of the current system
+
+ """
+ return StateSpace(*tf2ss(self.num, self.den),
+ **self._dt_dict)
+
+ @staticmethod
+ def _z_to_zinv(num, den):
+ """Change a transfer function from the variable `z` to `z**-1`.
+
+ Parameters
+ ----------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of descending degree of 'z'.
+ That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``.
+
+ Returns
+ -------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of ascending degree of 'z**-1'.
+ That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``.
+ """
+ diff = len(num) - len(den)
+ if diff > 0:
+ den = np.hstack((np.zeros(diff), den))
+ elif diff < 0:
+ num = np.hstack((np.zeros(-diff), num))
+ return num, den
+
+ @staticmethod
+ def _zinv_to_z(num, den):
+ """Change a transfer function from the variable `z` to `z**-1`.
+
+ Parameters
+ ----------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of ascending degree of 'z**-1'.
+ That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``.
+
+ Returns
+ -------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of descending degree of 'z'.
+ That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``.
+ """
+ diff = len(num) - len(den)
+ if diff > 0:
+ den = np.hstack((den, np.zeros(diff)))
+ elif diff < 0:
+ num = np.hstack((num, np.zeros(-diff)))
+ return num, den
+
+
+class TransferFunctionContinuous(TransferFunction, lti):
+ r"""
+ Continuous-time Linear Time Invariant system in transfer function form.
+
+ Represents the system as the transfer function
+ :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j`, where
+ :math:`b` are elements of the numerator `num`, :math:`a` are elements of
+ the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``.
+ Continuous-time `TransferFunction` systems inherit additional
+ functionality from the `lti` class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `TransferFunction` class can be instantiated with 1 or 2
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` system: (`StateSpace`, `TransferFunction` or `ZerosPolesGain`)
+ * 2: array_like: (numerator, denominator)
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, lti
+ tf2ss, tf2zpk, tf2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `TransferFunction` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients
+ for both the numerator and denominator should be specified in descending
+ exponent order (e.g. ``s^2 + 3s + 5`` would be represented as
+ ``[1, 3, 5]``)
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`:
+
+ >>> from scipy import signal
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ >>> signal.TransferFunction(num, den)
+ TransferFunctionContinuous(
+ array([1., 3., 3.]),
+ array([1., 2., 1.]),
+ dt: None
+ )
+
+ """
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """
+ Returns the discretized `TransferFunction` system.
+
+ Parameters
+ ----------
+ dt : float
+ The discretization time step.
+ method : str, optional
+ Which method to use:
+
+ * gbt: generalized bilinear transformation
+ * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
+ * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
+ * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
+ * zoh: zero-order hold (default)
+ * foh: first-order hold
+ * impulse: equivalent impulse response
+
+ alpha : float within [0, 1], optional
+ The generalized bilinear transformation weighting parameter, which
+ should only be specified with method="gbt", and is ignored otherwise
+
+ Returns
+ -------
+ sys: instance of `dlti` and `StateSpace`
+
+ See Also
+ --------
+ cont2discrete
+ """
+ return TransferFunction(*cont2discrete((self.num, self.den),
+ dt,
+ method=method,
+ alpha=alpha)[:-1],
+ dt=dt)
+
+
+class TransferFunctionDiscrete(TransferFunction, dlti):
+ r"""
+ Discrete-time Linear Time Invariant system in transfer function form.
+
+ Represents the system as the transfer function
+ :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where
+ :math:`b` are elements of the numerator `num`, :math:`a` are elements of
+ the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``.
+ Discrete-time `TransferFunction` systems inherit additional functionality
+ from the `dlti` class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `TransferFunction` class can be instantiated with 1 or 2
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `dlti` system: (`StateSpace`, `TransferFunction` or `ZerosPolesGain`)
+ * 2: array_like: (numerator, denominator)
+ dt : float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `True`
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, dlti
+ tf2ss, tf2zpk, tf2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `TransferFunction` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients
+ for both the numerator and denominator should be specified in descending
+ exponent order (e.g., ``z^2 + 3z + 5`` would be represented as
+ ``[1, 3, 5]``).
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of
+ 0.5 seconds:
+
+ >>> from scipy import signal
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ >>> signal.TransferFunction(num, den, dt=0.5)
+ TransferFunctionDiscrete(
+ array([1., 3., 3.]),
+ array([1., 2., 1.]),
+ dt: 0.5
+ )
+
+ """
+ pass
+
+
+class ZerosPolesGain(LinearTimeInvariant):
+ r"""
+ Linear Time Invariant system class in zeros, poles, gain form.
+
+ Represents the system as the continuous- or discrete-time transfer function
+ :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is
+ the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`.
+ `ZerosPolesGain` systems inherit additional functionality from the `lti`,
+ respectively the `dlti` classes, depending on which system representation
+ is used.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `ZerosPolesGain` class can be instantiated with 1 or 3
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 3: array_like: (zeros, poles, gain)
+ dt : float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `None`
+ (continuous-time). Must be specified as a keyword argument, for
+ example, ``dt=0.1``.
+
+
+ See Also
+ --------
+ TransferFunction, StateSpace, lti, dlti
+ zpk2ss, zpk2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> from scipy import signal
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time
+ of 0.1 seconds:
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1)
+ ZerosPolesGainDiscrete(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: 0.1
+ )
+
+ """
+ def __new__(cls, *system, dt=None):
+ """Handle object conversion if input is an instance of `lti`"""
+ if len(system) == 1 and isinstance(system[0], LinearTimeInvariant):
+ return system[0].to_zpk()
+
+ # Choose whether to inherit from `lti` or from `dlti`
+ if cls is ZerosPolesGain:
+ if dt is None:
+ return ZerosPolesGainContinuous.__new__(
+ ZerosPolesGainContinuous,
+ *system)
+ else:
+ return ZerosPolesGainDiscrete.__new__(
+ ZerosPolesGainDiscrete,
+ *system, dt=dt)
+
+ # No special conversion needed
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """Initialize the zeros, poles, gain system."""
+ # Conversion of lti instances is handled in __new__
+ if isinstance(system[0], LinearTimeInvariant):
+ return
+
+ super().__init__(**kwargs)
+
+ self._zeros = None
+ self._poles = None
+ self._gain = None
+
+ self.zeros, self.poles, self.gain = system
+
+ def __repr__(self):
+ """Return representation of the `ZerosPolesGain` system."""
+ return (
+ f'{self.__class__.__name__}(\n'
+ f'{repr(self.zeros)},\n'
+ f'{repr(self.poles)},\n'
+ f'{repr(self.gain)},\n'
+ f'dt: {repr(self.dt)}\n)'
+ )
+
+ @property
+ def zeros(self):
+ """Zeros of the `ZerosPolesGain` system."""
+ return self._zeros
+
+ @zeros.setter
+ def zeros(self, zeros):
+ self._zeros = atleast_1d(zeros)
+
+ # Update dimensions
+ if len(self.zeros.shape) > 1:
+ self.outputs, self.inputs = self.zeros.shape
+ else:
+ self.outputs = 1
+ self.inputs = 1
+
+ @property
+ def poles(self):
+ """Poles of the `ZerosPolesGain` system."""
+ return self._poles
+
+ @poles.setter
+ def poles(self, poles):
+ self._poles = atleast_1d(poles)
+
+ @property
+ def gain(self):
+ """Gain of the `ZerosPolesGain` system."""
+ return self._gain
+
+ @gain.setter
+ def gain(self, gain):
+ self._gain = gain
+
+ def _copy(self, system):
+ """
+ Copy the parameters of another `ZerosPolesGain` system.
+
+ Parameters
+ ----------
+ system : instance of `ZerosPolesGain`
+ The zeros, poles gain system that is to be copied
+
+ """
+ self.poles = system.poles
+ self.zeros = system.zeros
+ self.gain = system.gain
+
+ def to_tf(self):
+ """
+ Convert system representation to `TransferFunction`.
+
+ Returns
+ -------
+ sys : instance of `TransferFunction`
+ Transfer function of the current system
+
+ """
+ return TransferFunction(*zpk2tf(self.zeros, self.poles, self.gain),
+ **self._dt_dict)
+
+ def to_zpk(self):
+ """
+ Return a copy of the current 'ZerosPolesGain' system.
+
+ Returns
+ -------
+ sys : instance of `ZerosPolesGain`
+ The current system (copy)
+
+ """
+ return copy.deepcopy(self)
+
+ def to_ss(self):
+ """
+ Convert system representation to `StateSpace`.
+
+ Returns
+ -------
+ sys : instance of `StateSpace`
+ State space model of the current system
+
+ """
+ return StateSpace(*zpk2ss(self.zeros, self.poles, self.gain),
+ **self._dt_dict)
+
+
+class ZerosPolesGainContinuous(ZerosPolesGain, lti):
+ r"""
+ Continuous-time Linear Time Invariant system in zeros, poles, gain form.
+
+ Represents the system as the continuous time transfer function
+ :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is
+ the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`.
+ Continuous-time `ZerosPolesGain` systems inherit additional functionality
+ from the `lti` class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `ZerosPolesGain` class can be instantiated with 1 or 3
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` system: (`StateSpace`, `TransferFunction` or `ZerosPolesGain`)
+ * 3: array_like: (zeros, poles, gain)
+
+ See Also
+ --------
+ TransferFunction, StateSpace, lti
+ zpk2ss, zpk2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s)=\frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> from scipy import signal
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ """
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """
+ Returns the discretized `ZerosPolesGain` system.
+
+ Parameters
+ ----------
+ dt : float
+ The discretization time step.
+ method : str, optional
+ Which method to use:
+
+ * gbt: generalized bilinear transformation
+ * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
+ * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
+ * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
+ * zoh: zero-order hold (default)
+ * foh: first-order hold
+ * impulse: equivalent impulse response
+
+ alpha : float within [0, 1], optional
+ The generalized bilinear transformation weighting parameter, which
+ should only be specified with method="gbt", and is ignored otherwise
+
+ Returns
+ -------
+ sys: instance of `dlti` and `ZerosPolesGain`
+
+ See Also
+ --------
+ cont2discrete
+ """
+ return ZerosPolesGain(
+ *cont2discrete((self.zeros, self.poles, self.gain),
+ dt,
+ method=method,
+ alpha=alpha)[:-1],
+ dt=dt)
+
+
+class ZerosPolesGainDiscrete(ZerosPolesGain, dlti):
+ r"""
+ Discrete-time Linear Time Invariant system in zeros, poles, gain form.
+
+ Represents the system as the discrete-time transfer function
+ :math:`H(z)=k \prod_i (z - q[i]) / \prod_j (z - p[j])`, where :math:`k` is
+ the `gain`, :math:`q` are the `zeros` and :math:`p` are the `poles`.
+ Discrete-time `ZerosPolesGain` systems inherit additional functionality
+ from the `dlti` class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `ZerosPolesGain` class can be instantiated with 1 or 3
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `dlti` system: (`StateSpace`, `TransferFunction` or `ZerosPolesGain`)
+ * 3: array_like: (zeros, poles, gain)
+ dt : float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `True`
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ TransferFunction, StateSpace, dlti
+ zpk2ss, zpk2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> from scipy import signal
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time
+ of 0.1 seconds:
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1)
+ ZerosPolesGainDiscrete(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: 0.1
+ )
+
+ """
+ pass
+
+
+class StateSpace(LinearTimeInvariant):
+ r"""
+ Linear Time Invariant system in state-space form.
+
+ Represents the system as the continuous-time, first order differential
+ equation :math:`\dot{x} = A x + B u` or the discrete-time difference
+ equation :math:`x[k+1] = A x[k] + B u[k]`. `StateSpace` systems
+ inherit additional functionality from the `lti`, respectively the `dlti`
+ classes, depending on which system representation is used.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `StateSpace` class can be instantiated with 1 or 4 arguments.
+ The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 4: array_like: (A, B, C, D)
+ dt : float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `None`
+ (continuous-time). Must be specified as a keyword argument, for
+ example, ``dt=0.1``.
+
+ See Also
+ --------
+ TransferFunction, ZerosPolesGain, lti, dlti
+ ss2zpk, ss2tf, zpk2sos
+
+ Notes
+ -----
+ If the parameter `system` is a tuple (A, B, C, D) with four state space matrices,
+ then those matrices are converted into two-dimensional arrays of the same dtype
+ by calling `abcd_normalize`. The resulting dtype will be based on NumPy's dtype
+ promotion rules, except in the case where each of `A`, `B`, `C`, and `D` has
+ integer dtype, in which case the resulting dtype will be the default floating point
+ dtype of ``float64``.
+
+ Changing the value of properties that are not part of the
+ `StateSpace` system representation (such as `zeros` or `poles`) is very
+ inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ The :ref:`tutorial_signal_state_space_representation` section of the
+ :ref:`user_guide` presents the corresponding definitions of continuous-time and
+ disrcete time state space systems.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> a = np.array([[0, 1], [0, 0]])
+ >>> b = np.array([[0], [1]])
+ >>> c = np.array([[1, 0]])
+ >>> d = np.array([[0]])
+
+ >>> sys = signal.StateSpace(a, b, c, d)
+ >>> print(sys)
+ StateSpaceContinuous(
+ array([[0., 1.],
+ [0., 0.]]),
+ array([[0.],
+ [1.]]),
+ array([[1., 0.]]),
+ array([[0.]]),
+ dt: None
+ )
+
+ >>> sys.to_discrete(0.1)
+ StateSpaceDiscrete(
+ array([[1. , 0.1],
+ [0. , 1. ]]),
+ array([[0.005],
+ [0.1 ]]),
+ array([[1., 0.]]),
+ array([[0.]]),
+ dt: 0.1
+ )
+
+ >>> a = np.array([[1, 0.1], [0, 1]])
+ >>> b = np.array([[0.005], [0.1]])
+
+ >>> signal.StateSpace(a, b, c, d, dt=0.1)
+ StateSpaceDiscrete(
+ array([[1. , 0.1],
+ [0. , 1. ]]),
+ array([[0.005],
+ [0.1 ]]),
+ array([[1., 0.]]),
+ array([[0.]]),
+ dt: 0.1
+ )
+
+ """
+
+ # Override NumPy binary operations and ufuncs
+ __array_priority__ = 100.0
+ __array_ufunc__ = None
+
+ def __new__(cls, *system, dt=None):
+ """Create new StateSpace object and settle inheritance."""
+ # Handle object conversion if input is an instance of `lti`
+ if len(system) == 1 and isinstance(system[0], LinearTimeInvariant):
+ return system[0].to_ss()
+
+ # Choose whether to inherit from `lti` or from `dlti`
+ if cls is StateSpace:
+ if dt is None:
+ return StateSpaceContinuous.__new__(StateSpaceContinuous,
+ *system)
+ else:
+ return StateSpaceDiscrete.__new__(StateSpaceDiscrete,
+ *system, dt=dt)
+
+ # No special conversion needed
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """Initialize the state space lti/dlti system."""
+ # Conversion of lti instances is handled in __new__
+ if isinstance(system[0], LinearTimeInvariant):
+ return
+
+ # Remove system arguments, not needed by parents anymore
+ super().__init__(**kwargs)
+
+ self._A = None
+ self._B = None
+ self._C = None
+ self._D = None
+
+ # Convert A, B, C, D into 2d arrays of dtype float64 or complex128:
+ self.A, self.B, self.C, self.D = abcd_normalize(*system)
+
+ def __repr__(self):
+ """Return representation of the `StateSpace` system."""
+ return (
+ f'{self.__class__.__name__}(\n'
+ f'{repr(self.A)},\n'
+ f'{repr(self.B)},\n'
+ f'{repr(self.C)},\n'
+ f'{repr(self.D)},\n'
+ f'dt: {repr(self.dt)}\n)'
+ )
+
+ def _check_binop_other(self, other):
+ return isinstance(other, StateSpace | np.ndarray | float | complex |
+ np.number | int)
+
+ def __mul__(self, other):
+ """
+ Post-multiply another system or a scalar
+
+ Handles multiplication of systems in the sense of a frequency domain
+ multiplication. That means, given two systems E1(s) and E2(s), their
+ multiplication, H(s) = E1(s) * E2(s), means that applying H(s) to U(s)
+ is equivalent to first applying E2(s), and then E1(s).
+
+ Notes
+ -----
+ For SISO systems the order of system application does not matter.
+ However, for MIMO systems, where the two systems are matrices, the
+ order above ensures standard Matrix multiplication rules apply.
+ """
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ if isinstance(other, StateSpace):
+ # Disallow mix of discrete and continuous systems.
+ if type(other) is not type(self):
+ return NotImplemented
+
+ if self.dt != other.dt:
+ raise TypeError('Cannot multiply systems with different `dt`.')
+
+ n1 = self.A.shape[0]
+ n2 = other.A.shape[0]
+
+ # Interconnection of systems
+ # x1' = A1 x1 + B1 u1
+ # y1 = C1 x1 + D1 u1
+ # x2' = A2 x2 + B2 y1
+ # y2 = C2 x2 + D2 y1
+ #
+ # Plugging in with u1 = y2 yields
+ # [x1'] [A1 B1*C2 ] [x1] [B1*D2]
+ # [x2'] = [0 A2 ] [x2] + [B2 ] u2
+ # [x1]
+ # y2 = [C1 D1*C2] [x2] + D1*D2 u2
+ a = np.vstack((np.hstack((self.A, np.dot(self.B, other.C))),
+ np.hstack((zeros((n2, n1)), other.A))))
+ b = np.vstack((np.dot(self.B, other.D), other.B))
+ c = np.hstack((self.C, np.dot(self.D, other.C)))
+ d = np.dot(self.D, other.D)
+ else:
+ # Assume that other is a scalar / matrix
+ # For post multiplication the input gets scaled
+ a = self.A
+ b = np.dot(self.B, other)
+ c = self.C
+ d = np.dot(self.D, other)
+
+ common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype)
+ return StateSpace(np.asarray(a, dtype=common_dtype),
+ np.asarray(b, dtype=common_dtype),
+ np.asarray(c, dtype=common_dtype),
+ np.asarray(d, dtype=common_dtype),
+ **self._dt_dict)
+
+ def __rmul__(self, other):
+ """Pre-multiply a scalar or matrix (but not StateSpace)"""
+ if not self._check_binop_other(other) or isinstance(other, StateSpace):
+ return NotImplemented
+
+ # For pre-multiplication only the output gets scaled
+ a = self.A
+ b = self.B
+ c = np.dot(other, self.C)
+ d = np.dot(other, self.D)
+
+ common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype)
+ return StateSpace(np.asarray(a, dtype=common_dtype),
+ np.asarray(b, dtype=common_dtype),
+ np.asarray(c, dtype=common_dtype),
+ np.asarray(d, dtype=common_dtype),
+ **self._dt_dict)
+
+ def __neg__(self):
+ """Negate the system (equivalent to pre-multiplying by -1)."""
+ return StateSpace(self.A, self.B, -self.C, -self.D, **self._dt_dict)
+
+ def __add__(self, other):
+ """
+ Adds two systems in the sense of frequency domain addition.
+ """
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ if isinstance(other, StateSpace):
+ # Disallow mix of discrete and continuous systems.
+ if type(other) is not type(self):
+ raise TypeError(f'Cannot add {type(self)} and {type(other)}')
+
+ if self.dt != other.dt:
+ raise TypeError('Cannot add systems with different `dt`.')
+ # Interconnection of systems
+ # x1' = A1 x1 + B1 u
+ # y1 = C1 x1 + D1 u
+ # x2' = A2 x2 + B2 u
+ # y2 = C2 x2 + D2 u
+ # y = y1 + y2
+ #
+ # Plugging in yields
+ # [x1'] [A1 0 ] [x1] [B1]
+ # [x2'] = [0 A2] [x2] + [B2] u
+ # [x1]
+ # y = [C1 C2] [x2] + [D1 + D2] u
+ a = linalg.block_diag(self.A, other.A)
+ b = np.vstack((self.B, other.B))
+ c = np.hstack((self.C, other.C))
+ d = self.D + other.D
+ else:
+ other = np.atleast_2d(other)
+ if self.D.shape == other.shape:
+ # A scalar/matrix is really just a static system (A=0, B=0, C=0)
+ a = self.A
+ b = self.B
+ c = self.C
+ d = self.D + other
+ else:
+ raise ValueError("Cannot add systems with incompatible "
+ f"dimensions ({self.D.shape} and {other.shape})")
+
+ common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype)
+ return StateSpace(np.asarray(a, dtype=common_dtype),
+ np.asarray(b, dtype=common_dtype),
+ np.asarray(c, dtype=common_dtype),
+ np.asarray(d, dtype=common_dtype),
+ **self._dt_dict)
+
+ def __sub__(self, other):
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ return self.__add__(-other)
+
+ def __radd__(self, other):
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ return self.__add__(other)
+
+ def __rsub__(self, other):
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ return (-self).__add__(other)
+
+ def __truediv__(self, other):
+ """
+ Divide by a scalar
+ """
+ # Division by non-StateSpace scalars
+ if not self._check_binop_other(other) or isinstance(other, StateSpace):
+ return NotImplemented
+
+ if isinstance(other, np.ndarray) and other.ndim > 0:
+ # It's ambiguous what this means, so disallow it
+ raise ValueError("Cannot divide StateSpace by non-scalar numpy arrays")
+
+ return self.__mul__(1/other)
+
+ @property
+ def A(self):
+ """State matrix of the `StateSpace` system."""
+ return self._A
+
+ @A.setter
+ def A(self, A):
+ self._A = np.atleast_2d(A) if A is not None else None
+
+ @property
+ def B(self):
+ """Input matrix of the `StateSpace` system."""
+ return self._B
+
+ @B.setter
+ def B(self, B):
+ self._B = np.atleast_2d(B) if B is not None else None
+ self.inputs = self.B.shape[-1]
+
+ @property
+ def C(self):
+ """Output matrix of the `StateSpace` system."""
+ return self._C
+
+ @C.setter
+ def C(self, C):
+ self._C = np.atleast_2d(C) if C is not None else None
+ self.outputs = self.C.shape[0]
+
+ @property
+ def D(self):
+ """Feedthrough matrix of the `StateSpace` system."""
+ return self._D
+
+ @D.setter
+ def D(self, D):
+ self._D = np.atleast_2d(D) if D is not None else None
+
+ def _copy(self, system):
+ """
+ Copy the parameters of another `StateSpace` system.
+
+ Parameters
+ ----------
+ system : instance of `StateSpace`
+ The state-space system that is to be copied
+
+ """
+ self.A = system.A
+ self.B = system.B
+ self.C = system.C
+ self.D = system.D
+
+ def to_tf(self, **kwargs):
+ """
+ Convert system representation to `TransferFunction`.
+
+ Parameters
+ ----------
+ **kwargs
+ Additional keywords passed to `ss2zpk`
+
+ Returns
+ -------
+ sys : instance of `TransferFunction`
+ Transfer function of the current system
+
+ """
+ return TransferFunction(*ss2tf(self._A, self._B, self._C, self._D,
+ **kwargs), **self._dt_dict)
+
+ def to_zpk(self, **kwargs):
+ """
+ Convert system representation to `ZerosPolesGain`.
+
+ Parameters
+ ----------
+ **kwargs
+ Additional keywords passed to `ss2zpk`
+
+ Returns
+ -------
+ sys : instance of `ZerosPolesGain`
+ Zeros, poles, gain representation of the current system
+
+ """
+ return ZerosPolesGain(*ss2zpk(self._A, self._B, self._C, self._D,
+ **kwargs), **self._dt_dict)
+
+ def to_ss(self):
+ """
+ Return a copy of the current `StateSpace` system.
+
+ Returns
+ -------
+ sys : instance of `StateSpace`
+ The current system (copy)
+
+ """
+ return copy.deepcopy(self)
+
+
+class StateSpaceContinuous(StateSpace, lti):
+ r"""
+ Continuous-time Linear Time Invariant system in state-space form.
+
+ Represents the system as the continuous-time, first order differential
+ equation :math:`\dot{x} = A x + B u`.
+ Continuous-time `StateSpace` systems inherit additional functionality
+ from the `lti` class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `StateSpace` class can be instantiated with 1 or 3 arguments.
+ The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` system: (`StateSpace`, `TransferFunction` or `ZerosPolesGain`)
+ * 4: array_like: (A, B, C, D)
+
+ See Also
+ --------
+ TransferFunction, ZerosPolesGain, lti
+ ss2zpk, ss2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `StateSpace` system representation (such as `zeros` or `poles`) is very
+ inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+
+ >>> a = np.array([[0, 1], [0, 0]])
+ >>> b = np.array([[0], [1]])
+ >>> c = np.array([[1, 0]])
+ >>> d = np.array([[0]])
+
+ >>> sys = signal.StateSpace(a, b, c, d)
+ >>> print(sys)
+ StateSpaceContinuous(
+ array([[0., 1.],
+ [0., 0.]]),
+ array([[0.],
+ [1.]]),
+ array([[1., 0.]]),
+ array([[0.]]),
+ dt: None
+ )
+
+ """
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """
+ Returns the discretized `StateSpace` system.
+
+ Parameters
+ ----------
+ dt : float
+ The discretization time step.
+ method : str, optional
+ Which method to use:
+
+ * gbt: generalized bilinear transformation
+ * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
+ * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
+ * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
+ * zoh: zero-order hold (default)
+ * foh: first-order hold
+ * impulse: equivalent impulse response
+
+ alpha : float within [0, 1], optional
+ The generalized bilinear transformation weighting parameter, which
+ should only be specified with method="gbt", and is ignored otherwise
+
+ Returns
+ -------
+ sys: instance of `dlti` and `StateSpace`
+
+ See Also
+ --------
+ cont2discrete
+ """
+ return StateSpace(*cont2discrete((self.A, self.B, self.C, self.D),
+ dt,
+ method=method,
+ alpha=alpha)[:-1],
+ dt=dt)
+
+
+class StateSpaceDiscrete(StateSpace, dlti):
+ r"""
+ Discrete-time Linear Time Invariant system in state-space form.
+
+ Represents the system as the discrete-time difference equation
+ :math:`x[k+1] = A x[k] + B u[k]`.
+ `StateSpace` systems inherit additional functionality from the `dlti`
+ class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `StateSpace` class can be instantiated with 1 or 3 arguments.
+ The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `dlti` system: (`StateSpace`, `TransferFunction` or `ZerosPolesGain`)
+ * 4: array_like: (A, B, C, D)
+ dt : float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `True`
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ TransferFunction, ZerosPolesGain, dlti
+ ss2zpk, ss2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `StateSpace` system representation (such as `zeros` or `poles`) is very
+ inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+
+ >>> a = np.array([[1, 0.1], [0, 1]])
+ >>> b = np.array([[0.005], [0.1]])
+ >>> c = np.array([[1, 0]])
+ >>> d = np.array([[0]])
+
+ >>> signal.StateSpace(a, b, c, d, dt=0.1)
+ StateSpaceDiscrete(
+ array([[1. , 0.1],
+ [0. , 1. ]]),
+ array([[0.005],
+ [0.1 ]]),
+ array([[1., 0.]]),
+ array([[0.]]),
+ dt: 0.1
+ )
+
+ """
+ pass
+
+
+def lsim(system, U, T, X0=None, interp=True):
+ """
+ Simulate output of a continuous-time linear system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple describing the system
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1: (instance of `lti`)
+ * 2: (num, den)
+ * 3: (zeros, poles, gain)
+ * 4: (A, B, C, D)
+
+ U : array_like
+ An input array describing the input at each time `T`
+ (interpolation is assumed between given times). If there are
+ multiple inputs, then each column of the rank-2 array
+ represents an input. If U = 0 or None, a zero input is used.
+ T : array_like
+ The time steps at which the input is defined and at which the
+ output is desired. Must be nonnegative, increasing, and equally spaced.
+ X0 : array_like, optional
+ The initial conditions on the state vector (zero by default).
+ interp : bool, optional
+ Whether to use linear (True, the default) or zero-order-hold (False)
+ interpolation for the input array.
+
+ Returns
+ -------
+ T : 1D ndarray
+ Time values for the output.
+ yout : 1D ndarray
+ System response.
+ xout : ndarray
+ Time evolution of the state vector.
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ We'll use `lsim` to simulate an analog Bessel filter applied to
+ a signal.
+
+ >>> import numpy as np
+ >>> from scipy.signal import bessel, lsim
+ >>> import matplotlib.pyplot as plt
+
+ Create a low-pass Bessel filter with a cutoff of 12 Hz.
+
+ >>> b, a = bessel(N=5, Wn=2*np.pi*12, btype='lowpass', analog=True)
+
+ Generate data to which the filter is applied.
+
+ >>> t = np.linspace(0, 1.25, 500, endpoint=False)
+
+ The input signal is the sum of three sinusoidal curves, with
+ frequencies 4 Hz, 40 Hz, and 80 Hz. The filter should mostly
+ eliminate the 40 Hz and 80 Hz components, leaving just the 4 Hz signal.
+
+ >>> u = (np.cos(2*np.pi*4*t) + 0.6*np.sin(2*np.pi*40*t) +
+ ... 0.5*np.cos(2*np.pi*80*t))
+
+ Simulate the filter with `lsim`.
+
+ >>> tout, yout, xout = lsim((b, a), U=u, T=t)
+
+ Plot the result.
+
+ >>> plt.plot(t, u, 'r', alpha=0.5, linewidth=1, label='input')
+ >>> plt.plot(tout, yout, 'k', linewidth=1.5, label='output')
+ >>> plt.legend(loc='best', shadow=True, framealpha=1)
+ >>> plt.grid(alpha=0.3)
+ >>> plt.xlabel('t')
+ >>> plt.show()
+
+ In a second example, we simulate a double integrator ``y'' = u``, with
+ a constant input ``u = 1``. We'll use the state space representation
+ of the integrator.
+
+ >>> from scipy.signal import lti
+ >>> A = np.array([[0.0, 1.0], [0.0, 0.0]])
+ >>> B = np.array([[0.0], [1.0]])
+ >>> C = np.array([[1.0, 0.0]])
+ >>> D = 0.0
+ >>> system = lti(A, B, C, D)
+
+ `t` and `u` define the time and input signal for the system to
+ be simulated.
+
+ >>> t = np.linspace(0, 5, num=50)
+ >>> u = np.ones_like(t)
+
+ Compute the simulation, and then plot `y`. As expected, the plot shows
+ the curve ``y = 0.5*t**2``.
+
+ >>> tout, y, x = lsim(system, u, t)
+ >>> plt.plot(t, y)
+ >>> plt.grid(alpha=0.3)
+ >>> plt.xlabel('t')
+ >>> plt.show()
+
+ """
+ if isinstance(system, lti):
+ sys = system._as_ss()
+ elif isinstance(system, dlti):
+ raise AttributeError('lsim can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_ss()
+ T = atleast_1d(T)
+ if len(T.shape) != 1:
+ raise ValueError("T must be a rank-1 array.")
+
+ A, B, C, D = map(np.asarray, (sys.A, sys.B, sys.C, sys.D))
+ n_states = A.shape[0]
+ n_inputs = B.shape[1]
+
+ n_steps = T.size
+ if X0 is None:
+ X0 = zeros(n_states, sys.A.dtype)
+ xout = np.empty((n_steps, n_states), sys.A.dtype)
+
+ if T[0] == 0:
+ xout[0] = X0
+ elif T[0] > 0:
+ # step forward to initial time, with zero input
+ xout[0] = dot(X0, linalg.expm(transpose(A) * T[0]))
+ else:
+ raise ValueError("Initial time must be nonnegative")
+
+ no_input = (U is None or
+ (isinstance(U, int | float) and U == 0.) or
+ not np.any(U))
+
+ if n_steps == 1:
+ yout = squeeze(xout @ C.T)
+ if not no_input:
+ yout += squeeze(U @ D.T)
+ return T, yout, squeeze(xout)
+
+ dt = T[1] - T[0]
+ if not np.allclose(np.diff(T), dt):
+ raise ValueError("Time steps are not equally spaced.")
+
+ if no_input:
+ # Zero input: just use matrix exponential
+ # take transpose because state is a row vector
+ expAT_dt = linalg.expm(A.T * dt)
+ for i in range(1, n_steps):
+ xout[i] = xout[i-1] @ expAT_dt
+ yout = squeeze(xout @ C.T)
+ return T, yout, squeeze(xout)
+
+ # Nonzero input
+ U = atleast_1d(U)
+ if U.ndim == 1:
+ U = U[:, np.newaxis]
+
+ if U.shape[0] != n_steps:
+ raise ValueError("U must have the same number of rows "
+ "as elements in T.")
+
+ if U.shape[1] != n_inputs:
+ raise ValueError("System does not define that many inputs.")
+
+ if not interp:
+ # Zero-order hold
+ # Algorithm: to integrate from time 0 to time dt, we solve
+ # xdot = A x + B u, x(0) = x0
+ # udot = 0, u(0) = u0.
+ #
+ # Solution is
+ # [ x(dt) ] [ A*dt B*dt ] [ x0 ]
+ # [ u(dt) ] = exp [ 0 0 ] [ u0 ]
+ M = np.vstack([np.hstack([A * dt, B * dt]),
+ np.zeros((n_inputs, n_states + n_inputs))])
+ # transpose everything because the state and input are row vectors
+ expMT = linalg.expm(M.T)
+ Ad = expMT[:n_states, :n_states]
+ Bd = expMT[n_states:, :n_states]
+ for i in range(1, n_steps):
+ xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd
+ else:
+ # Linear interpolation between steps
+ # Algorithm: to integrate from time 0 to time dt, with linear
+ # interpolation between inputs u(0) = u0 and u(dt) = u1, we solve
+ # xdot = A x + B u, x(0) = x0
+ # udot = (u1 - u0) / dt, u(0) = u0.
+ #
+ # Solution is
+ # [ x(dt) ] [ A*dt B*dt 0 ] [ x0 ]
+ # [ u(dt) ] = exp [ 0 0 I ] [ u0 ]
+ # [u1 - u0] [ 0 0 0 ] [u1 - u0]
+ M = np.vstack([np.hstack([A * dt, B * dt,
+ np.zeros((n_states, n_inputs))]),
+ np.hstack([np.zeros((n_inputs, n_states + n_inputs)),
+ np.identity(n_inputs)]),
+ np.zeros((n_inputs, n_states + 2 * n_inputs))])
+ expMT = linalg.expm(M.T)
+ Ad = expMT[:n_states, :n_states]
+ Bd1 = expMT[n_states+n_inputs:, :n_states]
+ Bd0 = expMT[n_states:n_states + n_inputs, :n_states] - Bd1
+ for i in range(1, n_steps):
+ xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd0 + U[i] @ Bd1
+
+ yout = squeeze(xout @ C.T) + squeeze(U @ D.T)
+ return T, yout, squeeze(xout)
+
+
+def _default_response_times(A, n):
+ """Compute a reasonable set of time samples for the response time.
+
+ This function is used by `impulse` and `step` to compute the response time
+ when the `T` argument to the function is None.
+
+ Parameters
+ ----------
+ A : array_like
+ The system matrix, which is square.
+ n : int
+ The number of time samples to generate.
+
+ Returns
+ -------
+ t : ndarray
+ The 1-D array of length `n` of time samples at which the response
+ is to be computed.
+ """
+ # Create a reasonable time interval.
+ # TODO: This could use some more work.
+ # For example, what is expected when the system is unstable?
+ vals = linalg.eigvals(A)
+ r = min(abs(real(vals)))
+ if r == 0.0:
+ r = 1.0
+ tc = 1.0 / r
+ t = linspace(0.0, 7 * tc, n)
+ return t
+
+
+def impulse(system, X0=None, T=None, N=None):
+ """Impulse response of continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple of array_like
+ describing the system.
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ X0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ T : array_like, optional
+ Time points. Computed if not given.
+ N : int, optional
+ The number of time points to compute (if `T` is not given).
+
+ Returns
+ -------
+ T : ndarray
+ A 1-D array of time points.
+ yout : ndarray
+ A 1-D array containing the impulse response of the system (except for
+ singularities at zero).
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ Compute the impulse response of a second order system with a repeated
+ root: ``x''(t) + 2*x'(t) + x(t) = u(t)``
+
+ >>> from scipy import signal
+ >>> system = ([1.0], [1.0, 2.0, 1.0])
+ >>> t, y = signal.impulse(system)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(t, y)
+
+ """
+ if isinstance(system, lti):
+ sys = system._as_ss()
+ elif isinstance(system, dlti):
+ raise AttributeError('impulse can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_ss()
+ if X0 is None:
+ X = squeeze(sys.B)
+ else:
+ X = squeeze(sys.B + X0)
+ if N is None:
+ N = 100
+ if T is None:
+ T = _default_response_times(sys.A, N)
+ else:
+ T = asarray(T)
+
+ _, h, _ = lsim(sys, 0., T, X, interp=False)
+ return T, h
+
+
+def step(system, X0=None, T=None, N=None):
+ """Step response of continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple of array_like
+ describing the system.
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ X0 : array_like, optional
+ Initial state-vector (default is zero).
+ T : array_like, optional
+ Time points (computed if not given).
+ N : int, optional
+ Number of time points to compute if `T` is not given.
+
+ Returns
+ -------
+ T : 1D ndarray
+ Output time points.
+ yout : 1D ndarray
+ Step response of system.
+
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> lti = signal.lti([1.0], [1.0, 1.0])
+ >>> t, y = signal.step(lti)
+ >>> plt.plot(t, y)
+ >>> plt.xlabel('Time [s]')
+ >>> plt.ylabel('Amplitude')
+ >>> plt.title('Step response for 1. Order Lowpass')
+ >>> plt.grid()
+
+ """
+ if isinstance(system, lti):
+ sys = system._as_ss()
+ elif isinstance(system, dlti):
+ raise AttributeError('step can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_ss()
+ if N is None:
+ N = 100
+ if T is None:
+ T = _default_response_times(sys.A, N)
+ else:
+ T = asarray(T)
+ U = ones(T.shape, sys.A.dtype)
+ vals = lsim(sys, U, T, X0=X0, interp=False)
+ return vals[0], vals[1]
+
+
+def bode(system, w=None, n=100):
+ """
+ Calculate Bode magnitude and phase data of a continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple describing the system
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ w : array_like, optional
+ Array of frequencies (in rad/s). Magnitude and phase data is calculated
+ for every value in this array. If not given a reasonable set will be
+ calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [rad/s]
+ mag : 1D ndarray
+ Magnitude array [dB]
+ phase : 1D ndarray
+ Phase array [deg]
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> sys = signal.TransferFunction([1], [1, 1])
+ >>> w, mag, phase = signal.bode(sys)
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, mag) # Bode magnitude plot
+ >>> plt.figure()
+ >>> plt.semilogx(w, phase) # Bode phase plot
+ >>> plt.show()
+
+ """
+ w, y = freqresp(system, w=w, n=n)
+
+ mag = 20.0 * np.log10(abs(y))
+ phase = np.unwrap(np.arctan2(y.imag, y.real)) * 180.0 / np.pi
+
+ return w, mag, phase
+
+
+def freqresp(system, w=None, n=10000):
+ r"""Calculate the frequency response of a continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the `lti` class or a tuple describing the system
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ w : array_like, optional
+ Array of frequencies (in rad/s). Magnitude and phase data is
+ calculated for every value in this array. If not given, a reasonable
+ set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [rad/s]
+ H : 1D ndarray
+ Array of complex magnitude values
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ Generating the Nyquist plot of a transfer function
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ Construct the transfer function :math:`H(s) = \frac{5}{(s-1)^3}`:
+
+ >>> s1 = signal.ZerosPolesGain([], [1, 1, 1], [5])
+
+ >>> w, H = signal.freqresp(s1)
+
+ >>> plt.figure()
+ >>> plt.plot(H.real, H.imag, "b")
+ >>> plt.plot(H.real, -H.imag, "r")
+ >>> plt.show()
+ """
+ if isinstance(system, lti):
+ if isinstance(system, TransferFunction | ZerosPolesGain):
+ sys = system
+ else:
+ sys = system._as_zpk()
+ elif isinstance(system, dlti):
+ raise AttributeError('freqresp can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_zpk()
+
+ if sys.inputs != 1 or sys.outputs != 1:
+ raise ValueError("freqresp() requires a SISO (single input, single "
+ "output) system.")
+
+ if w is not None:
+ worN = w
+ else:
+ worN = n
+
+ if isinstance(sys, TransferFunction):
+ # In the call to freqs(), sys.num.ravel() is used because there are
+ # cases where sys.num is a 2-D array with a single row.
+ w, h = freqs(sys.num.ravel(), sys.den, worN=worN)
+
+ elif isinstance(sys, ZerosPolesGain):
+ w, h = freqs_zpk(sys.zeros, sys.poles, sys.gain, worN=worN)
+
+ return w, h
+
+
+# This class will be used by place_poles to return its results
+# see https://code.activestate.com/recipes/52308/
+class Bunch:
+ def __init__(self, **kwds):
+ self.__dict__.update(kwds)
+
+
+def _valid_inputs(A, B, poles, method, rtol, maxiter):
+ """
+ Check the poles come in complex conjugate pairs
+ Check shapes of A, B and poles are compatible.
+ Check the method chosen is compatible with provided poles
+ Return update method to use and ordered poles
+
+ """
+ poles = np.asarray(poles)
+ if poles.ndim > 1:
+ raise ValueError("Poles must be a 1D array like.")
+ # Will raise ValueError if poles do not come in complex conjugates pairs
+ poles = _order_complex_poles(poles)
+ if A.ndim > 2:
+ raise ValueError("A must be a 2D array/matrix.")
+ if B.ndim > 2:
+ raise ValueError("B must be a 2D array/matrix")
+ if A.shape[0] != A.shape[1]:
+ raise ValueError("A must be square")
+ if len(poles) > A.shape[0]:
+ raise ValueError(
+ f"maximum number of poles is {A.shape[0]} but you asked for {len(poles)}"
+ )
+ if len(poles) < A.shape[0]:
+ raise ValueError(
+ f"number of poles is {len(poles)} but you should provide {A.shape[0]}"
+ )
+ r = np.linalg.matrix_rank(B)
+ for p in poles:
+ if sum(p == poles) > r:
+ raise ValueError("at least one of the requested pole is repeated "
+ "more than rank(B) times")
+ # Choose update method
+ update_loop = _YT_loop
+ if method not in ('KNV0','YT'):
+ raise ValueError("The method keyword must be one of 'YT' or 'KNV0'")
+
+ if method == "KNV0":
+ update_loop = _KNV0_loop
+ if not all(np.isreal(poles)):
+ raise ValueError("Complex poles are not supported by KNV0")
+
+ if maxiter < 1:
+ raise ValueError("maxiter must be at least equal to 1")
+
+ # We do not check rtol <= 0 as the user can use a negative rtol to
+ # force maxiter iterations
+ if rtol > 1:
+ raise ValueError("rtol can not be greater than 1")
+
+ return update_loop, poles
+
+
+def _order_complex_poles(poles):
+ """
+ Check we have complex conjugates pairs and reorder P according to YT, ie
+ real_poles, complex_i, conjugate complex_i, ....
+ The lexicographic sort on the complex poles is added to help the user to
+ compare sets of poles.
+ """
+ ordered_poles = np.sort(poles[np.isreal(poles)])
+ im_poles = []
+ for p in np.sort(poles[np.imag(poles) < 0]):
+ if np.conj(p) in poles:
+ im_poles.extend((p, np.conj(p)))
+
+ ordered_poles = np.hstack((ordered_poles, im_poles))
+
+ if poles.shape[0] != len(ordered_poles):
+ raise ValueError("Complex poles must come with their conjugates")
+ return ordered_poles
+
+
+def _KNV0(B, ker_pole, transfer_matrix, j, poles):
+ """
+ Algorithm "KNV0" Kautsky et Al. Robust pole
+ assignment in linear state feedback, Int journal of Control
+ 1985, vol 41 p 1129->1155
+ https://la.epfl.ch/files/content/sites/la/files/
+ users/105941/public/KautskyNicholsDooren
+
+ """
+ # Remove xj form the base
+ transfer_matrix_not_j = np.delete(transfer_matrix, j, axis=1)
+ # If we QR this matrix in full mode Q=Q0|Q1
+ # then Q1 will be a single column orthogonal to
+ # Q0, that's what we are looking for !
+
+ # After merge of gh-4249 great speed improvements could be achieved
+ # using QR updates instead of full QR in the line below
+
+ # To debug with numpy qr uncomment the line below
+ # Q, R = np.linalg.qr(transfer_matrix_not_j, mode="complete")
+ Q, R = s_qr(transfer_matrix_not_j, mode="full")
+
+ mat_ker_pj = np.dot(ker_pole[j], ker_pole[j].T)
+ yj = np.dot(mat_ker_pj, Q[:, -1])
+
+ # If Q[:, -1] is "almost" orthogonal to ker_pole[j] its
+ # projection into ker_pole[j] will yield a vector
+ # close to 0. As we are looking for a vector in ker_pole[j]
+ # simply stick with transfer_matrix[:, j] (unless someone provides me with
+ # a better choice ?)
+
+ if not np.allclose(yj, 0):
+ xj = yj/np.linalg.norm(yj)
+ transfer_matrix[:, j] = xj
+
+ # KNV does not support complex poles, using YT technique the two lines
+ # below seem to work 9 out of 10 times but it is not reliable enough:
+ # transfer_matrix[:, j]=real(xj)
+ # transfer_matrix[:, j+1]=imag(xj)
+
+ # Add this at the beginning of this function if you wish to test
+ # complex support:
+ # if ~np.isreal(P[j]) and (j>=B.shape[0]-1 or P[j]!=np.conj(P[j+1])):
+ # return
+ # Problems arise when imag(xj)=>0 I have no idea on how to fix this
+
+
+def _YT_real(ker_pole, Q, transfer_matrix, i, j):
+ """
+ Applies algorithm from YT section 6.1 page 19 related to real pairs
+ """
+ # step 1 page 19
+ u = Q[:, -2, np.newaxis]
+ v = Q[:, -1, np.newaxis]
+
+ # step 2 page 19
+ m = np.dot(np.dot(ker_pole[i].T, np.dot(u, v.T) -
+ np.dot(v, u.T)), ker_pole[j])
+
+ # step 3 page 19
+ um, sm, vm = np.linalg.svd(m)
+ # mu1, mu2 two first columns of U => 2 first lines of U.T
+ mu1, mu2 = um.T[:2, :, np.newaxis]
+ # VM is V.T with numpy we want the first two lines of V.T
+ nu1, nu2 = vm[:2, :, np.newaxis]
+
+ # what follows is a rough python translation of the formulas
+ # in section 6.2 page 20 (step 4)
+ transfer_matrix_j_mo_transfer_matrix_j = np.vstack((
+ transfer_matrix[:, i, np.newaxis],
+ transfer_matrix[:, j, np.newaxis]))
+
+ if not np.allclose(sm[0], sm[1]):
+ ker_pole_imo_mu1 = np.dot(ker_pole[i], mu1)
+ ker_pole_i_nu1 = np.dot(ker_pole[j], nu1)
+ ker_pole_mu_nu = np.vstack((ker_pole_imo_mu1, ker_pole_i_nu1))
+ else:
+ ker_pole_ij = np.vstack((
+ np.hstack((ker_pole[i],
+ np.zeros(ker_pole[i].shape))),
+ np.hstack((np.zeros(ker_pole[j].shape),
+ ker_pole[j]))
+ ))
+ mu_nu_matrix = np.vstack(
+ (np.hstack((mu1, mu2)), np.hstack((nu1, nu2)))
+ )
+ ker_pole_mu_nu = np.dot(ker_pole_ij, mu_nu_matrix)
+ transfer_matrix_ij = np.dot(np.dot(ker_pole_mu_nu, ker_pole_mu_nu.T),
+ transfer_matrix_j_mo_transfer_matrix_j)
+ if not np.allclose(transfer_matrix_ij, 0):
+ transfer_matrix_ij = (np.sqrt(2)*transfer_matrix_ij /
+ np.linalg.norm(transfer_matrix_ij))
+ transfer_matrix[:, i] = transfer_matrix_ij[
+ :transfer_matrix[:, i].shape[0], 0
+ ]
+ transfer_matrix[:, j] = transfer_matrix_ij[
+ transfer_matrix[:, i].shape[0]:, 0
+ ]
+ else:
+ # As in knv0 if transfer_matrix_j_mo_transfer_matrix_j is orthogonal to
+ # Vect{ker_pole_mu_nu} assign transfer_matrixi/transfer_matrix_j to
+ # ker_pole_mu_nu and iterate. As we are looking for a vector in
+ # Vect{Matker_pole_MU_NU} (see section 6.1 page 19) this might help
+ # (that's a guess, not a claim !)
+ transfer_matrix[:, i] = ker_pole_mu_nu[
+ :transfer_matrix[:, i].shape[0], 0
+ ]
+ transfer_matrix[:, j] = ker_pole_mu_nu[
+ transfer_matrix[:, i].shape[0]:, 0
+ ]
+
+
+def _YT_complex(ker_pole, Q, transfer_matrix, i, j):
+ """
+ Applies algorithm from YT section 6.2 page 20 related to complex pairs
+ """
+ # step 1 page 20
+ ur = np.sqrt(2)*Q[:, -2, np.newaxis]
+ ui = np.sqrt(2)*Q[:, -1, np.newaxis]
+ u = ur + 1j*ui
+
+ # step 2 page 20
+ ker_pole_ij = ker_pole[i]
+ m = np.dot(np.dot(np.conj(ker_pole_ij.T), np.dot(u, np.conj(u).T) -
+ np.dot(np.conj(u), u.T)), ker_pole_ij)
+
+ # step 3 page 20
+ e_val, e_vec = np.linalg.eig(m)
+ # sort eigenvalues according to their module
+ e_val_idx = np.argsort(np.abs(e_val))
+ mu1 = e_vec[:, e_val_idx[-1], np.newaxis]
+ mu2 = e_vec[:, e_val_idx[-2], np.newaxis]
+
+ # what follows is a rough python translation of the formulas
+ # in section 6.2 page 20 (step 4)
+
+ # remember transfer_matrix_i has been split as
+ # transfer_matrix[i]=real(transfer_matrix_i) and
+ # transfer_matrix[j]=imag(transfer_matrix_i)
+ transfer_matrix_j_mo_transfer_matrix_j = (
+ transfer_matrix[:, i, np.newaxis] +
+ 1j*transfer_matrix[:, j, np.newaxis]
+ )
+ if not np.allclose(np.abs(e_val[e_val_idx[-1]]),
+ np.abs(e_val[e_val_idx[-2]])):
+ ker_pole_mu = np.dot(ker_pole_ij, mu1)
+ else:
+ mu1_mu2_matrix = np.hstack((mu1, mu2))
+ ker_pole_mu = np.dot(ker_pole_ij, mu1_mu2_matrix)
+ transfer_matrix_i_j = np.dot(np.dot(ker_pole_mu, np.conj(ker_pole_mu.T)),
+ transfer_matrix_j_mo_transfer_matrix_j)
+
+ if not np.allclose(transfer_matrix_i_j, 0):
+ transfer_matrix_i_j = (transfer_matrix_i_j /
+ np.linalg.norm(transfer_matrix_i_j))
+ transfer_matrix[:, i] = np.real(transfer_matrix_i_j[:, 0])
+ transfer_matrix[:, j] = np.imag(transfer_matrix_i_j[:, 0])
+ else:
+ # same idea as in YT_real
+ transfer_matrix[:, i] = np.real(ker_pole_mu[:, 0])
+ transfer_matrix[:, j] = np.imag(ker_pole_mu[:, 0])
+
+
+def _YT_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol):
+ """
+ Algorithm "YT" Tits, Yang. Globally Convergent
+ Algorithms for Robust Pole Assignment by State Feedback
+ https://hdl.handle.net/1903/5598
+ The poles P have to be sorted accordingly to section 6.2 page 20
+
+ """
+ # The IEEE edition of the YT paper gives useful information on the
+ # optimal update order for the real poles in order to minimize the number
+ # of times we have to loop over all poles, see page 1442
+ nb_real = poles[np.isreal(poles)].shape[0]
+ # hnb => Half Nb Real
+ hnb = nb_real // 2
+
+ # Stick to the indices in the paper and then remove one to get numpy array
+ # index it is a bit easier to link the code to the paper this way even if it
+ # is not very clean. The paper is unclear about what should be done when
+ # there is only one real pole => use KNV0 on this real pole seem to work
+ if nb_real > 0:
+ #update the biggest real pole with the smallest one
+ update_order = [[nb_real], [1]]
+ else:
+ update_order = [[],[]]
+
+ r_comp = np.arange(nb_real+1, len(poles)+1, 2)
+ # step 1.a
+ r_p = np.arange(1, hnb+nb_real % 2)
+ update_order[0].extend(2*r_p)
+ update_order[1].extend(2*r_p+1)
+ # step 1.b
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 1.c
+ r_p = np.arange(1, hnb+1)
+ update_order[0].extend(2*r_p-1)
+ update_order[1].extend(2*r_p)
+ # step 1.d
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 2.a
+ r_j = np.arange(2, hnb+nb_real % 2)
+ for j in r_j:
+ for i in range(1, hnb+1):
+ update_order[0].append(i)
+ update_order[1].append(i+j)
+ # step 2.b
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 2.c
+ r_j = np.arange(2, hnb+nb_real % 2)
+ for j in r_j:
+ for i in range(hnb+1, nb_real+1):
+ idx_1 = i+j
+ if idx_1 > nb_real:
+ idx_1 = i+j-nb_real
+ update_order[0].append(i)
+ update_order[1].append(idx_1)
+ # step 2.d
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 3.a
+ for i in range(1, hnb+1):
+ update_order[0].append(i)
+ update_order[1].append(i+hnb)
+ # step 3.b
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+
+ update_order = np.array(update_order).T-1
+ stop = False
+ nb_try = 0
+ while nb_try < maxiter and not stop:
+ det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix))
+ for i, j in update_order:
+ if i == j:
+ assert i == 0, "i!=0 for KNV call in YT"
+ assert np.isreal(poles[i]), "calling KNV on a complex pole"
+ _KNV0(B, ker_pole, transfer_matrix, i, poles)
+ else:
+ transfer_matrix_not_i_j = np.delete(transfer_matrix, (i, j),
+ axis=1)
+ # after merge of gh-4249 great speed improvements could be
+ # achieved using QR updates instead of full QR in the line below
+
+ #to debug with numpy qr uncomment the line below
+ #Q, _ = np.linalg.qr(transfer_matrix_not_i_j, mode="complete")
+ Q, _ = s_qr(transfer_matrix_not_i_j, mode="full")
+
+ if np.isreal(poles[i]):
+ assert np.isreal(poles[j]), "mixing real and complex " + \
+ "in YT_real" + str(poles)
+ _YT_real(ker_pole, Q, transfer_matrix, i, j)
+ else:
+ assert ~np.isreal(poles[i]), "mixing real and complex " + \
+ "in YT_real" + str(poles)
+ _YT_complex(ker_pole, Q, transfer_matrix, i, j)
+
+ det_transfer_matrix = np.max((np.sqrt(np.spacing(1)),
+ np.abs(np.linalg.det(transfer_matrix))))
+ cur_rtol = np.abs(
+ (det_transfer_matrix -
+ det_transfer_matrixb) /
+ det_transfer_matrix)
+ if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)):
+ # Convergence test from YT page 21
+ stop = True
+ nb_try += 1
+ return stop, cur_rtol, nb_try
+
+
+def _KNV0_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol):
+ """
+ Loop over all poles one by one and apply KNV method 0 algorithm
+ """
+ # This method is useful only because we need to be able to call
+ # _KNV0 from YT without looping over all poles, otherwise it would
+ # have been fine to mix _KNV0_loop and _KNV0 in a single function
+ stop = False
+ nb_try = 0
+ while nb_try < maxiter and not stop:
+ det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix))
+ for j in range(B.shape[0]):
+ _KNV0(B, ker_pole, transfer_matrix, j, poles)
+
+ det_transfer_matrix = np.max((np.sqrt(np.spacing(1)),
+ np.abs(np.linalg.det(transfer_matrix))))
+ cur_rtol = np.abs((det_transfer_matrix - det_transfer_matrixb) /
+ det_transfer_matrix)
+ if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)):
+ # Convergence test from YT page 21
+ stop = True
+
+ nb_try += 1
+ return stop, cur_rtol, nb_try
+
+
+def place_poles(A, B, poles, method="YT", rtol=1e-3, maxiter=30):
+ """
+ Compute K such that eigenvalues (A - dot(B, K))=poles.
+
+ K is the gain matrix such as the plant described by the linear system
+ ``AX+BU`` will have its closed-loop poles, i.e the eigenvalues ``A - B*K``,
+ as close as possible to those asked for in poles.
+
+ SISO, MISO and MIMO systems are supported.
+
+ Parameters
+ ----------
+ A, B : ndarray
+ State-space representation of linear system ``AX + BU``.
+ poles : array_like
+ Desired real poles and/or complex conjugates poles.
+ Complex poles are only supported with ``method="YT"`` (default).
+ method : {'YT', 'KNV0'}, optional
+ Which method to choose to find the gain matrix K. One of:
+
+ - 'YT': Yang Tits
+ - 'KNV0': Kautsky, Nichols, Van Dooren update method 0
+
+ See References and Notes for details on the algorithms.
+ rtol : float, optional
+ After each iteration the determinant of the eigenvectors of
+ ``A - B*K`` is compared to its previous value, when the relative
+ error between these two values becomes lower than `rtol` the algorithm
+ stops. Default is 1e-3.
+ maxiter : int, optional
+ Maximum number of iterations to compute the gain matrix.
+ Default is 30.
+
+ Returns
+ -------
+ full_state_feedback : Bunch object
+ full_state_feedback is composed of:
+ gain_matrix : 2-D ndarray
+ The closed loop matrix K such as the eigenvalues of ``A-BK``
+ are as close as possible to the requested poles.
+ computed_poles : 1-D ndarray
+ The poles corresponding to ``A-BK`` sorted as first the real
+ poles in increasing order, then the complex conjugates in
+ lexicographic order.
+ requested_poles : 1-D ndarray
+ The poles the algorithm was asked to place sorted as above,
+ they may differ from what was achieved.
+ X : 2-D ndarray
+ The transfer matrix such as ``X * diag(poles) = (A - B*K)*X``
+ (see Notes)
+ rtol : float
+ The relative tolerance achieved on ``det(X)`` (see Notes).
+ `rtol` will be NaN if it is possible to solve the system
+ ``diag(poles) = (A - B*K)``, or 0 when the optimization
+ algorithms can't do anything i.e when ``B.shape[1] == 1``.
+ nb_iter : int
+ The number of iterations performed before converging.
+ `nb_iter` will be NaN if it is possible to solve the system
+ ``diag(poles) = (A - B*K)``, or 0 when the optimization
+ algorithms can't do anything i.e when ``B.shape[1] == 1``.
+
+ Notes
+ -----
+ The Tits and Yang (YT), [2]_ paper is an update of the original Kautsky et
+ al. (KNV) paper [1]_. KNV relies on rank-1 updates to find the transfer
+ matrix X such that ``X * diag(poles) = (A - B*K)*X``, whereas YT uses
+ rank-2 updates. This yields on average more robust solutions (see [2]_
+ pp 21-22), furthermore the YT algorithm supports complex poles whereas KNV
+ does not in its original version. Only update method 0 proposed by KNV has
+ been implemented here, hence the name ``'KNV0'``.
+
+ KNV extended to complex poles is used in Matlab's ``place`` function, YT is
+ distributed under a non-free licence by Slicot under the name ``robpole``.
+ It is unclear and undocumented how KNV0 has been extended to complex poles
+ (Tits and Yang claim on page 14 of their paper that their method can not be
+ used to extend KNV to complex poles), therefore only YT supports them in
+ this implementation.
+
+ As the solution to the problem of pole placement is not unique for MIMO
+ systems, both methods start with a tentative transfer matrix which is
+ altered in various way to increase its determinant. Both methods have been
+ proven to converge to a stable solution, however depending on the way the
+ initial transfer matrix is chosen they will converge to different
+ solutions and therefore there is absolutely no guarantee that using
+ ``'KNV0'`` will yield results similar to Matlab's or any other
+ implementation of these algorithms.
+
+ Using the default method ``'YT'`` should be fine in most cases; ``'KNV0'``
+ is only provided because it is needed by ``'YT'`` in some specific cases.
+ Furthermore ``'YT'`` gives on average more robust results than ``'KNV0'``
+ when ``abs(det(X))`` is used as a robustness indicator.
+
+ [2]_ is available as a technical report on the following URL:
+ https://hdl.handle.net/1903/5598
+
+ References
+ ----------
+ .. [1] J. Kautsky, N.K. Nichols and P. van Dooren, "Robust pole assignment
+ in linear state feedback", International Journal of Control, Vol. 41
+ pp. 1129-1155, 1985.
+ .. [2] A.L. Tits and Y. Yang, "Globally convergent algorithms for robust
+ pole assignment by state feedback", IEEE Transactions on Automatic
+ Control, Vol. 41, pp. 1432-1452, 1996.
+
+ Examples
+ --------
+ A simple example demonstrating real pole placement using both KNV and YT
+ algorithms. This is example number 1 from section 4 of the reference KNV
+ publication ([1]_):
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> A = np.array([[ 1.380, -0.2077, 6.715, -5.676 ],
+ ... [-0.5814, -4.290, 0, 0.6750 ],
+ ... [ 1.067, 4.273, -6.654, 5.893 ],
+ ... [ 0.0480, 4.273, 1.343, -2.104 ]])
+ >>> B = np.array([[ 0, 5.679 ],
+ ... [ 1.136, 1.136 ],
+ ... [ 0, 0, ],
+ ... [-3.146, 0 ]])
+ >>> P = np.array([-0.2, -0.5, -5.0566, -8.6659])
+
+ Now compute K with KNV method 0, with the default YT method and with the YT
+ method while forcing 100 iterations of the algorithm and print some results
+ after each call.
+
+ >>> fsf1 = signal.place_poles(A, B, P, method='KNV0')
+ >>> fsf1.gain_matrix
+ array([[ 0.20071427, -0.96665799, 0.24066128, -0.10279785],
+ [ 0.50587268, 0.57779091, 0.51795763, -0.41991442]])
+
+ >>> fsf2 = signal.place_poles(A, B, P) # uses YT method
+ >>> fsf2.computed_poles
+ array([-8.6659, -5.0566, -0.5 , -0.2 ]) # may vary
+
+ >>> fsf3 = signal.place_poles(A, B, P, rtol=-1, maxiter=100)
+ >>> fsf3.X
+ array([[ 0.52072442+0.j, -0.08409372+0.j, -0.56847937+0.j, 0.74823657+0.j],
+ [-0.04977751+0.j, -0.80872954+0.j, 0.13566234+0.j, -0.29322906+0.j],
+ [-0.82266932+0.j, -0.19168026+0.j, -0.56348322+0.j, -0.43815060+0.j],
+ [ 0.22267347+0.j, 0.54967577+0.j, -0.58387806+0.j, -0.40271926+0.j]])
+
+ The absolute value of the determinant of X is a good indicator to check the
+ robustness of the results, both ``'KNV0'`` and ``'YT'`` aim at maximizing
+ it. Below a comparison of the robustness of the results above:
+
+ >>> abs(np.linalg.det(fsf1.X)) < abs(np.linalg.det(fsf2.X))
+ True
+ >>> abs(np.linalg.det(fsf2.X)) < abs(np.linalg.det(fsf3.X))
+ True
+
+ Now a simple example for complex poles:
+
+ >>> A = np.array([[ 0, 7/3., 0, 0 ],
+ ... [ 0, 0, 0, 7/9. ],
+ ... [ 0, 0, 0, 0 ],
+ ... [ 0, 0, 0, 0 ]])
+ >>> B = np.array([[ 0, 0 ],
+ ... [ 0, 0 ],
+ ... [ 1, 0 ],
+ ... [ 0, 1 ]])
+ >>> P = np.array([-3, -1, -2-1j, -2+1j]) / 3.
+ >>> fsf = signal.place_poles(A, B, P, method='YT')
+
+ We can plot the desired and computed poles in the complex plane:
+
+ >>> t = np.linspace(0, 2*np.pi, 401)
+ >>> plt.plot(np.cos(t), np.sin(t), 'k--') # unit circle
+ >>> plt.plot(fsf.requested_poles.real, fsf.requested_poles.imag,
+ ... 'wo', label='Desired')
+ >>> plt.plot(fsf.computed_poles.real, fsf.computed_poles.imag, 'bx',
+ ... label='Placed')
+ >>> plt.grid()
+ >>> plt.axis('image')
+ >>> plt.axis([-1.1, 1.1, -1.1, 1.1])
+ >>> plt.legend(bbox_to_anchor=(1.05, 1), loc=2, numpoints=1)
+
+ """
+ # Move away all the inputs checking, it only adds noise to the code
+ update_loop, poles = _valid_inputs(A, B, poles, method, rtol, maxiter)
+
+ # The current value of the relative tolerance we achieved
+ cur_rtol = 0
+ # The number of iterations needed before converging
+ nb_iter = 0
+
+ # Step A: QR decomposition of B page 1132 KN
+ # to debug with numpy qr uncomment the line below
+ # u, z = np.linalg.qr(B, mode="complete")
+ u, z = s_qr(B, mode="full")
+ rankB = np.linalg.matrix_rank(B)
+ u0 = u[:, :rankB]
+ u1 = u[:, rankB:]
+ z = z[:rankB, :]
+
+ # If we can use the identity matrix as X the solution is obvious
+ if B.shape[0] == rankB:
+ # if B is square and full rank there is only one solution
+ # such as (A+BK)=inv(X)*diag(P)*X with X=eye(A.shape[0])
+ # i.e K=inv(B)*(diag(P)-A)
+ # if B has as many lines as its rank (but not square) there are many
+ # solutions and we can choose one using least squares
+ # => use lstsq in both cases.
+ # In both cases the transfer matrix X will be eye(A.shape[0]) and I
+ # can hardly think of a better one so there is nothing to optimize
+ #
+ # for complex poles we use the following trick
+ #
+ # |a -b| has for eigenvalues a+b and a-b
+ # |b a|
+ #
+ # |a+bi 0| has the obvious eigenvalues a+bi and a-bi
+ # |0 a-bi|
+ #
+ # e.g solving the first one in R gives the solution
+ # for the second one in C
+ diag_poles = np.zeros(A.shape)
+ idx = 0
+ while idx < poles.shape[0]:
+ p = poles[idx]
+ diag_poles[idx, idx] = np.real(p)
+ if ~np.isreal(p):
+ diag_poles[idx, idx+1] = -np.imag(p)
+ diag_poles[idx+1, idx+1] = np.real(p)
+ diag_poles[idx+1, idx] = np.imag(p)
+ idx += 1 # skip next one
+ idx += 1
+ gain_matrix = np.linalg.lstsq(B, diag_poles-A, rcond=-1)[0]
+ transfer_matrix = np.eye(A.shape[0])
+ cur_rtol = np.nan
+ nb_iter = np.nan
+ else:
+ # step A (p1144 KNV) and beginning of step F: decompose
+ # dot(U1.T, A-P[i]*I).T and build our set of transfer_matrix vectors
+ # in the same loop
+ ker_pole = []
+
+ # flag to skip the conjugate of a complex pole
+ skip_conjugate = False
+ # select orthonormal base ker_pole for each Pole and vectors for
+ # transfer_matrix
+ for j in range(B.shape[0]):
+ if skip_conjugate:
+ skip_conjugate = False
+ continue
+ pole_space_j = np.dot(u1.T, A-poles[j]*np.eye(B.shape[0])).T
+
+ # after QR Q=Q0|Q1
+ # only Q0 is used to reconstruct the qr'ed (dot Q, R) matrix.
+ # Q1 is orthogonal to Q0 and will be multiplied by the zeros in
+ # R when using mode "complete". In default mode Q1 and the zeros
+ # in R are not computed
+
+ # To debug with numpy qr uncomment the line below
+ # Q, _ = np.linalg.qr(pole_space_j, mode="complete")
+ Q, _ = s_qr(pole_space_j, mode="full")
+
+ ker_pole_j = Q[:, pole_space_j.shape[1]:]
+
+ # We want to select one vector in ker_pole_j to build the transfer
+ # matrix, however qr returns sometimes vectors with zeros on the
+ # same line for each pole and this yields very long convergence
+ # times.
+ # Or some other times a set of vectors, one with zero imaginary
+ # part and one (or several) with imaginary parts. After trying
+ # many ways to select the best possible one (eg ditch vectors
+ # with zero imaginary part for complex poles) I ended up summing
+ # all vectors in ker_pole_j, this solves 100% of the problems and
+ # is a valid choice for transfer_matrix.
+ # This way for complex poles we are sure to have a non zero
+ # imaginary part that way, and the problem of lines full of zeros
+ # in transfer_matrix is solved too as when a vector from
+ # ker_pole_j has a zero the other one(s) when
+ # ker_pole_j.shape[1]>1) for sure won't have a zero there.
+
+ transfer_matrix_j = np.sum(ker_pole_j, axis=1)[:, np.newaxis]
+ transfer_matrix_j = (transfer_matrix_j /
+ np.linalg.norm(transfer_matrix_j))
+ if ~np.isreal(poles[j]): # complex pole
+ transfer_matrix_j = np.hstack([np.real(transfer_matrix_j),
+ np.imag(transfer_matrix_j)])
+ ker_pole.extend([ker_pole_j, ker_pole_j])
+
+ # Skip next pole as it is the conjugate
+ skip_conjugate = True
+ else: # real pole, nothing to do
+ ker_pole.append(ker_pole_j)
+
+ if j == 0:
+ transfer_matrix = transfer_matrix_j
+ else:
+ transfer_matrix = np.hstack((transfer_matrix, transfer_matrix_j))
+
+ if rankB > 1: # otherwise there is nothing we can optimize
+ stop, cur_rtol, nb_iter = update_loop(ker_pole, transfer_matrix,
+ poles, B, maxiter, rtol)
+ if not stop and rtol > 0:
+ # if rtol<=0 the user has probably done that on purpose,
+ # don't annoy them
+ err_msg = (
+ "Convergence was not reached after maxiter iterations.\n"
+ f"You asked for a tolerance of {rtol}, we got {cur_rtol}."
+ )
+ warnings.warn(err_msg, stacklevel=2)
+
+ # reconstruct transfer_matrix to match complex conjugate pairs,
+ # ie transfer_matrix_j/transfer_matrix_j+1 are
+ # Re(Complex_pole), Im(Complex_pole) now and will be Re-Im/Re+Im after
+ transfer_matrix = transfer_matrix.astype(complex)
+ idx = 0
+ while idx < poles.shape[0]-1:
+ if ~np.isreal(poles[idx]):
+ rel = transfer_matrix[:, idx].copy()
+ img = transfer_matrix[:, idx+1]
+ # rel will be an array referencing a column of transfer_matrix
+ # if we don't copy() it will changer after the next line and
+ # and the line after will not yield the correct value
+ transfer_matrix[:, idx] = rel-1j*img
+ transfer_matrix[:, idx+1] = rel+1j*img
+ idx += 1 # skip next one
+ idx += 1
+
+ try:
+ m = np.linalg.solve(transfer_matrix.T, np.dot(np.diag(poles),
+ transfer_matrix.T)).T
+ gain_matrix = np.linalg.solve(z, np.dot(u0.T, m-A))
+ except np.linalg.LinAlgError as e:
+ raise ValueError("The poles you've chosen can't be placed. "
+ "Check the controllability matrix and try "
+ "another set of poles") from e
+
+ # Beware: Kautsky solves A+BK but the usual form is A-BK
+ gain_matrix = -gain_matrix
+ # K still contains complex with ~=0j imaginary parts, get rid of them
+ gain_matrix = np.real(gain_matrix)
+
+ full_state_feedback = Bunch()
+ full_state_feedback.gain_matrix = gain_matrix
+ full_state_feedback.computed_poles = _order_complex_poles(
+ np.linalg.eig(A - np.dot(B, gain_matrix))[0]
+ )
+ full_state_feedback.requested_poles = poles
+ full_state_feedback.X = transfer_matrix
+ full_state_feedback.rtol = cur_rtol
+ full_state_feedback.nb_iter = nb_iter
+
+ return full_state_feedback
+
+
+def dlsim(system, u, t=None, x0=None):
+ r"""Simulate output of a discrete-time linear system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+
+ u : array_like
+ An input array describing the input at each time `t` (interpolation is
+ assumed between given times). If there are multiple inputs, then each
+ column of the rank-2 array represents an input.
+ t : array_like, optional
+ The time steps at which the input is defined. If `t` is given, it
+ must be the same length as `u`, and the final value in `t` determines
+ the number of steps returned in the output.
+ x0 : array_like, optional
+ The initial conditions on the state vector (zero by default).
+
+ Returns
+ -------
+ tout : ndarray
+ Time values for the output, as a 1-D array.
+ yout : ndarray
+ System response, as a 1-D array.
+ xout : ndarray, optional
+ Time-evolution of the state-vector. Only generated if the input is a
+ `StateSpace` system.
+
+ See Also
+ --------
+ lsim, dstep, dimpulse, cont2discrete
+
+ Examples
+ --------
+ A simple integrator transfer function with a discrete time step of 1.0
+ could be implemented as:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> tf = ([1.0,], [1.0, -1.0], 1.0)
+ >>> t_in = [0.0, 1.0, 2.0, 3.0]
+ >>> u = np.asarray([0.0, 0.0, 1.0, 1.0])
+ >>> t_out, y = signal.dlsim(tf, u, t=t_in)
+ >>> y.T
+ array([[ 0., 0., 0., 1.]])
+
+ """
+ # Convert system to dlti-StateSpace
+ if isinstance(system, lti):
+ raise AttributeError('dlsim can only be used with discrete-time dlti '
+ 'systems.')
+ elif not isinstance(system, dlti):
+ system = dlti(*system[:-1], dt=system[-1])
+
+ # Condition needed to ensure output remains compatible
+ is_ss_input = isinstance(system, StateSpace)
+ system = system._as_ss()
+
+ u = np.atleast_1d(u)
+
+ if u.ndim == 1:
+ u = np.atleast_2d(u).T
+
+ if t is None:
+ out_samples = len(u)
+ stoptime = (out_samples - 1) * system.dt
+ else:
+ stoptime = t[-1]
+ out_samples = int(np.floor(stoptime / system.dt)) + 1
+
+ # Pre-build output arrays
+ xout = np.zeros((out_samples, system.A.shape[0]))
+ yout = np.zeros((out_samples, system.C.shape[0]))
+ tout = np.linspace(0.0, stoptime, num=out_samples)
+
+ # Check initial condition
+ if x0 is None:
+ xout[0, :] = np.zeros((system.A.shape[1],))
+ else:
+ xout[0, :] = np.asarray(x0)
+
+ # Pre-interpolate inputs into the desired time steps
+ if t is None:
+ u_dt = u
+ else:
+ if len(u.shape) == 1:
+ u = u[:, np.newaxis]
+
+ u_dt = make_interp_spline(t, u, k=1)(tout)
+
+ # Simulate the system
+ for i in range(0, out_samples - 1):
+ xout[i+1, :] = (np.dot(system.A, xout[i, :]) +
+ np.dot(system.B, u_dt[i, :]))
+ yout[i, :] = (np.dot(system.C, xout[i, :]) +
+ np.dot(system.D, u_dt[i, :]))
+
+ # Last point
+ yout[out_samples-1, :] = (np.dot(system.C, xout[out_samples-1, :]) +
+ np.dot(system.D, u_dt[out_samples-1, :]))
+
+ if is_ss_input:
+ return tout, yout, xout
+ else:
+ return tout, yout
+
+
+def dimpulse(system, x0=None, t=None, n=None):
+ r"""Impulse response of discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ x0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ t : array_like, optional
+ Time points. Computed if not given.
+ n : int, optional
+ The number of time points to compute (if `t` is not given).
+
+ Returns
+ -------
+ tout : ndarray
+ Time values for the output, as a 1-D array.
+ yout : tuple of ndarray
+ Impulse response of system. Each element of the tuple represents
+ the output of the system based on an impulse in each input.
+
+ See Also
+ --------
+ impulse, dstep, dlsim, cont2discrete
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ ...
+ >>> dt = 1 # sampling interval is one => time unit is sample number
+ >>> bb, aa = signal.butter(3, 0.25, fs=1/dt)
+ >>> t, y = signal.dimpulse((bb, aa, dt), n=25)
+ ...
+ >>> fig0, ax0 = plt.subplots()
+ >>> ax0.step(t, np.squeeze(y), '.-', where='post')
+ >>> ax0.set_title(r"Impulse Response of a $3^\text{rd}$ Order Butterworth Filter")
+ >>> ax0.set(xlabel='Sample number', ylabel='Amplitude')
+ >>> ax0.grid()
+ >>> plt.show()
+ """
+ # Convert system to dlti-StateSpace
+ if isinstance(system, dlti):
+ system = system._as_ss()
+ elif isinstance(system, lti):
+ raise AttributeError('dimpulse can only be used with discrete-time '
+ 'dlti systems.')
+ else:
+ system = dlti(*system[:-1], dt=system[-1])._as_ss()
+
+ # Default to 100 samples if unspecified
+ if n is None:
+ n = 100
+
+ # If time is not specified, use the number of samples
+ # and system dt
+ if t is None:
+ t = np.linspace(0, n * system.dt, n, endpoint=False)
+ else:
+ t = np.asarray(t)
+
+ # For each input, implement a step change
+ yout = None
+ for i in range(0, system.inputs):
+ u = np.zeros((t.shape[0], system.inputs))
+ u[0, i] = 1.0
+
+ one_output = dlsim(system, u, t=t, x0=x0)
+
+ if yout is None:
+ yout = (one_output[1],)
+ else:
+ yout = yout + (one_output[1],)
+
+ tout = one_output[0]
+
+ return tout, yout
+
+
+def dstep(system, x0=None, t=None, n=None):
+ r"""Step response of discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ x0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ t : array_like, optional
+ Time points. Computed if not given.
+ n : int, optional
+ The number of time points to compute (if `t` is not given).
+
+ Returns
+ -------
+ tout : ndarray
+ Output time points, as a 1-D array.
+ yout : tuple of ndarray
+ Step response of system. Each element of the tuple represents
+ the output of the system based on a step response to each input.
+
+ See Also
+ --------
+ step, dimpulse, dlsim, cont2discrete
+
+ Examples
+ --------
+ The following example illustrates how to create a digital Butterworth filer and
+ plot its step response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ ...
+ >>> dt = 1 # sampling interval is one => time unit is sample number
+ >>> bb, aa = signal.butter(3, 0.25, fs=1/dt)
+ >>> t, y = signal.dstep((bb, aa, dt), n=25)
+ ...
+ >>> fig0, ax0 = plt.subplots()
+ >>> ax0.step(t, np.squeeze(y), '.-', where='post')
+ >>> ax0.set_title(r"Step Response of a $3^\text{rd}$ Order Butterworth Filter")
+ >>> ax0.set(xlabel='Sample number', ylabel='Amplitude', ylim=(0, 1.1*np.max(y)))
+ >>> ax0.grid()
+ >>> plt.show()
+ """
+ # Convert system to dlti-StateSpace
+ if isinstance(system, dlti):
+ system = system._as_ss()
+ elif isinstance(system, lti):
+ raise AttributeError('dstep can only be used with discrete-time dlti '
+ 'systems.')
+ else:
+ system = dlti(*system[:-1], dt=system[-1])._as_ss()
+
+ # Default to 100 samples if unspecified
+ if n is None:
+ n = 100
+
+ # If time is not specified, use the number of samples
+ # and system dt
+ if t is None:
+ t = np.linspace(0, n * system.dt, n, endpoint=False)
+ else:
+ t = np.asarray(t)
+
+ # For each input, implement a step change
+ yout = None
+ for i in range(0, system.inputs):
+ u = np.zeros((t.shape[0], system.inputs))
+ u[:, i] = np.ones((t.shape[0],))
+
+ one_output = dlsim(system, u, t=t, x0=x0)
+
+ if yout is None:
+ yout = (one_output[1],)
+ else:
+ yout = yout + (one_output[1],)
+
+ tout = one_output[0]
+
+ return tout, yout
+
+
+def dfreqresp(system, w=None, n=10000, whole=False):
+ r"""
+ Calculate the frequency response of a discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ w : array_like, optional
+ Array of frequencies (in radians/sample). Magnitude and phase data is
+ calculated for every value in this array. If not given a reasonable
+ set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+ whole : bool, optional
+ Normally, if 'w' is not given, frequencies are computed from 0 to the
+ Nyquist frequency, pi radians/sample (upper-half of unit-circle). If
+ `whole` is True, compute frequencies from 0 to 2*pi radians/sample.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [radians/sample]
+ H : 1D ndarray
+ Array of complex magnitude values
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``z^2 + 3z + 5`` would be represented as ``[1, 3, 5]``).
+
+ .. versionadded:: 0.18.0
+
+ Examples
+ --------
+ The following example generates the Nyquist plot of the transfer function
+ :math:`H(z) = \frac{1}{z^2 + 2z + 3}` with a sampling time of 0.05 seconds:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.05) # construct H(z)
+ >>> w, H = signal.dfreqresp(sys)
+ ...
+ >>> fig0, ax0 = plt.subplots()
+ >>> ax0.plot(H.real, H.imag, label=r"$H(z=e^{+j\omega})$")
+ >>> ax0.plot(H.real, -H.imag, label=r"$H(z=e^{-j\omega})$")
+ >>> ax0.set_title(r"Nyquist Plot of $H(z) = 1 / (z^2 + 2z + 3)$")
+ >>> ax0.set(xlabel=r"$\text{Re}\{z\}$", ylabel=r"$\text{Im}\{z\}$",
+ ... xlim=(-0.2, 0.65), aspect='equal')
+ >>> ax0.plot(H[0].real, H[0].imag, 'k.') # mark H(exp(1j*w[0]))
+ >>> ax0.text(0.2, 0, r"$H(e^{j0})$")
+ >>> ax0.grid(True)
+ >>> ax0.legend()
+ >>> plt.show()
+ """
+ if not isinstance(system, dlti):
+ if isinstance(system, lti):
+ raise AttributeError('dfreqresp can only be used with '
+ 'discrete-time systems.')
+
+ system = dlti(*system[:-1], dt=system[-1])
+
+ if isinstance(system, StateSpace):
+ # No SS->ZPK code exists right now, just SS->TF->ZPK
+ system = system._as_tf()
+
+ if not isinstance(system, TransferFunction | ZerosPolesGain):
+ raise ValueError('Unknown system type')
+
+ if system.inputs != 1 or system.outputs != 1:
+ raise ValueError("dfreqresp requires a SISO (single input, single "
+ "output) system.")
+
+ if w is not None:
+ worN = w
+ else:
+ worN = n
+
+ if isinstance(system, TransferFunction):
+ # Convert numerator and denominator from polynomials in the variable
+ # 'z' to polynomials in the variable 'z^-1', as freqz expects.
+ num, den = TransferFunction._z_to_zinv(system.num.ravel(), system.den)
+ w, h = freqz(num, den, worN=worN, whole=whole)
+
+ elif isinstance(system, ZerosPolesGain):
+ w, h = freqz_zpk(system.zeros, system.poles, system.gain, worN=worN,
+ whole=whole)
+
+ return w, h
+
+
+def dbode(system, w=None, n=100):
+ r"""Calculate Bode magnitude and phase data of a discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ w : array_like, optional
+ Array of frequencies normalized to the Nyquist frequency being π, i.e.,
+ having unit radiant / sample. Magnitude and phase data is calculated for every
+ value in this array. If not given, a reasonable set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Array of frequencies normalized to the Nyquist frequency being ``np.pi/dt``
+ with ``dt`` being the sampling interval of the `system` parameter.
+ The unit is rad/s assuming ``dt`` is in seconds.
+ mag : 1D ndarray
+ Magnitude array in dB
+ phase : 1D ndarray
+ Phase array in degrees
+
+ Notes
+ -----
+ This function is a convenience wrapper around `dfreqresp` for extracting
+ magnitude and phase from the calculated complex-valued amplitude of the
+ frequency response.
+
+ .. versionadded:: 0.18.0
+
+ See Also
+ --------
+ dfreqresp, dlti, TransferFunction, ZerosPolesGain, StateSpace
+
+
+ Examples
+ --------
+ The following example shows how to create a Bode plot of a 5-th order
+ Butterworth lowpass filter with a corner frequency of 100 Hz:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy import signal
+ ...
+ >>> T = 1e-4 # sampling interval in s
+ >>> f_c, o = 1e2, 5 # corner frequency in Hz (i.e., -3 dB value) and filter order
+ >>> bb, aa = signal.butter(o, f_c, 'lowpass', fs=1/T)
+ ...
+ >>> w, mag, phase = signal.dbode((bb, aa, T))
+ >>> w /= 2*np.pi # convert unit of frequency into Hertz
+ ...
+ >>> fg, (ax0, ax1) = plt.subplots(2, 1, sharex='all', figsize=(5, 4),
+ ... tight_layout=True)
+ >>> ax0.set_title("Bode Plot of Butterworth Lowpass Filter " +
+ ... rf"($f_c={f_c:g}\,$Hz, order={o})")
+ >>> ax0.set_ylabel(r"Magnitude in dB")
+ >>> ax1.set(ylabel=r"Phase in Degrees",
+ ... xlabel="Frequency $f$ in Hertz", xlim=(w[1], w[-1]))
+ >>> ax0.semilogx(w, mag, 'C0-', label=r"$20\,\log_{10}|G(f)|$") # Magnitude plot
+ >>> ax1.semilogx(w, phase, 'C1-', label=r"$\angle G(f)$") # Phase plot
+ ...
+ >>> for ax_ in (ax0, ax1):
+ ... ax_.axvline(f_c, color='m', alpha=0.25, label=rf"${f_c=:g}\,$Hz")
+ ... ax_.grid(which='both', axis='x') # plot major & minor vertical grid lines
+ ... ax_.grid(which='major', axis='y')
+ ... ax_.legend()
+ >>> plt.show()
+ """
+ w, y = dfreqresp(system, w=w, n=n)
+
+ if isinstance(system, dlti):
+ dt = system.dt
+ else:
+ dt = system[-1]
+
+ mag = 20.0 * np.log10(abs(y))
+ phase = np.rad2deg(np.unwrap(np.angle(y)))
+
+ return w / dt, mag, phase
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_max_len_seq.py b/.venv/lib/python3.12/site-packages/scipy/signal/_max_len_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d64beaca86d1da50b563668679b6fc52c954ab0
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_max_len_seq.py
@@ -0,0 +1,139 @@
+# Author: Eric Larson
+# 2014
+
+"""Tools for MLS generation"""
+
+import numpy as np
+
+from ._max_len_seq_inner import _max_len_seq_inner
+
+__all__ = ['max_len_seq']
+
+
+# These are definitions of linear shift register taps for use in max_len_seq()
+_mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1],
+ 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8],
+ 14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14],
+ 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21],
+ 23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20],
+ 27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7],
+ 31: [28], 32: [31, 30, 10]}
+
+def max_len_seq(nbits, state=None, length=None, taps=None):
+ """
+ Maximum length sequence (MLS) generator.
+
+ Parameters
+ ----------
+ nbits : int
+ Number of bits to use. Length of the resulting sequence will
+ be ``(2**nbits) - 1``. Note that generating long sequences
+ (e.g., greater than ``nbits == 16``) can take a long time.
+ state : array_like, optional
+ If array, must be of length ``nbits``, and will be cast to binary
+ (bool) representation. If None, a seed of ones will be used,
+ producing a repeatable representation. If ``state`` is all
+ zeros, an error is raised as this is invalid. Default: None.
+ length : int, optional
+ Number of samples to compute. If None, the entire length
+ ``(2**nbits) - 1`` is computed.
+ taps : array_like, optional
+ Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence).
+ If None, taps will be automatically selected (for up to
+ ``nbits == 32``).
+
+ Returns
+ -------
+ seq : array
+ Resulting MLS sequence of 0's and 1's.
+ state : array
+ The final state of the shift register.
+
+ Notes
+ -----
+ The algorithm for MLS generation is generically described in:
+
+ https://en.wikipedia.org/wiki/Maximum_length_sequence
+
+ The default values for taps are specifically taken from the first
+ option listed for each value of ``nbits`` in:
+
+ https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm
+
+ .. versionadded:: 0.15.0
+
+ Examples
+ --------
+ MLS uses binary convention:
+
+ >>> from scipy.signal import max_len_seq
+ >>> max_len_seq(4)[0]
+ array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8)
+
+ MLS has a white spectrum (except for DC):
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from numpy.fft import fft, ifft, fftshift, fftfreq
+ >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1
+ >>> spec = fft(seq)
+ >>> N = len(seq)
+ >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-')
+ >>> plt.margins(0.1, 0.1)
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ Circular autocorrelation of MLS is an impulse:
+
+ >>> acorrcirc = ifft(spec * np.conj(spec)).real
+ >>> plt.figure()
+ >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-')
+ >>> plt.margins(0.1, 0.1)
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ Linear autocorrelation of MLS is approximately an impulse:
+
+ >>> acorr = np.correlate(seq, seq, 'full')
+ >>> plt.figure()
+ >>> plt.plot(np.arange(-N+1, N), acorr, '.-')
+ >>> plt.margins(0.1, 0.1)
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ taps_dtype = np.int32 if np.intp().itemsize == 4 else np.int64
+ if taps is None:
+ if nbits not in _mls_taps:
+ known_taps = np.array(list(_mls_taps.keys()))
+ raise ValueError(f'nbits must be between {known_taps.min()} and '
+ f'{known_taps.max()} if taps is None')
+ taps = np.array(_mls_taps[nbits], taps_dtype)
+ else:
+ taps = np.unique(np.array(taps, taps_dtype))[::-1]
+ if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1:
+ raise ValueError('taps must be non-empty with values between '
+ 'zero and nbits (inclusive)')
+ taps = np.array(taps) # needed for Cython and Pythran
+ n_max = (2**nbits) - 1
+ if length is None:
+ length = n_max
+ else:
+ length = int(length)
+ if length < 0:
+ raise ValueError('length must be greater than or equal to 0')
+ # We use int8 instead of bool here because NumPy arrays of bools
+ # don't seem to work nicely with Cython
+ if state is None:
+ state = np.ones(nbits, dtype=np.int8, order='c')
+ else:
+ # makes a copy if need be, ensuring it's 0's and 1's
+ state = np.array(state, dtype=bool, order='c').astype(np.int8)
+ if state.ndim != 1 or state.size != nbits:
+ raise ValueError('state must be a 1-D array of size nbits')
+ if np.all(state == 0):
+ raise ValueError('state must not be all zeros')
+
+ seq = np.empty(length, dtype=np.int8, order='c')
+ state = _max_len_seq_inner(taps, state, nbits, length, seq)
+ return seq, state
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_max_len_seq_inner.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/signal/_max_len_seq_inner.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..6f6aa95716f432b8e963f6e329faf865f85561f0
Binary files /dev/null and b/.venv/lib/python3.12/site-packages/scipy/signal/_max_len_seq_inner.cpython-312-x86_64-linux-gnu.so differ
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_peak_finding.py b/.venv/lib/python3.12/site-packages/scipy/signal/_peak_finding.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5fe546756dfebddd831de936a110ad05eab2d2b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_peak_finding.py
@@ -0,0 +1,1307 @@
+"""
+Functions for identifying peaks in signals.
+"""
+import math
+import numpy as np
+
+from scipy.signal._wavelets import _cwt, _ricker
+from scipy.stats import scoreatpercentile
+
+from ._peak_finding_utils import (
+ _local_maxima_1d,
+ _select_by_peak_distance,
+ _peak_prominences,
+ _peak_widths
+)
+
+
+__all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences',
+ 'peak_widths', 'find_peaks', 'find_peaks_cwt']
+
+
+def _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative extrema of `data`.
+
+ Relative extrema are calculated by finding locations where
+ ``comparator(data[n], data[n+1:n+order+1])`` is True.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative extrema.
+ comparator : callable
+ Function to use to compare two data points.
+ Should take two arrays as arguments.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n,n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated. 'wrap' (wrap around) or
+ 'clip' (treat overflow as the same as the last (or first) element).
+ Default 'clip'. See numpy.take.
+
+ Returns
+ -------
+ extrema : ndarray
+ Boolean array of the same shape as `data` that is True at an extrema,
+ False otherwise.
+
+ See Also
+ --------
+ argrelmax, argrelmin
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._peak_finding import _boolrelextrema
+ >>> testdata = np.array([1,2,3,2,1])
+ >>> _boolrelextrema(testdata, np.greater, axis=0)
+ array([False, False, True, False, False], dtype=bool)
+
+ """
+ if (int(order) != order) or (order < 1):
+ raise ValueError('Order must be an int >= 1')
+
+ datalen = data.shape[axis]
+ locs = np.arange(0, datalen)
+
+ results = np.ones(data.shape, dtype=bool)
+ main = data.take(locs, axis=axis, mode=mode)
+ for shift in range(1, order + 1):
+ plus = data.take(locs + shift, axis=axis, mode=mode)
+ minus = data.take(locs - shift, axis=axis, mode=mode)
+ results &= comparator(main, plus)
+ results &= comparator(main, minus)
+ if ~results.any():
+ return results
+ return results
+
+
+def argrelmin(data, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative minima of `data`.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative minima.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n, n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated.
+ Available options are 'wrap' (wrap around) or 'clip' (treat overflow
+ as the same as the last (or first) element).
+ Default 'clip'. See numpy.take.
+
+ Returns
+ -------
+ extrema : tuple of ndarrays
+ Indices of the minima in arrays of integers. ``extrema[k]`` is
+ the array of indices of axis `k` of `data`. Note that the
+ return value is a tuple even when `data` is 1-D.
+
+ See Also
+ --------
+ argrelextrema, argrelmax, find_peaks
+
+ Notes
+ -----
+ This function uses `argrelextrema` with np.less as comparator. Therefore, it
+ requires a strict inequality on both sides of a value to consider it a
+ minimum. This means flat minima (more than one sample wide) are not detected.
+ In case of 1-D `data` `find_peaks` can be used to detect all
+ local minima, including flat ones, by calling it with negated `data`.
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import argrelmin
+ >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
+ >>> argrelmin(x)
+ (array([1, 5]),)
+ >>> y = np.array([[1, 2, 1, 2],
+ ... [2, 2, 0, 0],
+ ... [5, 3, 4, 4]])
+ ...
+ >>> argrelmin(y, axis=1)
+ (array([0, 2]), array([2, 1]))
+
+ """
+ return argrelextrema(data, np.less, axis, order, mode)
+
+
+def argrelmax(data, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative maxima of `data`.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative maxima.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n, n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated.
+ Available options are 'wrap' (wrap around) or 'clip' (treat overflow
+ as the same as the last (or first) element).
+ Default 'clip'. See `numpy.take`.
+
+ Returns
+ -------
+ extrema : tuple of ndarrays
+ Indices of the maxima in arrays of integers. ``extrema[k]`` is
+ the array of indices of axis `k` of `data`. Note that the
+ return value is a tuple even when `data` is 1-D.
+
+ See Also
+ --------
+ argrelextrema, argrelmin, find_peaks
+
+ Notes
+ -----
+ This function uses `argrelextrema` with np.greater as comparator. Therefore,
+ it requires a strict inequality on both sides of a value to consider it a
+ maximum. This means flat maxima (more than one sample wide) are not detected.
+ In case of 1-D `data` `find_peaks` can be used to detect all
+ local maxima, including flat ones.
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import argrelmax
+ >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
+ >>> argrelmax(x)
+ (array([3, 6]),)
+ >>> y = np.array([[1, 2, 1, 2],
+ ... [2, 2, 0, 0],
+ ... [5, 3, 4, 4]])
+ ...
+ >>> argrelmax(y, axis=1)
+ (array([0]), array([1]))
+ """
+ return argrelextrema(data, np.greater, axis, order, mode)
+
+
+def argrelextrema(data, comparator, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative extrema of `data`.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative extrema.
+ comparator : callable
+ Function to use to compare two data points.
+ Should take two arrays as arguments.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n, n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated. 'wrap' (wrap around) or
+ 'clip' (treat overflow as the same as the last (or first) element).
+ Default is 'clip'. See `numpy.take`.
+
+ Returns
+ -------
+ extrema : tuple of ndarrays
+ Indices of the maxima in arrays of integers. ``extrema[k]`` is
+ the array of indices of axis `k` of `data`. Note that the
+ return value is a tuple even when `data` is 1-D.
+
+ See Also
+ --------
+ argrelmin, argrelmax
+
+ Notes
+ -----
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import argrelextrema
+ >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
+ >>> argrelextrema(x, np.greater)
+ (array([3, 6]),)
+ >>> y = np.array([[1, 2, 1, 2],
+ ... [2, 2, 0, 0],
+ ... [5, 3, 4, 4]])
+ ...
+ >>> argrelextrema(y, np.less, axis=1)
+ (array([0, 2]), array([2, 1]))
+
+ """
+ results = _boolrelextrema(data, comparator,
+ axis, order, mode)
+ return np.nonzero(results)
+
+
+def _arg_x_as_expected(value):
+ """Ensure argument `x` is a 1-D C-contiguous array of dtype('float64').
+
+ Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x`
+ compatible with the signature of the wrapped Cython functions.
+
+ Returns
+ -------
+ value : ndarray
+ A 1-D C-contiguous array with dtype('float64').
+ """
+ value = np.asarray(value, order='C', dtype=np.float64)
+ if value.ndim != 1:
+ raise ValueError('`x` must be a 1-D array')
+ return value
+
+
+def _arg_peaks_as_expected(value):
+ """Ensure argument `peaks` is a 1-D C-contiguous array of dtype('intp').
+
+ Used in `peak_prominences` and `peak_widths` to make `peaks` compatible
+ with the signature of the wrapped Cython functions.
+
+ Returns
+ -------
+ value : ndarray
+ A 1-D C-contiguous array with dtype('intp').
+ """
+ value = np.asarray(value)
+ if value.size == 0:
+ # Empty arrays default to np.float64 but are valid input
+ value = np.array([], dtype=np.intp)
+ try:
+ # Safely convert to C-contiguous array of type np.intp
+ value = value.astype(np.intp, order='C', casting='safe',
+ subok=False, copy=False)
+ except TypeError as e:
+ raise TypeError("cannot safely cast `peaks` to dtype('intp')") from e
+ if value.ndim != 1:
+ raise ValueError('`peaks` must be a 1-D array')
+ return value
+
+
+def _arg_wlen_as_expected(value):
+ """Ensure argument `wlen` is of type `np.intp` and larger than 1.
+
+ Used in `peak_prominences` and `peak_widths`.
+
+ Returns
+ -------
+ value : np.intp
+ The original `value` rounded up to an integer or -1 if `value` was
+ None.
+ """
+ if value is None:
+ # _peak_prominences expects an intp; -1 signals that no value was
+ # supplied by the user
+ value = -1
+ elif 1 < value:
+ # Round up to a positive integer
+ if isinstance(value, float):
+ value = math.ceil(value)
+ value = np.intp(value)
+ else:
+ raise ValueError(f'`wlen` must be larger than 1, was {value}')
+ return value
+
+
+def peak_prominences(x, peaks, wlen=None):
+ """
+ Calculate the prominence of each peak in a signal.
+
+ The prominence of a peak measures how much a peak stands out from the
+ surrounding baseline of the signal and is defined as the vertical distance
+ between the peak and its lowest contour line.
+
+ Parameters
+ ----------
+ x : sequence
+ A signal with peaks.
+ peaks : sequence
+ Indices of peaks in `x`.
+ wlen : int, optional
+ A window length in samples that optionally limits the evaluated area for
+ each peak to a subset of `x`. The peak is always placed in the middle of
+ the window therefore the given length is rounded up to the next odd
+ integer. This parameter can speed up the calculation (see Notes).
+
+ Returns
+ -------
+ prominences : ndarray
+ The calculated prominences for each peak in `peaks`.
+ left_bases, right_bases : ndarray
+ The peaks' bases as indices in `x` to the left and right of each peak.
+ The higher base of each pair is a peak's lowest contour line.
+
+ Raises
+ ------
+ ValueError
+ If a value in `peaks` is an invalid index for `x`.
+
+ Warns
+ -----
+ PeakPropertyWarning
+ For indices in `peaks` that don't point to valid local maxima in `x`,
+ the returned prominence will be 0 and this warning is raised. This
+ also happens if `wlen` is smaller than the plateau size of a peak.
+
+ Warnings
+ --------
+ This function may return unexpected results for data containing NaNs. To
+ avoid this, NaNs should either be removed or replaced.
+
+ See Also
+ --------
+ find_peaks
+ Find peaks inside a signal based on peak properties.
+ peak_widths
+ Calculate the width of peaks.
+
+ Notes
+ -----
+ Strategy to compute a peak's prominence:
+
+ 1. Extend a horizontal line from the current peak to the left and right
+ until the line either reaches the window border (see `wlen`) or
+ intersects the signal again at the slope of a higher peak. An
+ intersection with a peak of the same height is ignored.
+ 2. On each side find the minimal signal value within the interval defined
+ above. These points are the peak's bases.
+ 3. The higher one of the two bases marks the peak's lowest contour line. The
+ prominence can then be calculated as the vertical difference between the
+ peaks height itself and its lowest contour line.
+
+ Searching for the peak's bases can be slow for large `x` with periodic
+ behavior because large chunks or even the full signal need to be evaluated
+ for the first algorithmic step. This evaluation area can be limited with the
+ parameter `wlen` which restricts the algorithm to a window around the
+ current peak and can shorten the calculation time if the window length is
+ short in relation to `x`.
+ However, this may stop the algorithm from finding the true global contour
+ line if the peak's true bases are outside this window. Instead, a higher
+ contour line is found within the restricted window leading to a smaller
+ calculated prominence. In practice, this is only relevant for the highest set
+ of peaks in `x`. This behavior may even be used intentionally to calculate
+ "local" prominences.
+
+ .. versionadded:: 1.1.0
+
+ References
+ ----------
+ .. [1] Wikipedia Article for Topographic Prominence:
+ https://en.wikipedia.org/wiki/Topographic_prominence
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import find_peaks, peak_prominences
+ >>> import matplotlib.pyplot as plt
+
+ Create a test signal with two overlaid harmonics
+
+ >>> x = np.linspace(0, 6 * np.pi, 1000)
+ >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)
+
+ Find all peaks and calculate prominences
+
+ >>> peaks, _ = find_peaks(x)
+ >>> prominences = peak_prominences(x, peaks)[0]
+ >>> prominences
+ array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 ,
+ 0.47822491, 2.48340261, 0.47822491])
+
+ Calculate the height of each peak's contour line and plot the results
+
+ >>> contour_heights = x[peaks] - prominences
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks])
+ >>> plt.show()
+
+ Let's evaluate a second example that demonstrates several edge cases for
+ one peak at index 5.
+
+ >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0])
+ >>> peaks = np.array([5])
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+ >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases)
+ (array([3.]), array([2]), array([6]))
+
+ Note how the peak at index 3 of the same height is not considered as a
+ border while searching for the left base. Instead, two minima at 0 and 2
+ are found in which case the one closer to the evaluated peak is always
+ chosen. On the right side, however, the base must be placed at 6 because the
+ higher peak represents the right border to the evaluated area.
+
+ >>> peak_prominences(x, peaks, wlen=3.1)
+ (array([2.]), array([4]), array([6]))
+
+ Here, we restricted the algorithm to a window from 3 to 7 (the length is 5
+ samples because `wlen` was rounded up to the next odd integer). Thus, the
+ only two candidates in the evaluated area are the two neighboring samples
+ and a smaller prominence is calculated.
+ """
+ x = _arg_x_as_expected(x)
+ peaks = _arg_peaks_as_expected(peaks)
+ wlen = _arg_wlen_as_expected(wlen)
+ return _peak_prominences(x, peaks, wlen)
+
+
+def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None):
+ """
+ Calculate the width of each peak in a signal.
+
+ This function calculates the width of a peak in samples at a relative
+ distance to the peak's height and prominence.
+
+ Parameters
+ ----------
+ x : sequence
+ A signal with peaks.
+ peaks : sequence
+ Indices of peaks in `x`.
+ rel_height : float, optional
+ Chooses the relative height at which the peak width is measured as a
+ percentage of its prominence. 1.0 calculates the width of the peak at
+ its lowest contour line while 0.5 evaluates at half the prominence
+ height. Must be at least 0. See notes for further explanation.
+ prominence_data : tuple, optional
+ A tuple of three arrays matching the output of `peak_prominences` when
+ called with the same arguments `x` and `peaks`. This data are calculated
+ internally if not provided.
+ wlen : int, optional
+ A window length in samples passed to `peak_prominences` as an optional
+ argument for internal calculation of `prominence_data`. This argument
+ is ignored if `prominence_data` is given.
+
+ Returns
+ -------
+ widths : ndarray
+ The widths for each peak in samples.
+ width_heights : ndarray
+ The height of the contour lines at which the `widths` where evaluated.
+ left_ips, right_ips : ndarray
+ Interpolated positions of left and right intersection points of a
+ horizontal line at the respective evaluation height.
+
+ Raises
+ ------
+ ValueError
+ If `prominence_data` is supplied but doesn't satisfy the condition
+ ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak,
+ has the wrong dtype, is not C-contiguous or does not have the same
+ shape.
+
+ Warns
+ -----
+ PeakPropertyWarning
+ Raised if any calculated width is 0. This may stem from the supplied
+ `prominence_data` or if `rel_height` is set to 0.
+
+ Warnings
+ --------
+ This function may return unexpected results for data containing NaNs. To
+ avoid this, NaNs should either be removed or replaced.
+
+ See Also
+ --------
+ find_peaks
+ Find peaks inside a signal based on peak properties.
+ peak_prominences
+ Calculate the prominence of peaks.
+
+ Notes
+ -----
+ The basic algorithm to calculate a peak's width is as follows:
+
+ * Calculate the evaluation height :math:`h_{eval}` with the formula
+ :math:`h_{eval} = h_{Peak} - P \\cdot R`, where :math:`h_{Peak}` is the
+ height of the peak itself, :math:`P` is the peak's prominence and
+ :math:`R` a positive ratio specified with the argument `rel_height`.
+ * Draw a horizontal line at the evaluation height to both sides, starting at
+ the peak's current vertical position until the lines either intersect a
+ slope, the signal border or cross the vertical position of the peak's
+ base (see `peak_prominences` for a definition). For the first case,
+ intersection with the signal, the true intersection point is estimated
+ with linear interpolation.
+ * Calculate the width as the horizontal distance between the chosen
+ endpoints on both sides. As a consequence of this the maximal possible
+ width for each peak is the horizontal distance between its bases.
+
+ As shown above to calculate a peak's width its prominence and bases must be
+ known. You can supply these yourself with the argument `prominence_data`.
+ Otherwise, they are internally calculated (see `peak_prominences`).
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import chirp, find_peaks, peak_widths
+ >>> import matplotlib.pyplot as plt
+
+ Create a test signal with two overlaid harmonics
+
+ >>> x = np.linspace(0, 6 * np.pi, 1000)
+ >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)
+
+ Find all peaks and calculate their widths at the relative height of 0.5
+ (contour line at half the prominence height) and 1 (at the lowest contour
+ line at full prominence height).
+
+ >>> peaks, _ = find_peaks(x)
+ >>> results_half = peak_widths(x, peaks, rel_height=0.5)
+ >>> results_half[0] # widths
+ array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081,
+ 35.46729324, 41.30429622, 181.93835853, 45.37078546])
+ >>> results_full = peak_widths(x, peaks, rel_height=1)
+ >>> results_full[0] # widths
+ array([181.9396084 , 72.99284945, 61.28657872, 373.84622694,
+ 61.78404617, 72.48822812, 253.09161876, 79.36860878])
+
+ Plot signal, peaks and contour lines at which the widths where calculated
+
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.hlines(*results_half[1:], color="C2")
+ >>> plt.hlines(*results_full[1:], color="C3")
+ >>> plt.show()
+ """
+ x = _arg_x_as_expected(x)
+ peaks = _arg_peaks_as_expected(peaks)
+ if prominence_data is None:
+ # Calculate prominence if not supplied and use wlen if supplied.
+ wlen = _arg_wlen_as_expected(wlen)
+ prominence_data = _peak_prominences(x, peaks, wlen)
+ return _peak_widths(x, peaks, rel_height, *prominence_data)
+
+
+def _unpack_condition_args(interval, x, peaks):
+ """
+ Parse condition arguments for `find_peaks`.
+
+ Parameters
+ ----------
+ interval : number or ndarray or sequence
+ Either a number or ndarray or a 2-element sequence of the former. The
+ first value is always interpreted as `imin` and the second, if supplied,
+ as `imax`.
+ x : ndarray
+ The signal with `peaks`.
+ peaks : ndarray
+ An array with indices used to reduce `imin` and / or `imax` if those are
+ arrays.
+
+ Returns
+ -------
+ imin, imax : number or ndarray or None
+ Minimal and maximal value in `argument`.
+
+ Raises
+ ------
+ ValueError :
+ If interval border is given as array and its size does not match the size
+ of `x`.
+
+ Notes
+ -----
+
+ .. versionadded:: 1.1.0
+ """
+ try:
+ imin, imax = interval
+ except (TypeError, ValueError):
+ imin, imax = (interval, None)
+
+ # Reduce arrays if arrays
+ if isinstance(imin, np.ndarray):
+ if imin.size != x.size:
+ raise ValueError('array size of lower interval border must match x')
+ imin = imin[peaks]
+ if isinstance(imax, np.ndarray):
+ if imax.size != x.size:
+ raise ValueError('array size of upper interval border must match x')
+ imax = imax[peaks]
+
+ return imin, imax
+
+
+def _select_by_property(peak_properties, pmin, pmax):
+ """
+ Evaluate where the generic property of peaks confirms to an interval.
+
+ Parameters
+ ----------
+ peak_properties : ndarray
+ An array with properties for each peak.
+ pmin : None or number or ndarray
+ Lower interval boundary for `peak_properties`. ``None`` is interpreted as
+ an open border.
+ pmax : None or number or ndarray
+ Upper interval boundary for `peak_properties`. ``None`` is interpreted as
+ an open border.
+
+ Returns
+ -------
+ keep : bool
+ A boolean mask evaluating to true where `peak_properties` confirms to the
+ interval.
+
+ See Also
+ --------
+ find_peaks
+
+ Notes
+ -----
+
+ .. versionadded:: 1.1.0
+ """
+ keep = np.ones(peak_properties.size, dtype=bool)
+ if pmin is not None:
+ keep &= (pmin <= peak_properties)
+ if pmax is not None:
+ keep &= (peak_properties <= pmax)
+ return keep
+
+
+def _select_by_peak_threshold(x, peaks, tmin, tmax):
+ """
+ Evaluate which peaks fulfill the threshold condition.
+
+ Parameters
+ ----------
+ x : ndarray
+ A 1-D array which is indexable by `peaks`.
+ peaks : ndarray
+ Indices of peaks in `x`.
+ tmin, tmax : scalar or ndarray or None
+ Minimal and / or maximal required thresholds. If supplied as ndarrays
+ their size must match `peaks`. ``None`` is interpreted as an open
+ border.
+
+ Returns
+ -------
+ keep : bool
+ A boolean mask evaluating to true where `peaks` fulfill the threshold
+ condition.
+ left_thresholds, right_thresholds : ndarray
+ Array matching `peak` containing the thresholds of each peak on
+ both sides.
+
+ Notes
+ -----
+
+ .. versionadded:: 1.1.0
+ """
+ # Stack thresholds on both sides to make min / max operations easier:
+ # tmin is compared with the smaller, and tmax with the greater threshold to
+ # each peak's side
+ stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1],
+ x[peaks] - x[peaks + 1]])
+ keep = np.ones(peaks.size, dtype=bool)
+ if tmin is not None:
+ min_thresholds = np.min(stacked_thresholds, axis=0)
+ keep &= (tmin <= min_thresholds)
+ if tmax is not None:
+ max_thresholds = np.max(stacked_thresholds, axis=0)
+ keep &= (max_thresholds <= tmax)
+
+ return keep, stacked_thresholds[0], stacked_thresholds[1]
+
+
+def find_peaks(x, height=None, threshold=None, distance=None,
+ prominence=None, width=None, wlen=None, rel_height=0.5,
+ plateau_size=None):
+ """
+ Find peaks inside a signal based on peak properties.
+
+ This function takes a 1-D array and finds all local maxima by
+ simple comparison of neighboring values. Optionally, a subset of these
+ peaks can be selected by specifying conditions for a peak's properties.
+
+ Parameters
+ ----------
+ x : sequence
+ A signal with peaks.
+ height : number or ndarray or sequence, optional
+ Required height of peaks. Either a number, ``None``, an array matching
+ `x` or a 2-element sequence of the former. The first element is
+ always interpreted as the minimal and the second, if supplied, as the
+ maximal required height.
+ threshold : number or ndarray or sequence, optional
+ Required threshold of peaks, the vertical distance to its neighboring
+ samples. Either a number, ``None``, an array matching `x` or a
+ 2-element sequence of the former. The first element is always
+ interpreted as the minimal and the second, if supplied, as the maximal
+ required threshold.
+ distance : number, optional
+ Required minimal horizontal distance (>= 1) in samples between
+ neighbouring peaks. Smaller peaks are removed first until the condition
+ is fulfilled for all remaining peaks.
+ prominence : number or ndarray or sequence, optional
+ Required prominence of peaks. Either a number, ``None``, an array
+ matching `x` or a 2-element sequence of the former. The first
+ element is always interpreted as the minimal and the second, if
+ supplied, as the maximal required prominence.
+ width : number or ndarray or sequence, optional
+ Required width of peaks in samples. Either a number, ``None``, an array
+ matching `x` or a 2-element sequence of the former. The first
+ element is always interpreted as the minimal and the second, if
+ supplied, as the maximal required width.
+ wlen : int, optional
+ Used for calculation of the peaks prominences, thus it is only used if
+ one of the arguments `prominence` or `width` is given. See argument
+ `wlen` in `peak_prominences` for a full description of its effects.
+ rel_height : float, optional
+ Used for calculation of the peaks width, thus it is only used if `width`
+ is given. See argument `rel_height` in `peak_widths` for a full
+ description of its effects.
+ plateau_size : number or ndarray or sequence, optional
+ Required size of the flat top of peaks in samples. Either a number,
+ ``None``, an array matching `x` or a 2-element sequence of the former.
+ The first element is always interpreted as the minimal and the second,
+ if supplied as the maximal required plateau size.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ peaks : ndarray
+ Indices of peaks in `x` that satisfy all given conditions.
+ properties : dict
+ A dictionary containing properties of the returned peaks which were
+ calculated as intermediate results during evaluation of the specified
+ conditions:
+
+ * 'peak_heights'
+ If `height` is given, the height of each peak in `x`.
+ * 'left_thresholds', 'right_thresholds'
+ If `threshold` is given, these keys contain a peaks vertical
+ distance to its neighbouring samples.
+ * 'prominences', 'right_bases', 'left_bases'
+ If `prominence` is given, these keys are accessible. See
+ `peak_prominences` for a description of their content.
+ * 'widths', 'width_heights', 'left_ips', 'right_ips'
+ If `width` is given, these keys are accessible. See `peak_widths`
+ for a description of their content.
+ * 'plateau_sizes', left_edges', 'right_edges'
+ If `plateau_size` is given, these keys are accessible and contain
+ the indices of a peak's edges (edges are still part of the
+ plateau) and the calculated plateau sizes.
+
+ .. versionadded:: 1.2.0
+
+ To calculate and return properties without excluding peaks, provide the
+ open interval ``(None, None)`` as a value to the appropriate argument
+ (excluding `distance`).
+
+ Warns
+ -----
+ PeakPropertyWarning
+ Raised if a peak's properties have unexpected values (see
+ `peak_prominences` and `peak_widths`).
+
+ Warnings
+ --------
+ This function may return unexpected results for data containing NaNs. To
+ avoid this, NaNs should either be removed or replaced.
+
+ See Also
+ --------
+ find_peaks_cwt
+ Find peaks using the wavelet transformation.
+ peak_prominences
+ Directly calculate the prominence of peaks.
+ peak_widths
+ Directly calculate the width of peaks.
+
+ Notes
+ -----
+ In the context of this function, a peak or local maximum is defined as any
+ sample whose two direct neighbours have a smaller amplitude. For flat peaks
+ (more than one sample of equal amplitude wide) the index of the middle
+ sample is returned (rounded down in case the number of samples is even).
+ For noisy signals the peak locations can be off because the noise might
+ change the position of local maxima. In those cases consider smoothing the
+ signal before searching for peaks or use other peak finding and fitting
+ methods (like `find_peaks_cwt`).
+
+ Some additional comments on specifying conditions:
+
+ * Almost all conditions (excluding `distance`) can be given as half-open or
+ closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open
+ interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval
+ :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified
+ as well, which returns the matching properties without exclusion of peaks.
+ * The border is always included in the interval used to select valid peaks.
+ * For several conditions the interval borders can be specified with
+ arrays matching `x` in shape which enables dynamic constrains based on
+ the sample position.
+ * The conditions are evaluated in the following order: `plateau_size`,
+ `height`, `threshold`, `distance`, `prominence`, `width`. In most cases
+ this order is the fastest one because faster operations are applied first
+ to reduce the number of peaks that need to be evaluated later.
+ * While indices in `peaks` are guaranteed to be at least `distance` samples
+ apart, edges of flat peaks may be closer than the allowed `distance`.
+ * Use `wlen` to reduce the time it takes to evaluate the conditions for
+ `prominence` or `width` if `x` is large or has many local maxima
+ (see `peak_prominences`).
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ To demonstrate this function's usage we use a signal `x` supplied with
+ SciPy (see `scipy.datasets.electrocardiogram`). Let's find all peaks (local
+ maxima) in `x` whose amplitude lies above 0.
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.datasets import electrocardiogram
+ >>> from scipy.signal import find_peaks
+ >>> x = electrocardiogram()[2000:4000]
+ >>> peaks, _ = find_peaks(x, height=0)
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.plot(np.zeros_like(x), "--", color="gray")
+ >>> plt.show()
+
+ We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching
+ `x` in size to reflect a changing condition for different parts of the
+ signal.
+
+ >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size))
+ >>> peaks, _ = find_peaks(x, height=(-border, border))
+ >>> plt.plot(x)
+ >>> plt.plot(-border, "--", color="gray")
+ >>> plt.plot(border, ":", color="gray")
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+
+ Another useful condition for periodic signals can be given with the
+ `distance` argument. In this case, we can easily select the positions of
+ QRS complexes within the electrocardiogram (ECG) by demanding a distance of
+ at least 150 samples.
+
+ >>> peaks, _ = find_peaks(x, distance=150)
+ >>> np.diff(peaks)
+ array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172])
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+
+ Especially for noisy signals peaks can be easily grouped by their
+ prominence (see `peak_prominences`). E.g., we can select all peaks except
+ for the mentioned QRS complexes by limiting the allowed prominence to 0.6.
+
+ >>> peaks, properties = find_peaks(x, prominence=(None, 0.6))
+ >>> properties["prominences"].max()
+ 0.5049999999999999
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+
+ And, finally, let's examine a different section of the ECG which contains
+ beat forms of different shape. To select only the atypical heart beats, we
+ combine two conditions: a minimal prominence of 1 and width of at least 20
+ samples.
+
+ >>> x = electrocardiogram()[17000:18000]
+ >>> peaks, properties = find_peaks(x, prominence=1, width=20)
+ >>> properties["prominences"], properties["widths"]
+ (array([1.495, 2.3 ]), array([36.93773946, 39.32723577]))
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"],
+ ... ymax = x[peaks], color = "C1")
+ >>> plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"],
+ ... xmax=properties["right_ips"], color = "C1")
+ >>> plt.show()
+ """
+ # _argmaxima1d expects array of dtype 'float64'
+ x = _arg_x_as_expected(x)
+ if distance is not None and distance < 1:
+ raise ValueError('`distance` must be greater or equal to 1')
+
+ peaks, left_edges, right_edges = _local_maxima_1d(x)
+ properties = {}
+
+ if plateau_size is not None:
+ # Evaluate plateau size
+ plateau_sizes = right_edges - left_edges + 1
+ pmin, pmax = _unpack_condition_args(plateau_size, x, peaks)
+ keep = _select_by_property(plateau_sizes, pmin, pmax)
+ peaks = peaks[keep]
+ properties["plateau_sizes"] = plateau_sizes
+ properties["left_edges"] = left_edges
+ properties["right_edges"] = right_edges
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if height is not None:
+ # Evaluate height condition
+ peak_heights = x[peaks]
+ hmin, hmax = _unpack_condition_args(height, x, peaks)
+ keep = _select_by_property(peak_heights, hmin, hmax)
+ peaks = peaks[keep]
+ properties["peak_heights"] = peak_heights
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if threshold is not None:
+ # Evaluate threshold condition
+ tmin, tmax = _unpack_condition_args(threshold, x, peaks)
+ keep, left_thresholds, right_thresholds = _select_by_peak_threshold(
+ x, peaks, tmin, tmax)
+ peaks = peaks[keep]
+ properties["left_thresholds"] = left_thresholds
+ properties["right_thresholds"] = right_thresholds
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if distance is not None:
+ # Evaluate distance condition
+ keep = _select_by_peak_distance(peaks, x[peaks], distance)
+ peaks = peaks[keep]
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if prominence is not None or width is not None:
+ # Calculate prominence (required for both conditions)
+ wlen = _arg_wlen_as_expected(wlen)
+ properties.update(zip(
+ ['prominences', 'left_bases', 'right_bases'],
+ _peak_prominences(x, peaks, wlen=wlen)
+ ))
+
+ if prominence is not None:
+ # Evaluate prominence condition
+ pmin, pmax = _unpack_condition_args(prominence, x, peaks)
+ keep = _select_by_property(properties['prominences'], pmin, pmax)
+ peaks = peaks[keep]
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if width is not None:
+ # Calculate widths
+ properties.update(zip(
+ ['widths', 'width_heights', 'left_ips', 'right_ips'],
+ _peak_widths(x, peaks, rel_height, properties['prominences'],
+ properties['left_bases'], properties['right_bases'])
+ ))
+ # Evaluate width condition
+ wmin, wmax = _unpack_condition_args(width, x, peaks)
+ keep = _select_by_property(properties['widths'], wmin, wmax)
+ peaks = peaks[keep]
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ return peaks, properties
+
+
+def _identify_ridge_lines(matr, max_distances, gap_thresh):
+ """
+ Identify ridges in the 2-D matrix.
+
+ Expect that the width of the wavelet feature increases with increasing row
+ number.
+
+ Parameters
+ ----------
+ matr : 2-D ndarray
+ Matrix in which to identify ridge lines.
+ max_distances : 1-D sequence
+ At each row, a ridge line is only connected
+ if the relative max at row[n] is within
+ `max_distances`[n] from the relative max at row[n+1].
+ gap_thresh : int
+ If a relative maximum is not found within `max_distances`,
+ there will be a gap. A ridge line is discontinued if
+ there are more than `gap_thresh` points without connecting
+ a new relative maximum.
+
+ Returns
+ -------
+ ridge_lines : tuple
+ Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the
+ ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none
+ found. Each ridge-line will be sorted by row (increasing), but the
+ order of the ridge lines is not specified.
+
+ References
+ ----------
+ .. [1] Bioinformatics (2006) 22 (17): 2059-2065.
+ :doi:`10.1093/bioinformatics/btl355`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._peak_finding import _identify_ridge_lines
+ >>> rng = np.random.default_rng()
+ >>> data = rng.random((5,5))
+ >>> max_dist = 3
+ >>> max_distances = np.full(20, max_dist)
+ >>> ridge_lines = _identify_ridge_lines(data, max_distances, 1)
+
+ Notes
+ -----
+ This function is intended to be used in conjunction with `cwt`
+ as part of `find_peaks_cwt`.
+
+ """
+ if len(max_distances) < matr.shape[0]:
+ raise ValueError('Max_distances must have at least as many rows '
+ 'as matr')
+
+ all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1)
+ # Highest row for which there are any relative maxima
+ has_relmax = np.nonzero(all_max_cols.any(axis=1))[0]
+ if len(has_relmax) == 0:
+ return []
+ start_row = has_relmax[-1]
+ # Each ridge line is a 3-tuple:
+ # rows, cols,Gap number
+ ridge_lines = [[[start_row],
+ [col],
+ 0] for col in np.nonzero(all_max_cols[start_row])[0]]
+ final_lines = []
+ rows = np.arange(start_row - 1, -1, -1)
+ cols = np.arange(0, matr.shape[1])
+ for row in rows:
+ this_max_cols = cols[all_max_cols[row]]
+
+ # Increment gap number of each line,
+ # set it to zero later if appropriate
+ for line in ridge_lines:
+ line[2] += 1
+
+ # XXX These should always be all_max_cols[row]
+ # But the order might be different. Might be an efficiency gain
+ # to make sure the order is the same and avoid this iteration
+ prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines])
+ # Look through every relative maximum found at current row
+ # Attempt to connect them with existing ridge lines.
+ for ind, col in enumerate(this_max_cols):
+ # If there is a previous ridge line within
+ # the max_distance to connect to, do so.
+ # Otherwise start a new one.
+ line = None
+ if len(prev_ridge_cols) > 0:
+ diffs = np.abs(col - prev_ridge_cols)
+ closest = np.argmin(diffs)
+ if diffs[closest] <= max_distances[row]:
+ line = ridge_lines[closest]
+ if line is not None:
+ # Found a point close enough, extend current ridge line
+ line[1].append(col)
+ line[0].append(row)
+ line[2] = 0
+ else:
+ new_line = [[row],
+ [col],
+ 0]
+ ridge_lines.append(new_line)
+
+ # Remove the ridge lines with gap_number too high
+ # XXX Modifying a list while iterating over it.
+ # Should be safe, since we iterate backwards, but
+ # still tacky.
+ for ind in range(len(ridge_lines) - 1, -1, -1):
+ line = ridge_lines[ind]
+ if line[2] > gap_thresh:
+ final_lines.append(line)
+ del ridge_lines[ind]
+
+ out_lines = []
+ for line in (final_lines + ridge_lines):
+ sortargs = np.argsort(line[0])
+ rows = np.array(line[0])[sortargs]
+ cols = np.array(line[1])[sortargs]
+ out_lines.append([rows, cols])
+
+ return out_lines
+
+
+def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None,
+ min_snr=1, noise_perc=10):
+ """
+ Filter ridge lines according to prescribed criteria. Intended
+ to be used for finding relative maxima.
+
+ Parameters
+ ----------
+ cwt : 2-D ndarray
+ Continuous wavelet transform from which the `ridge_lines` were defined.
+ ridge_lines : 1-D sequence
+ Each element should contain 2 sequences, the rows and columns
+ of the ridge line (respectively).
+ window_size : int, optional
+ Size of window to use to calculate noise floor.
+ Default is ``cwt.shape[1] / 20``.
+ min_length : int, optional
+ Minimum length a ridge line needs to be acceptable.
+ Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
+ min_snr : float, optional
+ Minimum SNR ratio. Default 1. The signal is the value of
+ the cwt matrix at the shortest length scale (``cwt[0, loc]``), the
+ noise is the `noise_perc`\\ th percentile of datapoints contained within a
+ window of `window_size` around ``cwt[0, loc]``.
+ noise_perc : float, optional
+ When calculating the noise floor, percentile of data points
+ examined below which to consider noise. Calculated using
+ scipy.stats.scoreatpercentile.
+
+ References
+ ----------
+ .. [1] Bioinformatics (2006) 22 (17): 2059-2065.
+ :doi:`10.1093/bioinformatics/btl355`
+
+ """
+ num_points = cwt.shape[1]
+ if min_length is None:
+ min_length = np.ceil(cwt.shape[0] / 4)
+ if window_size is None:
+ window_size = np.ceil(num_points / 20)
+
+ window_size = int(window_size)
+ hf_window, odd = divmod(window_size, 2)
+
+ # Filter based on SNR
+ row_one = cwt[0, :]
+ noises = np.empty_like(row_one)
+ for ind, val in enumerate(row_one):
+ window_start = max(ind - hf_window, 0)
+ window_end = min(ind + hf_window + odd, num_points)
+ noises[ind] = scoreatpercentile(row_one[window_start:window_end],
+ per=noise_perc)
+
+ def filt_func(line):
+ if len(line[0]) < min_length:
+ return False
+ snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]])
+ if snr < min_snr:
+ return False
+ return True
+
+ return list(filter(filt_func, ridge_lines))
+
+
+def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None,
+ gap_thresh=None, min_length=None,
+ min_snr=1, noise_perc=10, window_size=None):
+ """
+ Find peaks in a 1-D array with wavelet transformation.
+
+ The general approach is to smooth `vector` by convolving it with
+ `wavelet(width)` for each width in `widths`. Relative maxima which
+ appear at enough length scales, and with sufficiently high SNR, are
+ accepted.
+
+ Parameters
+ ----------
+ vector : ndarray
+ 1-D array in which to find the peaks.
+ widths : float or sequence
+ Single width or 1-D array-like of widths to use for calculating
+ the CWT matrix. In general,
+ this range should cover the expected width of peaks of interest.
+ wavelet : callable, optional
+ Should take two parameters and return a 1-D array to convolve
+ with `vector`. The first parameter determines the number of points
+ of the returned wavelet array, the second parameter is the scale
+ (`width`) of the wavelet. Should be normalized and symmetric.
+ Default is the ricker wavelet.
+ max_distances : ndarray, optional
+ At each row, a ridge line is only connected if the relative max at
+ ``row[n]`` is within ``max_distances[n]`` from the relative max at
+ ``row[n+1]``. Default value is ``widths/4``.
+ gap_thresh : float, optional
+ If a relative maximum is not found within `max_distances`,
+ there will be a gap. A ridge line is discontinued if there are more
+ than `gap_thresh` points without connecting a new relative maximum.
+ Default is the first value of the widths array i.e. ``widths[0]``.
+ min_length : int, optional
+ Minimum length a ridge line needs to be acceptable.
+ Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
+ min_snr : float, optional
+ Minimum SNR ratio. Default 1. The signal is the maximum CWT coefficient
+ on the largest ridge line. The noise is `noise_perc` th percentile of
+ datapoints contained within the same ridge line.
+ noise_perc : float, optional
+ When calculating the noise floor, percentile of data points
+ examined below which to consider noise. Calculated using
+ `stats.scoreatpercentile`. Default is 10.
+ window_size : int, optional
+ Size of window to use to calculate noise floor.
+ Default is ``cwt.shape[1] / 20``.
+
+ Returns
+ -------
+ peaks_indices : ndarray
+ Indices of the locations in the `vector` where peaks were found.
+ The list is sorted.
+
+ See Also
+ --------
+ find_peaks
+ Find peaks inside a signal based on peak properties.
+
+ Notes
+ -----
+ This approach was designed for finding sharp peaks among noisy data,
+ however with proper parameter selection it should function well for
+ different peak shapes.
+
+ The algorithm is as follows:
+ 1. Perform a continuous wavelet transform on `vector`, for the supplied
+ `widths`. This is a convolution of `vector` with `wavelet(width)` for
+ each width in `widths`.
+ 2. Identify "ridge lines" in the cwt matrix. These are relative maxima
+ at each row, connected across adjacent rows. See identify_ridge_lines
+ 3. Filter the ridge_lines using filter_ridge_lines.
+
+ References
+ ----------
+ .. [1] Bioinformatics (2006) 22 (17): 2059-2065.
+ :doi:`10.1093/bioinformatics/btl355`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> xs = np.arange(0, np.pi, 0.05)
+ >>> data = np.sin(xs)
+ >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10))
+ >>> peakind, xs[peakind], data[peakind]
+ ([32], array([ 1.6]), array([ 0.9995736]))
+
+ """
+ widths = np.atleast_1d(np.asarray(widths))
+
+ if gap_thresh is None:
+ gap_thresh = np.ceil(widths[0])
+ if max_distances is None:
+ max_distances = widths / 4.0
+ if wavelet is None:
+ wavelet = _ricker
+
+ cwt_dat = _cwt(vector, wavelet, widths)
+ ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh)
+ filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length,
+ window_size=window_size, min_snr=min_snr,
+ noise_perc=noise_perc)
+ max_locs = np.asarray([x[1][0] for x in filtered])
+ max_locs.sort()
+
+ return max_locs
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..93748f56c23450c1950fc987ae0b081f86420a5e
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9236e3ea016a8a087c8fd989e15aa475286e0578a0389c066be771717999e4d6
+size 146760
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_polyutils.py b/.venv/lib/python3.12/site-packages/scipy/signal/_polyutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..28bad89ab4e406d46d736a6f727528e40683fc30
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_polyutils.py
@@ -0,0 +1,257 @@
+"""Partial replacements for numpy polynomial routines, with Array API compatibility.
+
+This module contains both "old-style", np.poly1d, routines from the main numpy
+namespace, and "new-style", np.polynomial.polynomial, routines.
+
+To distinguish the two sets, the "new-style" routine names start with `npp_`
+"""
+import warnings
+import scipy._external.array_api_extra as xpx
+from scipy._lib._array_api import (
+ xp_promote, xp_default_dtype, xp_size, xp_device, is_numpy
+)
+
+from numpy.exceptions import RankWarning
+
+
+def _sort_cmplx(arr, xp):
+ # xp.sort is undefined for complex dtypes. Here we only need some
+ # consistent way to sort a complex array, including equal magnitude elements.
+ arr = xp.asarray(arr)
+ if xp.isdtype(arr.dtype, 'complex floating'):
+ sorter = abs(arr) + xp.real(arr) + xp.imag(arr)**3
+ else:
+ sorter = arr
+
+ idxs = xp.argsort(sorter)
+ return arr[idxs]
+
+
+def polyroots(coef, *, xp):
+ """numpy.roots, best-effor replacement
+ """
+ if coef.shape[0] < 2:
+ return xp.asarray([], dtype=coef.dtype)
+
+ root_func = getattr(xp, 'roots', None)
+ if root_func:
+ # NB: cupy.roots is broken in CuPy 13.x, but CuPy is handled via delegation
+ # so we never hit this code path with xp being cupy
+ return root_func(coef)
+
+ # companion matrix
+ n = coef.shape[0]
+ a = xp.eye(n - 1, n - 1, k=-1, dtype=coef.dtype)
+ a[:, -1] = -xp.flip(coef[1:]) / coef[0]
+
+ # non-symmetric eigenvalue problem is not in the spec but is available on e.g. torch
+ if hasattr(xp.linalg, 'eigvals'):
+ return xp.linalg.eigvals(a)
+ else:
+ import numpy as np
+ return xp.asarray(np.linalg.eigvals(np.asarray(a)))
+
+
+# https://github.com/numpy/numpy/blob/v2.1.0/numpy/lib/_function_base_impl.py#L1874-L1925
+def _trim_zeros(filt, trim='fb'):
+ first = 0
+ trim = trim.upper()
+ if 'F' in trim:
+ for i in filt:
+ if i != 0.:
+ break
+ else:
+ first = first + 1
+ last = filt.shape[0]
+ if 'B' in trim:
+ for i in filt[::-1]:
+ if i != 0.:
+ break
+ else:
+ last = last - 1
+ return filt[first:last]
+
+
+# For numpy arrays, use scipy.linalg.lstsq;
+# For other backends,
+# - use xp.linalg.lstsq, if available (cupy, torch, jax.numpy);
+# - otherwise manually compute pseudoinverse via SVD factorization
+def _lstsq(a, b, xp=None, rcond=None):
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+
+ if rcond is None:
+ rcond = xp.finfo(a.dtype).eps
+
+ if is_numpy(xp):
+ from scipy.linalg import lstsq as s_lstsq
+ return s_lstsq(a, b, cond=rcond)
+ elif lstsq_func := getattr(xp.linalg, "lstsq", None):
+ # cupy, torch, jax.numpy all have xp.linalg.lstsq
+ return lstsq_func(a, b, rcond=rcond)
+ else:
+ # unknown array library: LSQ solve via pseudoinverse
+ u, s, vt = xp.linalg.svd(a, full_matrices=False)
+
+ sing_val_mask = s > rcond
+ s = xpx.apply_where(sing_val_mask, (s,), lambda x: 1. / x, fill_value=0.)
+
+ sigma = xp.eye(s.shape[0]) * s # == np.diag(s)
+ x = vt.T @ sigma @ u.T @ b
+
+ rank = xp.count_nonzero(sing_val_mask)
+
+ # XXX actually compute residuals, when there's a use case
+ residuals = xp.asarray([])
+ return x, residuals, rank, s
+
+
+# ### Old-style routines ###
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L1232
+def _poly1d(c_or_r, *, xp):
+ """ Constructor of np.poly1d object from an array of coefficients (r=False)
+ """
+ c_or_r = xpx.atleast_nd(c_or_r, ndim=1, xp=xp)
+ if c_or_r.ndim > 1:
+ raise ValueError("Polynomial must be 1d only.")
+ c_or_r = _trim_zeros(c_or_r, trim='f')
+ if c_or_r.shape[0] == 0:
+ c_or_r = xp.asarray([0], dtype=c_or_r.dtype)
+ return c_or_r
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L702-L779
+def polyval(p, x, *, xp):
+ """ Old-style polynomial, `np.polyval`
+ """
+ p = xp.asarray(p)
+ x = xp.asarray(x)
+ y = xp.zeros_like(x)
+
+ # NB: cannot do `for pv in p` since array API iteration
+ # is only defined for 1D arrays.
+ for j in range(p.shape[0]):
+ y = y * x + p[j, ...]
+ return y
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L34-L157
+def poly(seq_of_zeros, *, xp):
+ # Only reproduce the 1D variant of np.poly
+ seq_of_zeros = xp.asarray(seq_of_zeros)
+ seq_of_zeros = xpx.atleast_nd(seq_of_zeros, ndim=1, xp=xp)
+
+ if seq_of_zeros.shape[0] == 0:
+ return xp.asarray(1.0, dtype=xp.real(seq_of_zeros).dtype)
+
+ # prefer np.convolve etc, if available
+ convolve_func = getattr(xp, 'convolve', None)
+ if convolve_func is None:
+ from scipy.signal import convolve as convolve_func
+
+ dt = seq_of_zeros.dtype
+ a = xp.ones((1,), dtype=dt)
+ one = xp.ones_like(seq_of_zeros[0])
+ for zero in seq_of_zeros:
+ a = convolve_func(a, xp.stack((one, -zero)), mode='full')
+
+ if xp.isdtype(a.dtype, 'complex floating'):
+ # if complex roots are all complex conjugates, the roots are real.
+ roots = xp.asarray(seq_of_zeros, dtype=xp.complex128)
+ if xp.all(xp.sort(xp.imag(roots)) == xp.sort(xp.imag(xp.conj(roots)))):
+ a = xp.asarray(xp.real(a), copy=True)
+
+ return a
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L912
+def polymul(a1, a2, *, xp):
+ a1, a2 = _poly1d(a1, xp=xp), _poly1d(a2, xp=xp)
+
+ # prefer np.convolve etc, if available
+ convolve_func = getattr(xp, 'convolve', None)
+ if convolve_func is None:
+ from scipy.signal import convolve as convolve_func
+
+ val = convolve_func(a1, a2)
+ return val
+
+
+# https://github.com/numpy/numpy/blob/v2.3.3/numpy/lib/_polynomial_impl.py#L459
+def polyfit(x, y, deg, *, xp, rcond=None):
+ # only reproduce the variant with full=False, w=None, cov=False
+ order = int(deg) + 1
+ x = xp.asarray(x)
+ y = xp.asarray(y)
+ x, y = xp_promote(x, y, force_floating=True, xp=xp)
+
+ # check arguments.
+ if deg < 0:
+ raise ValueError("expected deg >= 0")
+ if x.ndim != 1:
+ raise TypeError("expected 1D vector for x")
+ if xp_size(x) == 0:
+ raise TypeError("expected non-empty vector for x")
+ if y.ndim < 1 or y.ndim > 2:
+ raise TypeError("expected 1D or 2D array for y")
+ if x.shape[0] != y.shape[0]:
+ raise TypeError("expected x and y to have same length")
+
+ # set rcond
+ if rcond is None:
+ rcond = x.shape[0] * xp.finfo(x.dtype).eps
+
+ # set up least squares equation for powers of x: lhs = vander(x, order)
+ powers = xp.flip(xp.arange(order, dtype=x.dtype, device=xp_device(x)))
+ lhs = x[:, None] ** powers[None, :]
+
+ # scale lhs to improve condition number and solve
+ scale = xp.sqrt(xp.sum(lhs * lhs, axis=0))
+ lhs /= scale
+
+ c, _, rank, _ = _lstsq(lhs, y, rcond=rcond, xp=xp)
+ c = (c.T / scale).T # broadcast scale coefficients
+
+ # warn on rank reduction, which indicates an ill conditioned matrix
+ if rank != order:
+ msg = "Polyfit may be poorly conditioned"
+ warnings.warn(msg, RankWarning, stacklevel=2)
+
+ return c
+
+
+# ### New-style routines ###
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/polynomial/polynomial.py#L663
+def npp_polyval(x, c, *, xp, tensor=True):
+ if xp.isdtype(c.dtype, 'integral'):
+ c = xp.astype(c, xp_default_dtype(xp))
+
+ c = xpx.atleast_nd(c, ndim=1, xp=xp)
+ if isinstance(x, tuple | list):
+ x = xp.asarray(x)
+ if tensor:
+ c = xp.reshape(c, (c.shape + (1,)*x.ndim))
+
+ c0, _ = xp_promote(c[-1, ...], x, broadcast=True, xp=xp)
+ for i in range(2, c.shape[0] + 1):
+ c0 = c[-i, ...] + c0*x
+ return c0
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/polynomial/polynomial.py#L758-L842
+def npp_polyvalfromroots(x, r, *, xp, tensor=True):
+ r = xpx.atleast_nd(r, ndim=1, xp=xp)
+ # if r.dtype.char in '?bBhHiIlLqQpP':
+ # r = r.astype(np.double)
+
+ if isinstance(x, tuple | list):
+ x = xp.asarray(x)
+
+ if tensor:
+ r = xp.reshape(r, r.shape + (1,) * x.ndim)
+ elif x.ndim >= r.ndim:
+ raise ValueError("x.ndim must be < r.ndim when tensor == False")
+ return xp.prod(x - r, axis=0)
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_savitzky_golay.py b/.venv/lib/python3.12/site-packages/scipy/signal/_savitzky_golay.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c70d9794bbf936526438cd24cabe1d3c7ec5343
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_savitzky_golay.py
@@ -0,0 +1,391 @@
+from scipy._lib._util import float_factorial
+from scipy._external.array_api_compat import numpy as np_compat
+from scipy._lib._array_api import array_namespace, xp_swapaxes, xp_device
+import scipy._external.array_api_extra as xpx
+
+from scipy.ndimage import convolve1d # type: ignore[attr-defined]
+from scipy.signal import _polyutils as _pu
+from ._arraytools import axis_slice
+
+
+def savgol_coeffs(window_length, polyorder, deriv=0, delta=1.0, pos=None,
+ use="conv", *, xp=None, device=None):
+ """Compute the coefficients for a 1-D Savitzky-Golay FIR filter.
+
+ Parameters
+ ----------
+ window_length : int
+ The length of the filter window (i.e., the number of coefficients).
+ polyorder : int
+ The order of the polynomial used to fit the samples.
+ `polyorder` must be less than `window_length`.
+ deriv : int, optional
+ The order of the derivative to compute. This must be a
+ nonnegative integer. The default is 0, which means to filter
+ the data without differentiating.
+ delta : float, optional
+ The spacing of the samples to which the filter will be applied.
+ This is only used if deriv > 0.
+ pos : int or None, optional
+ If pos is not None, it specifies evaluation position within the
+ window. The default is the middle of the window.
+ use : str, optional
+ Either 'conv' or 'dot'. This argument chooses the order of the
+ coefficients. The default is 'conv', which means that the
+ coefficients are ordered to be used in a convolution. With
+ use='dot', the order is reversed, so the filter is applied by
+ dotting the coefficients with the data set.
+ xp : array_namespace, optional
+ Optional array namespace.
+ Should be compatible with the array API standard, or supported by
+ array-api-compat.
+ Default: ``numpy``
+ device : any
+ optional device specification for output. Should match one of the
+ supported device specifications in ``xp``.
+
+ Returns
+ -------
+ coeffs : 1-D ndarray
+ The filter coefficients.
+
+ See Also
+ --------
+ savgol_filter
+
+ Notes
+ -----
+ .. versionadded:: 0.14.0
+
+ References
+ ----------
+ A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by
+ Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8),
+ pp 1627-1639.
+ Jianwen Luo, Kui Ying, and Jing Bai. 2005. Savitzky-Golay smoothing and
+ differentiation filter for even number data. Signal Process.
+ 85, 7 (July 2005), 1429-1434.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import savgol_coeffs
+ >>> savgol_coeffs(5, 2)
+ array([-0.08571429, 0.34285714, 0.48571429, 0.34285714, -0.08571429])
+ >>> savgol_coeffs(5, 2, deriv=1)
+ array([ 2.00000000e-01, 1.00000000e-01, 2.07548111e-16, -1.00000000e-01,
+ -2.00000000e-01])
+
+ Note that use='dot' simply reverses the coefficients.
+
+ >>> savgol_coeffs(5, 2, pos=3)
+ array([ 0.25714286, 0.37142857, 0.34285714, 0.17142857, -0.14285714])
+ >>> savgol_coeffs(5, 2, pos=3, use='dot')
+ array([-0.14285714, 0.17142857, 0.34285714, 0.37142857, 0.25714286])
+ >>> savgol_coeffs(4, 2, pos=3, deriv=1, use='dot')
+ array([0.45, -0.85, -0.65, 1.05])
+
+ `x` contains data from the parabola x = t**2, sampled at
+ t = -1, 0, 1, 2, 3. `c` holds the coefficients that will compute the
+ derivative at the last position. When dotted with `x` the result should
+ be 6.
+
+ >>> x = np.array([1, 0, 1, 4, 9])
+ >>> c = savgol_coeffs(5, 2, pos=4, deriv=1, use='dot')
+ >>> c.dot(x)
+ 6.0
+ """
+
+ # An alternative method for finding the coefficients when deriv=0 is
+ # t = np.arange(window_length)
+ # unit = (t == pos).astype(int)
+ # coeffs = np.polyval(np.polyfit(t, unit, polyorder), t)
+ # The method implemented here is faster.
+
+ # To recreate the table of sample coefficients shown in the chapter on
+ # the Savitzy-Golay filter in the Numerical Recipes book, use
+ # window_length = nL + nR + 1
+ # pos = nL + 1
+ # c = savgol_coeffs(window_length, M, pos=pos, use='dot')
+
+ if polyorder >= window_length:
+ raise ValueError("polyorder must be less than window_length.")
+
+ halflen, rem = divmod(window_length, 2)
+
+ if pos is None:
+ if rem == 0:
+ pos = halflen - 0.5
+ else:
+ pos = halflen
+
+ if not (0 <= pos < window_length):
+ raise ValueError("pos must be nonnegative and less than "
+ "window_length.")
+
+ if use not in ['conv', 'dot']:
+ raise ValueError("`use` must be 'conv' or 'dot'")
+
+ # cf windows/_windows.py
+ xp = np_compat if xp is None else array_namespace(xp.empty(0))
+
+ if deriv > polyorder:
+ coeffs = xp.zeros(window_length, dtype=xp.float64, device=device)
+ return coeffs
+
+ # Form the design matrix A. The columns of A are powers of the integers
+ # from -pos to window_length - pos - 1. The powers (i.e., rows) range
+ # from 0 to polyorder. (That is, A is a vandermonde matrix, but not
+ # necessarily square.)
+ x = xp.arange(-pos, window_length - pos, dtype=xp.float64, device=device)
+
+ if use == "conv":
+ # Reverse so that result can be used in a convolution.
+ x = xp.flip(x)
+
+ order = xp.reshape(
+ xp.arange(polyorder + 1, dtype=xp.float64, device=device), (-1, 1)
+ )
+ A = x ** order
+
+ # y determines which order derivative is returned.
+ y = xp.zeros(polyorder + 1, dtype=xp.float64, device=device)
+ # The coefficient assigned to y[deriv] scales the result to take into
+ # account the order of the derivative and the sample spacing.
+ y = xpx.at(y, deriv).set(float_factorial(deriv) / (delta ** deriv))
+
+ # Find the least-squares solution of A*c = y
+ coeffs, _, _, _ = _pu._lstsq(A, y, xp=xp)
+
+ return coeffs
+
+
+def _polyder(p, m, *, xp):
+ """Differentiate polynomials represented with coefficients.
+
+ p must be a 1-D or 2-D array. In the 2-D case, each column gives
+ the coefficients of a polynomial; the first row holds the coefficients
+ associated with the highest power. m must be a nonnegative integer.
+ (numpy.polyder doesn't handle the 2-D case.)
+ """
+
+ if m == 0:
+ result = p
+ else:
+ n = p.shape[0]
+ if n <= m:
+ result = xp.zeros_like(p[:1, ...])
+ else:
+ dp = xp.asarray(p[:-m, ...], copy=True)
+ for k in range(m):
+ rng = xp.arange(
+ n - k - 1, m - k - 1, -1, dtype=p.dtype, device=xp_device(p)
+ )
+ dp *= xp.reshape(rng, (n - m,) + (1,) * (p.ndim - 1))
+ result = dp
+ return result
+
+
+def _fit_edge(x, window_start, window_stop, interp_start, interp_stop,
+ axis, polyorder, deriv, delta, y):
+ """
+ Given an N-d array `x` and the specification of a slice of `x` from
+ `window_start` to `window_stop` along `axis`, create an interpolating
+ polynomial of each 1-D slice, and evaluate that polynomial in the slice
+ from `interp_start` to `interp_stop`. Put the result into the
+ corresponding slice of `y`.
+ """
+ xp = array_namespace(x)
+
+ # Get the edge into a (window_length, -1) array.
+ x_edge = axis_slice(x, start=window_start, stop=window_stop, axis=axis)
+ if axis == 0 or axis == -x.ndim:
+ xx_edge = x_edge
+ swapped = False
+ else:
+ xx_edge = xp_swapaxes(x_edge, axis, 0, xp)
+ swapped = True
+ xx_edge = xp.reshape(xx_edge, (xx_edge.shape[0], -1))
+
+ # Fit the edges. poly_coeffs has shape (polyorder + 1, -1),
+ # where '-1' is the same as in xx_edge.
+ poly_coeffs = _pu.polyfit(
+ xp.arange(
+ 0, window_stop - window_start, dtype=x.dtype, device=xp_device(x)
+ ), xx_edge, polyorder, xp=xp
+ )
+
+ if deriv > 0:
+ poly_coeffs = _polyder(poly_coeffs, deriv, xp=xp)
+
+ # Compute the interpolated values for the edge.
+ i = xp.arange(
+ interp_start - window_start, interp_stop - window_start,
+ dtype=poly_coeffs.dtype, device=xp_device(poly_coeffs)
+ )
+ values = _pu.polyval(poly_coeffs, xp.reshape(i, (-1, 1)), xp=xp) / (delta ** deriv)
+
+ # Now put the values into the appropriate slice of y.
+ # First reshape values to match y.
+ shp = list(y.shape)
+ shp[0], shp[axis] = shp[axis], shp[0]
+ values = xp.reshape(values, (interp_stop - interp_start, *shp[1:]))
+ if swapped:
+ values = xp_swapaxes(values, 0, axis, xp)
+ # Get a view of the data to be replaced by values.
+ y_slice = [slice(None)] * y.ndim
+ y_slice[axis] = slice(interp_start, interp_stop)
+ y = xpx.at(y, tuple(y_slice)).set(values)
+
+ return y
+
+
+
+def _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y):
+ """
+ Use polynomial interpolation of x at the low and high ends of the axis
+ to fill in the halflen values in y.
+
+ This function just calls _fit_edge twice, once for each end of the axis.
+ """
+ halflen = window_length // 2
+ y = _fit_edge(x, 0, window_length, 0, halflen, axis,
+ polyorder, deriv, delta, y)
+ n = x.shape[axis]
+ y = _fit_edge(x, n - window_length, n, n - halflen, n, axis,
+ polyorder, deriv, delta, y)
+
+ return y
+
+
+def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0,
+ axis=-1, mode='interp', cval=0.0):
+ """ Apply a Savitzky-Golay filter to an array.
+
+ This is a 1-D filter. If `x` has dimension greater than 1, `axis`
+ determines the axis along which the filter is applied.
+
+ Parameters
+ ----------
+ x : array_like
+ The data to be filtered. If `x` is not a single or double precision
+ floating point array, it will be converted to type ``numpy.float64``
+ before filtering.
+ window_length : int
+ The length of the filter window (i.e., the number of coefficients).
+ If `mode` is 'interp', `window_length` must be less than or equal
+ to the size of `x`.
+ polyorder : int
+ The order of the polynomial used to fit the samples.
+ `polyorder` must be less than `window_length`.
+ deriv : int, optional
+ The order of the derivative to compute. This must be a
+ nonnegative integer. The default is 0, which means to filter
+ the data without differentiating.
+ delta : float, optional
+ The spacing of the samples to which the filter will be applied.
+ This is only used if deriv > 0. Default is 1.0.
+ axis : int, optional
+ The axis of the array `x` along which the filter is to be applied.
+ Default is -1.
+ mode : str, optional
+ Must be 'mirror', 'constant', 'nearest', 'wrap' or 'interp'. This
+ determines the type of extension to use for the padded signal to
+ which the filter is applied. When `mode` is 'constant', the padding
+ value is given by `cval`. See the Notes for more details on 'mirror',
+ 'constant', 'wrap', and 'nearest'.
+ When the 'interp' mode is selected (the default), no extension
+ is used. Instead, a degree `polyorder` polynomial is fit to the
+ last `window_length` values of the edges, and this polynomial is
+ used to evaluate the last `window_length // 2` output values.
+ cval : scalar, optional
+ Value to fill past the edges of the input if `mode` is 'constant'.
+ Default is 0.0.
+
+ Returns
+ -------
+ y : ndarray, same shape as `x`
+ The filtered data.
+
+ See Also
+ --------
+ savgol_coeffs
+
+ Notes
+ -----
+ Details on the `mode` options:
+
+ - 'mirror':
+ Repeats the values at the edges in reverse order. The value
+ closest to the edge is not included.
+ - 'nearest':
+ The extension contains the nearest input value.
+ - 'constant':
+ The extension contains the value given by the `cval` argument.
+ - 'wrap':
+ The extension contains the values from the other end of the array.
+
+ For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and
+ `window_length` is 7, the following shows the extended data for
+ the various `mode` options (assuming `cval` is 0)::
+
+ mode | Ext | Input | Ext
+ -----------+---------+------------------------+---------
+ 'mirror' | 4 3 2 | 1 2 3 4 5 6 7 8 | 7 6 5
+ 'nearest' | 1 1 1 | 1 2 3 4 5 6 7 8 | 8 8 8
+ 'constant' | 0 0 0 | 1 2 3 4 5 6 7 8 | 0 0 0
+ 'wrap' | 6 7 8 | 1 2 3 4 5 6 7 8 | 1 2 3
+
+ .. versionadded:: 0.14.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import savgol_filter
+ >>> np.set_printoptions(precision=2) # For compact display.
+ >>> x = np.array([2, 2, 5, 2, 1, 0, 1, 4, 9])
+
+ Filter with a window length of 5 and a degree 2 polynomial. Use
+ the defaults for all other parameters.
+
+ >>> savgol_filter(x, 5, 2)
+ array([1.66, 3.17, 3.54, 2.86, 0.66, 0.17, 1. , 4. , 9. ])
+
+ Note that the last five values in x are samples of a parabola, so
+ when mode='interp' (the default) is used with polyorder=2, the last
+ three values are unchanged. Compare that to, for example,
+ `mode='nearest'`:
+
+ >>> savgol_filter(x, 5, 2, mode='nearest')
+ array([1.74, 3.03, 3.54, 2.86, 0.66, 0.17, 1. , 4.6 , 7.97])
+
+ """
+ if mode not in ["mirror", "constant", "nearest", "interp", "wrap"]:
+ raise ValueError("mode must be 'mirror', 'constant', 'nearest' "
+ "'wrap' or 'interp'.")
+
+ xp = array_namespace(x)
+ x = xp.asarray(x)
+ # Ensure that x is either single or double precision floating point.
+ if x.dtype != xp.float64 and x.dtype != xp.float32:
+ x = xp.astype(x, xp.float64)
+
+ coeffs = savgol_coeffs(
+ window_length, polyorder, deriv=deriv, delta=delta, xp=xp, device=xp_device(x)
+ )
+
+ if mode == "interp":
+ if window_length > x.shape[axis]:
+ raise ValueError("If mode is 'interp', window_length must be less "
+ "than or equal to the size of x.")
+
+ # Do not pad. Instead, for the elements within `window_length // 2`
+ # of the ends of the sequence, use the polynomial that is fitted to
+ # the last `window_length` elements.
+ y = convolve1d(x, coeffs, axis=axis, mode="constant")
+ y = _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y)
+ else:
+ # Any mode other than 'interp' is passed on to ndimage.convolve1d.
+ y = convolve1d(x, coeffs, axis=axis, mode=mode, cval=cval)
+
+ return y
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_short_time_fft.py b/.venv/lib/python3.12/site-packages/scipy/signal/_short_time_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..533b25edd1e1c0985ccd0fd4b7cb7e6c657f5a2b
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_short_time_fft.py
@@ -0,0 +1,2291 @@
+"""Implementation of an FFT-based Short-time Fourier Transform. """
+
+# Implementation Notes for this file (as of 2025-08)
+# --------------------------------------------------
+# * Since the method `stft` and `istft` have identical names as the legacy
+# functions in the signal module, referencing them as HTML link in the
+# docstrings has to be done by an explicit `~ShortTimeFFT.stft` instead of an
+# ambiguous `stft` (The ``~`` hides the class / module name).
+# * The HTML documentation currently renders each method/property on a separate
+# page without reference to the parent class. Thus, a link to `ShortTimeFFT`
+# was added to the "See Also" section of each method/property. These links
+# can be removed, when SciPy updates ``pydata-sphinx-theme`` to >= 0.13.3
+# (currently 0.9). Consult Issue 18512 and PR 16660 for further details.
+
+
+# Linter does not allow to import ``Generator`` from ``typing`` module:
+from collections.abc import Generator, Callable
+from functools import partial, cached_property
+from types import GenericAlias
+from typing import get_args, Literal
+
+import numpy as np
+
+import scipy.fft as fft_lib
+from scipy.signal._signaltools import detrend
+from scipy.signal.windows import get_window
+
+__all__ = ['closest_STFT_dual_window', 'ShortTimeFFT']
+
+
+#: Allowed values for parameter `padding` of method `ShortTimeFFT.stft()`:
+PAD_TYPE = Literal['zeros', 'edge', 'even', 'odd']
+
+#: Allowed values for property `ShortTimeFFT.fft_mode`:
+FFT_MODE_TYPE = Literal['twosided', 'centered', 'onesided', 'onesided2X']
+
+
+def _calc_dual_canonical_window(win: np.ndarray, hop: int) -> np.ndarray:
+ """Calculate canonical dual window for 1d window `win` and a time step
+ of `hop` samples.
+
+ A ``ValueError`` is raised if the inversion fails.
+
+ This is a separate function not a method, since it is also used in the
+ class method ``ShortTimeFFT.from_dual()``.
+ """
+ if hop > len(win):
+ raise ValueError(f"{hop=} is larger than window length of {len(win)}" +
+ " => STFT not invertible!")
+ if issubclass(win.dtype.type, np.integer):
+ raise ValueError("Parameter 'win' cannot be of integer type, but " +
+ f"{win.dtype=} => STFT not invertible!")
+ # The calculation of `relative_resolution` does not work for ints.
+ # Furthermore, `win / DD` casts the integers away, thus an implicit
+ # cast is avoided, which can always cause confusion when using 32-Bit
+ # floats.
+
+ w2 = win.real**2 + win.imag**2 # win*win.conj() does not ensure w2 is real
+ DD = w2.copy()
+ for k_ in range(hop, len(win), hop):
+ DD[k_:] += w2[:-k_]
+ DD[:-k_] += w2[k_:]
+
+ # check DD > 0:
+ relative_resolution = np.finfo(win.dtype).resolution * max(DD)
+ if not np.all(DD >= relative_resolution):
+ raise ValueError("Short-time Fourier Transform not invertible!")
+
+ return win / DD
+
+
+def closest_STFT_dual_window(win: np.ndarray, hop: int,
+ desired_dual: np.ndarray | None = None, *,
+ scaled: bool = True) \
+ -> tuple[np.ndarray, float | complex]:
+ r"""Calculate the STFT dual window of a given window closest to a desired dual
+ window.
+
+ For a given short-time Fourier transform window `win` incremented by `hop`
+ samples, the dual window is calculated, which minimizes
+ ``abs(dual_win - desired_dual)**2`` when `scaled` is ``False``. For `scaled`
+ set to ``True``, ``abs(alpha*dual_win - desired_dual)**2`` is minimized with
+ `alpha` being the optimal scaling factor.
+ A ``ValueError`` is raised if no valid dual window can be determined.
+
+
+ Parameters
+ ----------
+ win : np.ndarray
+ The window must be a real- or complex-valued 1d array.
+ hop : int
+ The increment in samples by which the window is shifted in each step.
+ desired_dual : np.ndarray | None
+ The desired dual window must be a 1d array of the same length as `win`.
+ If set to ``None`` (default), then `desired_dual` is assumed to be the
+ rectangular window, i.e., ``np.ones_like(win)``.
+ scaled : bool
+ If set (default), the closest scaled version instead of closest dual window
+ is calculated.
+
+ Returns
+ -------
+ dual_win : np.ndarray
+ A dual window of ``alpha*win`` (with hop interval `hop`), which is closest
+ to `desired_dual`. Note that the dual window of `win` is `dual_win/alpha`
+ and that the dual window of `dual_win` is `alpha*win`.
+ `dual_win` has the same shape as `win` and `desired_win`.
+ alpha : float | complex
+ Scale factor for `win`. It is always one if `scaled` is set to ``False``.
+
+ Notes
+ -----
+ For a given window and `hop` interval, all possible dual windows are expressed
+ by the `hop` linear conditions of Eq. :math:numref:`eq_STFT_AllDualWinsCond` in
+ the :ref:`tutorial_stft` section of the :ref:`user_guide`. Hence, decreasing
+ `hop`, increases the number of degrees of freedom of the set of all possible
+ dual windows, improving the ability to better approximate a `desired_dual`.
+
+ This function can also be used to determine windows which fulfill the
+ so-called "Constant OverLap Add" (COLA) condition [1]_. It states that summing
+ all touching window values at any given sample position results in the same
+ constant :math:`\alpha`. Eq. :math:numref:`eq_STFT_AllDualWinsCond` shows that
+ this is equal to having a rectangular dual window, i.e., the dual being
+ ``alpha*np.ones(m)``.
+
+ Some examples of windows that satisfy COLA (taken from [2]_):
+
+ - Rectangular window at overlap of 0, 1/2, 2/3, 3/4, ...
+ - Bartlett window at overlap of 1/2, 3/4, 5/6, ...
+ - Hann window at 1/2, 2/3, 3/4, ...
+ - Any Blackman family window at 2/3 overlap
+ - Any window with ``hop=1``
+
+ References
+ ----------
+ .. [1] Julius O. Smith III, "Spectral Audio Signal Processing",
+ online book, 2011, https://www.dsprelated.com/freebooks/sasp/
+ .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and spectral density
+ estimation by the Discrete Fourier transform (DFT), including a
+ comprehensive list of window functions and some new at-top windows",
+ 2002, http://hdl.handle.net/11858/00-001M-0000-0013-557A-5
+
+ Examples
+ --------
+ Let's show that a Bartlett window with 75% overlap fulfills the COLA condition:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import closest_STFT_dual_window, windows
+ ...
+ >>> m = 24
+ >>> win, w_rect = windows.bartlett(m, sym=False), np.ones(m)
+ >>> d_win, alpha = closest_STFT_dual_window(win, m//4, w_rect, scaled=True)
+ >>> print(f"COLA: {np.allclose(d_win, w_rect*alpha)}, {alpha = :g}")
+ COLA: True, alpha = 0.5
+
+ We can also determine for which hop intervals the COLA condition is fulfilled:
+
+ >>> hops, deviations, alphas = np.arange(1, 16, dtype=int), [], []
+ >>> for h_ in hops:
+ ... w_cola, alpha = closest_STFT_dual_window(w_rect, h_, win, scaled=True)
+ ... deviations.append(np.linalg.norm(w_cola - win*alpha))
+ ... alphas.append(alpha)
+ ...
+ >>> fg0, (ax0, ax1) = plt.subplots(2, 1, sharex='all', tight_layout=True)
+ >>> ax0.set_title(f"COLA Window closest to a {m}-Sample Bartlett Window")
+ >>> ax0.set(ylabel=r"$||w_\text{cola}-\alpha w||$", xlim=(0, hops[-1]-.5))
+ >>> ax1.set(xlabel="Hop Interval", ylabel=r"Scaling factor $\alpha$",
+ ... ylim=(0, 1.25))
+ >>> ax0.plot(hops, deviations, 'C0.-')
+ >>> ax1.plot(hops, alphas, 'C1.-')
+ >>> for ax_ in (ax0, ax1):
+ ... ax_.grid()
+ >>> plt.show()
+
+ The lower plot shows the calculated scaling factor :math:`\alpha` for different
+ `hops` whereas the upper displays the :math:`L^2`-norm of the difference
+ between the scaled Bartlett window and the calculated window. Since for `hops`
+ 1 to 4 as well as for 6 and 12 the :math:`L^2`-norm of the difference is
+ practically zero, the COLA condition is fulfilled for those.
+
+ See Also
+ --------
+ ShortTimeFFT: Short-time Fourier transform which is able to utilize a dual
+ window for calculating the inverse.
+ ShortTimeFFT.from_win_equals_dual: Create instance where the window and its
+ dual are equal.
+
+ """
+ if desired_dual is None: # default is rectangular window
+ desired_dual = np.ones_like(win)
+ if not (win.ndim == 1 and win.shape == desired_dual.shape):
+ raise ValueError("Parameters `win` and `desired_dual` are not 1d arrays of " +
+ f"equal length ({win.shape=}, {desired_dual.shape=})!")
+ if not all(np.isfinite(win)):
+ raise ValueError("Parameter win must have finite entries!")
+ if not all(np.isfinite(desired_dual)):
+ raise ValueError("Parameter desired_dual must have finite entries!")
+ if not (1 <= hop <= len(win) and isinstance(hop, int | np.integer)):
+ raise ValueError(f"Parameter {hop=} is not an integer between 1 and " +
+ f"{len(win)=}!")
+
+ w_d = _calc_dual_canonical_window(win, hop)
+ wdd = win.conjugate() * desired_dual
+ q_d = wdd.copy()
+ for k_ in range(hop, len(win), hop):
+ q_d[k_:] += wdd[:-k_]
+ q_d[:-k_] += wdd[k_:]
+ q_d = w_d * q_d
+
+ if not scaled:
+ return w_d + desired_dual - q_d, 1.
+
+ numerator = q_d.conjugate().T @ w_d
+ denominator = q_d.T.real @ q_d.real + q_d.T.imag @ q_d.imag # always >= 0
+ if not (abs(numerator) > 0 and denominator > np.finfo(w_d.dtype).resolution):
+ raise ValueError(
+ "Unable to calculate scaled closest dual window due to numerically " +
+ "unstable scaling factor! Try setting parameter `scaled` to False.")
+ alpha = numerator / denominator
+ return w_d + alpha * (desired_dual - q_d), alpha
+
+
+# noinspection PyShadowingNames
+class ShortTimeFFT:
+ r"""Provide a parametrized discrete Short-time Fourier transform (stft)
+ and its inverse (istft).
+
+ .. currentmodule:: scipy.signal.ShortTimeFFT
+
+ The `~ShortTimeFFT.stft` calculates sequential FFTs by sliding a
+ window (`win`) over an input signal by `hop` increments. It can be used to
+ quantify the change of the spectrum over time.
+
+ The `~ShortTimeFFT.stft` is represented by a complex-valued matrix S[q,p]
+ where the p-th column represents an FFT with the window centered at the
+ time t[p] = p * `delta_t` = p * `hop` * `T` where `T` is the sampling
+ interval of the input signal. The q-th row represents the values at the
+ frequency f[q] = q * `delta_f` with `delta_f` = 1 / (`mfft` * `T`) being
+ the bin width of the FFT.
+
+ The inverse STFT `~ShortTimeFFT.istft` is calculated by reversing the steps
+ of the STFT: Take the IFFT of the p-th slice of S[q,p] and multiply the
+ result with the so-called dual window (see `dual_win`). Shift the result by
+ p * `delta_t` and add the result to previous shifted results to reconstruct
+ the signal. If only the dual window is known and the STFT is invertible,
+ `from_dual` can be used to instantiate this class.
+
+ By default, the so-called canonical dual window is used. It is the window with
+ minimal energy among all possible dual windows. `from_win_equals_dual` and
+ `~scipy.signal.closest_STFT_dual_window` provide means for utilizing alterantive
+ dual windows. Note that `win` is also always a dual window of `dual_win`.
+
+ Due to the convention of time t = 0 being at the first sample of the input
+ signal, the STFT values typically have negative time slots. Hence,
+ negative indexes like `p_min` or `k_min` do not indicate counting
+ backwards from an array's end like in standard Python indexing but being
+ left of t = 0.
+
+ More detailed information can be found in the :ref:`tutorial_stft`
+ section of the :ref:`user_guide`.
+
+ Note that all parameters of the initializer, except `scale_to` (which uses
+ `scaling`) have identical named attributes.
+
+ Parameters
+ ----------
+ win : np.ndarray
+ The window must be a real- or complex-valued 1d array.
+ hop : int
+ The increment in samples, by which the window is shifted in each step.
+ fs : float
+ Sampling frequency of input signal and window. Its relation to the
+ sampling interval `T` is ``T = 1 / fs``.
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
+ Mode of FFT to be used (default 'onesided').
+ See property `fft_mode` for details.
+ mfft : int | None
+ Length of the FFT used, if a zero padded FFT is desired.
+ If ``None`` (default), the length of the window `win` is used.
+ dual_win : np.ndarray | None
+ The dual window of `win`. If set to ``None``, it is calculated if
+ needed.
+ scale_to : 'magnitude', 'psd' | None
+ If not ``None`` (default) the window function is scaled, so each STFT
+ column represents either a 'magnitude' or a power spectral density
+ ('psd') spectrum. This parameter sets the property `scaling` to the
+ same value. See method `scale_to` for details.
+ phase_shift : int | None
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
+ frequency `f`. The default value of 0 ensures that there is no phase shift
+ on the zeroth slice (in which t=0 is centered). See property
+ `phase_shift` for more details.
+
+ Notes
+ -----
+ A typical STFT application is the creation of various types of time-frequency
+ plots, often subsumed under the term "spectrogram". Note that this term is also
+ used to explecitly refer to the absolute square of a STFT [11]_, as done in
+ :meth:`spectrogram`.
+
+ The STFT can also be used for filtering and filter banks as discussed in [12]_.
+
+
+ References
+ ----------
+ .. [11] Karlheinz Gröchenig: "Foundations of Time-Frequency Analysis",
+ Birkhäuser Boston 2001, `10.1007/978-1-4612-0003-1`
+ .. [12] Julius O. Smith III, "Spectral Audio Signal Processing", online book, 2011,
+ https://www.dsprelated.com/freebooks/sasp/
+
+
+ Examples
+ --------
+ The following example shows the magnitude of the STFT of a sine with
+ varying frequency :math:`f_i(t)` (marked by a red dashed line in the plot):
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import ShortTimeFFT
+ >>> from scipy.signal.windows import gaussian
+ ...
+ >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal
+ >>> t_x = np.arange(N) * T_x # time indexes for signal
+ >>> f_i = 1 * np.arctan((t_x - t_x[N // 2]) / 2) + 5 # varying frequency
+ >>> x = np.sin(2*np.pi*np.cumsum(f_i)*T_x) # the signal
+
+ The utilized Gaussian window is 50 samples or 2.5 s long. The parameter
+ ``mfft=200`` in `ShortTimeFFT` causes the spectrum to be oversampled
+ by a factor of 4:
+
+ >>> g_std = 8 # standard deviation for Gaussian window in samples
+ >>> w = gaussian(50, std=g_std, sym=True) # symmetric Gaussian window
+ >>> SFT = ShortTimeFFT(w, hop=10, fs=1/T_x, mfft=200, scale_to='magnitude')
+ >>> Sx = SFT.stft(x) # perform the STFT
+
+ In the plot, the time extent of the signal `x` is marked by vertical dashed
+ lines. Note that the SFT produces values outside the time range of `x`. The
+ shaded areas on the left and the right indicate border effects caused
+ by the window slices in that area not fully being inside time range of
+ `x`:
+
+ >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit
+ >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot
+ >>> ax1.set_title(rf"STFT ({SFT.m_num*SFT.T:g}$\,s$ Gaussian window, " +
+ ... rf"$\sigma_t={g_std*SFT.T}\,$s)")
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " +
+ ... rf"$\Delta t = {SFT.delta_t:g}\,$s)",
+ ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " +
+ ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)",
+ ... xlim=(t_lo, t_hi))
+ ...
+ >>> im1 = ax1.imshow(abs(Sx), origin='lower', aspect='auto',
+ ... extent=SFT.extent(N), cmap='viridis')
+ >>> ax1.plot(t_x, f_i, 'r--', alpha=.5, label='$f_i(t)$')
+ >>> fig1.colorbar(im1, label="Magnitude $|S_x(t, f)|$")
+ ...
+ >>> # Shade areas where window slices stick out to the side:
+ >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T),
+ ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]:
+ ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.2)
+ >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line:
+ ... ax1.axvline(t_, color='y', linestyle='--', alpha=0.5)
+ >>> ax1.legend()
+ >>> fig1.tight_layout()
+ >>> plt.show()
+
+ Reconstructing the signal with the `~ShortTimeFFT.istft` is
+ straightforward, but note that the length of `x1` should be specified,
+ since the STFT length increases in `hop` steps:
+
+ >>> SFT.invertible # check if invertible
+ True
+ >>> x1 = SFT.istft(Sx, k1=N)
+ >>> np.allclose(x, x1)
+ True
+
+ It is possible to calculate the STFT of signal parts:
+
+ >>> N2 = SFT.nearest_k_p(N // 2)
+ >>> Sx0 = SFT.stft(x[:N2])
+ >>> Sx1 = SFT.stft(x[N2:])
+
+ When assembling sequential STFT parts together, the overlap needs to be
+ considered:
+
+ >>> p0_ub = SFT.upper_border_begin(N2)[1] - SFT.p_min
+ >>> p1_le = SFT.lower_border_end[1] - SFT.p_min
+ >>> Sx01 = np.hstack((Sx0[:, :p0_ub],
+ ... Sx0[:, p0_ub:] + Sx1[:, :p1_le],
+ ... Sx1[:, p1_le:]))
+ >>> np.allclose(Sx01, Sx) # Compare with SFT of complete signal
+ True
+
+ It is also possible to calculate the `itsft` for signal parts:
+
+ >>> y_p = SFT.istft(Sx, N//3, N//2)
+ >>> np.allclose(y_p, x[N//3:N//2])
+ True
+
+ """
+ # immutable attributes (only have getters but no setters):
+ _win: np.ndarray # window
+ _dual_win: np.ndarray | None = None # canonical dual window
+ _hop: int # Step of STFT in number of samples
+
+ # mutable attributes:
+ _fs: float # sampling frequency of input signal and window
+ _fft_mode: FFT_MODE_TYPE = 'onesided' # Mode of FFT to use
+ _mfft: int # length of FFT used - defaults to len(win)
+ _scaling: Literal['magnitude', 'psd', 'unitary'] | None = None # Scaling of _win
+ _phase_shift: int | None # amount to shift phase of FFT in samples
+
+ # attributes for caching calculated values:
+ _fac_mag: float | None = None
+ _fac_psd: float | None = None
+ _lower_border_end: tuple[int, int] | None = None
+ # The following tuples store parameter(s) and return value(s) of methods for caching
+ # (initialized with invalid parameters; should only be accessed by atomic
+ # read/writes to alleviate potential multithreading issues):
+ _cache_post_padding: tuple[int, tuple[int, int]] = -1, (0, 0)
+ _cache_upper_border_begin: tuple[int, tuple[int, int]] = -1, (0, 0)
+ _cache_t: tuple[tuple[int, int | None, int | None, int, float], np.ndarray] = \
+ (-1, None, None, 0, 0.), np.ndarray([])
+ _cache_f: tuple[tuple[FFT_MODE_TYPE, int, float], np.ndarray] = \
+ ('onesided', -1, 1.), np.ndarray([])
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__: classmethod = classmethod(GenericAlias)
+
+ def __init__(self, win: np.ndarray, hop: int, fs: float, *,
+ fft_mode: FFT_MODE_TYPE = 'onesided',
+ mfft: int | None = None,
+ dual_win: np.ndarray | None = None,
+ scale_to: Literal['magnitude', 'psd'] | None = None,
+ phase_shift: int | None = 0):
+ if not (win.ndim == 1 and win.size > 0):
+ raise ValueError(f"Parameter win must be 1d, but {win.shape=}!")
+ if not all(np.isfinite(win)):
+ raise ValueError("Parameter win must have finite entries!")
+ if not (hop >= 1 and isinstance(hop, int | np.integer)):
+ raise ValueError(f"Parameter {hop=} is not an integer >= 1!")
+
+ self._win, self._hop, self.fs = win, hop, fs
+ self.win.setflags(write=False)
+ self.mfft = len(win) if mfft is None else mfft
+
+ if dual_win is not None:
+ if dual_win.shape != win.shape:
+ raise ValueError(f"{dual_win.shape=} must equal {win.shape=}!")
+ if not all(np.isfinite(dual_win)):
+ raise ValueError("Parameter dual_win must be a finite array!")
+ dual_win.setflags(write=False)
+ self._dual_win = dual_win # needs to be set before scaling
+
+ if scale_to is not None: # needs to be set before fft_mode
+ self.scale_to(scale_to)
+
+ self.fft_mode, self.phase_shift = fft_mode, phase_shift
+
+ @classmethod
+ def from_dual(cls, dual_win: np.ndarray, hop: int, fs: float, *,
+ fft_mode: FFT_MODE_TYPE = 'onesided',
+ mfft: int | None = None,
+ scale_to: Literal['magnitude', 'psd'] | None = None,
+ phase_shift: int | None = 0):
+ r"""Instantiate a `ShortTimeFFT` by only providing a dual window.
+
+ If an STFT is invertible, it is possible to calculate the window `win`
+ from a given dual window `dual_win`. All other parameters have the
+ same meaning as in the initializer of `ShortTimeFFT`.
+
+ As explained in the :ref:`tutorial_stft` section of the
+ :ref:`user_guide`, an invertible STFT can be interpreted as series
+ expansion of time-shifted and frequency modulated dual windows. E.g.,
+ the series coefficient S[q,p] belongs to the term, which shifted
+ `dual_win` by p * `delta_t` and multiplied it by
+ exp( 2 * j * pi * t * q * `delta_f`).
+
+
+ Examples
+ --------
+ The following example discusses decomposing a signal into time- and
+ frequency-shifted Gaussians. A Gaussian with standard deviation of
+ one made up of 51 samples will be used:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import ShortTimeFFT
+ >>> from scipy.signal.windows import gaussian
+ ...
+ >>> T, N = 0.1, 51
+ >>> d_win = gaussian(N, std=1/T, sym=True) # symmetric Gaussian window
+ >>> t = T * (np.arange(N) - N//2)
+ ...
+ >>> fg1, ax1 = plt.subplots()
+ >>> ax1.set_title(r"Dual Window: Gaussian with $\sigma_t=1$")
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)",
+ ... xlim=(t[0], t[-1]), ylim=(0, 1.1*np.max(d_win)))
+ >>> ax1.plot(t, d_win, 'C0-')
+
+ The following plot with the overlap of 41, 11 and 2 samples show how
+ the `hop` interval affects the shape of the window `win`:
+
+ >>> fig2, axx = plt.subplots(3, 1, sharex='all')
+ ...
+ >>> axx[0].set_title(r"Windows for hop$\in\{10, 40, 49\}$")
+ >>> for c_, h_ in enumerate([10, 40, 49]):
+ ... SFT = ShortTimeFFT.from_dual(d_win, h_, 1/T)
+ ... axx[c_].plot(t + h_ * T, SFT.win, 'k--', alpha=.3, label=None)
+ ... axx[c_].plot(t - h_ * T, SFT.win, 'k:', alpha=.3, label=None)
+ ... axx[c_].plot(t, SFT.win, f'C{c_+1}',
+ ... label=r"$\Delta t=%0.1f\,$s" % SFT.delta_t)
+ ... axx[c_].set_ylim(0, 1.1*max(SFT.win))
+ ... axx[c_].legend(loc='center')
+ >>> axx[-1].set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)",
+ ... xlim=(t[0], t[-1]))
+ >>> plt.show()
+
+ Beside the window `win` centered at t = 0 the previous (t = -`delta_t`)
+ and following window (t = `delta_t`) are depicted. It can be seen that
+ for small `hop` intervals, the window is compact and smooth, having a
+ good time-frequency concentration in the STFT. For the large `hop`
+ interval of 4.9 s, the window has small values around t = 0, which are
+ not covered by the overlap of the adjacent windows, which could lead to
+ numeric inaccuracies. Furthermore, the peaky shape at the beginning and
+ the end of the window points to a higher bandwidth, resulting in a
+ poorer time-frequency resolution of the STFT.
+ Hence, the choice of the `hop` interval will be a compromise between
+ a time-frequency resolution and memory requirements demanded by small
+ `hop` sizes.
+
+ See Also
+ --------
+ from_window: Create instance by wrapping `get_window`.
+ ShortTimeFFT: Create instance using standard initializer.
+ """
+ win = _calc_dual_canonical_window(dual_win, hop)
+ return cls(win=win, hop=hop, fs=fs, fft_mode=fft_mode, mfft=mfft,
+ dual_win=dual_win, scale_to=scale_to,
+ phase_shift=phase_shift)
+
+ @classmethod
+ def from_window(cls, win_param: str | tuple | float,
+ fs: float, nperseg: int, noverlap: int, *,
+ symmetric_win: bool = False,
+ fft_mode: FFT_MODE_TYPE = 'onesided',
+ mfft: int | None = None,
+ scale_to: Literal['magnitude', 'psd'] | None = None,
+ phase_shift: int | None = 0):
+ """Instantiate `ShortTimeFFT` by using `get_window`.
+
+ The method `get_window` is used to create a window of length
+ `nperseg`. The parameter names `noverlap`, and `nperseg` are used here,
+ since they more inline with other classical STFT libraries.
+
+ Parameters
+ ----------
+ win_param: Union[str, tuple, float],
+ Parameters passed to `get_window`. For windows with no parameters,
+ it may be a string (e.g., ``'hann'``), for parametrized windows a
+ tuple, (e.g., ``('gaussian', 2.)``) or a single float specifying
+ the shape parameter of a kaiser window (i.e. ``4.`` and
+ ``('kaiser', 4.)`` are equal. See `get_window` for more details.
+ fs : float
+ Sampling frequency of input signal. Its relation to the
+ sampling interval `T` is ``T = 1 / fs``.
+ nperseg: int
+ Window length in samples, which corresponds to the `m_num`.
+ noverlap: int
+ Window overlap in samples. It relates to the `hop` increment by
+ ``hop = npsereg - noverlap``.
+ symmetric_win: bool
+ If ``True`` then a symmetric window is generated, else a periodic window is
+ generated (default). Though symmetric windows seem for most applications to
+ be more sensible, the default of a periodic windows was chosen to
+ correspond to the default of `get_window`. This parameter is ignored, if
+ the window name in the `window` parameter has a suffix ``'_periodic'`` or
+ ``'_symmetric'`` appended to it (e.g., ``'hann_symmetric'``).
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
+ Mode of FFT to be used (default 'onesided').
+ See property `fft_mode` for details.
+ mfft: int | None
+ Length of the FFT used, if a zero padded FFT is desired.
+ If ``None`` (default), the length of the window `win` is used.
+ scale_to : 'magnitude', 'psd' | None
+ If not ``None`` (default) the window function is scaled, so each
+ STFT column represents either a 'magnitude' or a power spectral
+ density ('psd') spectrum. This parameter sets the property
+ `scaling` to the same value. See method `scale_to` for details.
+ phase_shift : int | None
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
+ frequency `f`. The default value 0 ensures that there is no phase
+ shift on the zeroth slice (in which t=0 is centered). See property
+ `phase_shift` for more details.
+
+ Examples
+ --------
+ The following instances ``SFT0`` and ``SFT1`` are equivalent:
+
+ >>> from scipy.signal import ShortTimeFFT, get_window
+ >>> nperseg = 9 # window length
+ >>> w = get_window(('gaussian_periodic', 2.), nperseg)
+ >>> fs = 128 # sampling frequency
+ >>> hop = 3 # increment of STFT time slice
+ >>> SFT0 = ShortTimeFFT(w, hop, fs=fs)
+ >>> SFT1 = ShortTimeFFT.from_window(('gaussian', 2.), fs, nperseg,
+ ... noverlap=nperseg-hop)
+
+ See Also
+ --------
+ scipy.signal.get_window: Return a window of a given length and type.
+ from_dual: Create instance using dual window.
+ ShortTimeFFT: Create instance using standard initializer.
+ """
+ win = get_window(win_param, nperseg, fftbins=not symmetric_win)
+ return cls(win, hop=nperseg-noverlap, fs=fs, fft_mode=fft_mode,
+ mfft=mfft, scale_to=scale_to, phase_shift=phase_shift)
+
+ @classmethod
+ def from_win_equals_dual(
+ cls, desired_win: np.ndarray, hop: int, fs: float, *,
+ fft_mode: FFT_MODE_TYPE = 'onesided', mfft: int | None = None,
+ scale_to: Literal['magnitude', 'psd', 'unitary'] | None = None,
+ phase_shift: int | None = 0):
+ r"""Create instance where the window and its dual are equal up to a
+ scaling factor.
+
+ An instance is created were window and dual window are equal as well as being
+ closest to the parameter `desired_win` in the least-squares sense, i.e.,
+ minimizing ``abs(win-desired_win)**2``. Hence, `win` has the same length as
+ `desired_win`. Then a scaling factor is applied accoring to the `scale_to`
+ parameter.
+
+ All other parameters have the identical meaning as in the initializer.
+
+ To be able to calculate a valid window, `desired_win` needs to have a valid
+ dual STFT window for the given `hop` interval.
+ If this is not the case, a ``ValueError`` is raised.
+
+ Parameters
+ ----------
+ desired_win : np.ndarray
+ A real-valued or complex-valued 1d array containing the sample of the
+ desired window.
+ hop : int
+ The increment in samples, by which the window is shifted in each step.
+ fs : float
+ Sampling frequency of input signal and window. Its relation to the
+ sampling interval `T` is ``T = 1 / fs``.
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
+ Mode of FFT to be used (default 'onesided').
+ See property `fft_mode` for details.
+ mfft : int | None
+ Length of the FFT used, if a zero padded FFT is desired.
+ If ``None`` (default), the length of the window `win` is used.
+ scale_to : 'magnitude' | 'psd' | 'unitary' | None
+ If not ``None`` (default) the window function is scaled, so each STFT
+ column represents either a 'magnitude' or a power spectral density ('psd')
+ spectrum, Alternatively, the STFT can be scaled to a`unitary` mapping,
+ i.e., dividing the window by ``np.sqrt(mfft)`` and multiplying the dual
+ window by the same amount.
+ phase_shift : int | None
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
+ frequency `f`. The default value of 0 ensures that there is no phase shift
+ on the zeroth slice (in which t=0 is centered). See property
+ `phase_shift` for more details.
+
+
+ Notes
+ -----
+ The set of all possible windows with identical dual is defined by the set of
+ linear constraints of Eq. :math:numref:`eq_STFT_AllDualWinsCond` in the
+ :ref:`tutorial_stft` section of the :ref:`user_guide`. There it is also
+ derived that ``ShortTimeFFT.dual_win == ShortTimeFFT.m_pts * ShortTimeFFT.win``
+ needs to hold for an STFT to be a unitary mapping.
+
+ A unitary mapping preserves the value of the scalar product, i.e.,
+
+ .. math::
+
+ \langle x, y\rangle = \sum_k x[k]\, \overline{y[k]}
+ \stackrel{\stackrel{\text{unitary}}{\downarrow}}{=}
+ \sum_{q,p} S_x[q,p]\, \overline{S_y[q,p]}
+ = \langle S_x[q,p], S_y[q,p]\rangle\ ,
+
+ with :math:`S_{x,y}` being the STFT of :math:`x,y`. Hence, the energy
+ :math:`E_x=T\sum_k |x[k]|^2` of a signal is also preserved. This is also
+ illustrated in the example below.
+
+ Thie reason of distinguishing between no scaling (i.e., parameter `scale_to` is
+ ``None``) and unitary scaling (i.e., ``scale_to = 'unitary'``) is due to the
+ utilized FFT function not being unitary (i.e., using the default value
+ ``'backward'`` for the `~scipy.fft.fft` parameter `norm`).
+
+
+ See Also
+ --------
+ closest_STFT_dual_window: Calculate the STFT dual window of a given window
+ closest to a desired dual window.
+ ShortTimeFFT.spectrogram: Calculate squared STFTs
+ ShortTimeFFT: Class this property belongs to.
+
+ Examples
+ --------
+ The following example shows that an STFT can be indeed unitary:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import ShortTimeFFT, windows
+ ...
+ >>> m, hop, std = 36, 8, 5
+ >>> desired_win = windows.gaussian(m, std, sym=True)
+ >>> SFT = ShortTimeFFT.from_win_equals_dual(desired_win, hop, fs=1/m,
+ ... fft_mode='twosided',
+ ... scale_to='unitary')
+ >>> np.allclose(SFT.dual_win, SFT.win * SFT.m_num) # check if STFT is unitary
+ True
+ >>> x1, x2 = np.tile([-1, -1, 1, 1], 5), np.tile([1, -1, -1, 1], 5)
+ >>> np.sum(x1*x2) # scalar product is zero -> orthogonal signals
+ 0
+ >>> np.sum(x1**2) # scalar product of x1 with itself
+ 20
+ >>> Sx11, Sx12 = SFT.spectrogram(x1), SFT.spectrogram(x1, x2)
+ >>> np.sum(Sx12) # STFT scalar product is also zero
+ -4.163336342344337e-16+0j # may vary
+ >>> np.sum(Sx11) # == np.sum(x1**2)
+ 19.999999999999996 # may vary
+ ...
+ ... # Do the plotting:
+ >>> fg1, (ax11, ax12) = plt.subplots(1, 2, tight_layout=True, figsize=(8, 4))
+ >>> s_fac = np.sqrt(SFT.mfft)
+ >>> _ = fg1.suptitle(f"Scaled Unitary Window of {m} Sample Gaussian with " +
+ ... rf"{hop=}, $\sigma={std}$, Scale factor: {s_fac}")
+ >>> ax11.set(ylabel="Amplitude", xlabel="Samples", xlim=(0, m))
+ >>> ax12.set(xlabel="Frequency Bins", ylabel="Magnitude Spectrum",
+ ... xlim=(0, 15), ylim=(1e-5, 1.5))
+ >>> u_win_str = rf"Unitary $\times{s_fac:g}$"
+ >>> for x_, n_ in zip((desired_win, SFT.win*s_fac), ('Desired', u_win_str)):
+ ... ax11.plot(x_, '.-', alpha=0.5, label=n_)
+ ... X_ = np.fft.rfft(x_) / np.sum(abs(x_))
+ ... ax12.semilogy(abs(X_), '.-', alpha=0.5, label=n_)
+ >>> for ax_ in (ax11, ax12):
+ ... ax_.grid(True)
+ ... ax_.legend()
+ >>> plt.show()
+
+ Note that ``fftmode='twosided'`` is used, since we need sum over the complete
+ time frequency plane. Due to passing ``scale_to='unitary'`` the window
+ ``SFT.win`` is scaled by ``1/np.sqrt(SFT.mfft)``. Hence, ``SFT.win`` needs to
+ be scaled by `s_fac` in the plot above.
+ """
+ if not (desired_win.ndim == 1 and desired_win.size > 0):
+ raise ValueError(f"Parameter desired_win is not 1d, but "
+ f"{desired_win.shape=}!")
+ if issubclass(desired_win.dtype.type, np.integer):
+ raise ValueError("Parameter desired_win cannot be of integer type, " +
+ f"but {desired_win.dtype=} => cast to float | complex ")
+ if not all(np.isfinite(desired_win)):
+ raise ValueError("Parameter desired_win must have finite entries!")
+ if not (1 <= hop <= len(desired_win) and isinstance(hop, int | np.integer)):
+ raise ValueError(f"Parameter {hop=} is not an integer between 1 and " +
+ f"{len(desired_win)=}!")
+ if scale_to not in ['magnitude', 'psd', 'unitary', None]:
+ raise ValueError(f"Parameter {scale_to=} not in " +
+ "['magnitude', 'psd', 'unitary', None]!")
+
+ mfft = len(desired_win) if mfft is None else mfft
+ s_fac = np.sqrt(mfft) if scale_to == 'unitary' else 1
+
+ win = desired_win.copy() # we do not want to modify input parameters
+ relative_resolution = np.finfo(win.dtype).resolution * max(win)
+ for m in range(hop):
+ a = np.linalg.norm(desired_win[m::hop])
+ if not (a > relative_resolution):
+ raise ValueError("Parameter desired_win does not have valid STFT dual "
+ f"window for {hop=}!")
+ win[m::hop] /= a
+
+ SFT = cls(win=win/s_fac, hop=hop, fs=fs, fft_mode=fft_mode, mfft=mfft,
+ dual_win=win*s_fac, phase_shift=phase_shift,
+ scale_to=None if scale_to=='unitary' else scale_to)
+
+ if scale_to == 'unitary':
+ SFT._scaling = scale_to
+ return SFT
+
+
+ @property
+ def win(self) -> np.ndarray:
+ """Window function as real- or complex-valued 1d array.
+
+ This attribute is read-only, since `dual_win` depends on it.
+ To make this array immutable, its WRITEABLE flag is set to ``FALSE``.
+
+ See Also
+ --------
+ dual_win: Dual window.
+ m_num: Number of samples in window `win`.
+ m_num_mid: Center index of window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ hop: ime increment in signal samples for sliding window.
+ win: Window function as real- or complex-valued 1d array.
+ numpy.ndarray.setflags: Modify array flags.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._win
+
+ @property
+ def hop(self) -> int:
+ """Time increment in signal samples for sliding window.
+
+ This attribute is read only, since `dual_win` depends on it.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ m_num: Number of samples in window `win`.
+ m_num_mid: Center index of window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ T: Sampling interval of input signal and of the window.
+ win: Window function as real- or complex-valued 1d array.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._hop
+
+ @property
+ def T(self) -> float:
+ """Sampling interval of input signal and of the window.
+
+ A ``ValueError`` is raised if it is set to a non-positive value.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ fs: Sampling frequency (being ``1/T``)
+ t: Times of STFT for an input signal with `n` samples.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return 1 / self._fs
+
+ @T.setter
+ def T(self, v: float):
+ """Sampling interval of input signal and of the window.
+
+ A ``ValueError`` is raised if it is set to a non-positive value.
+ """
+ if not (v > 0):
+ raise ValueError(f"Sampling interval T={v} must be positive!")
+ self._fs = 1 / v
+
+ @property
+ def fs(self) -> float:
+ """Sampling frequency of input signal and of the window.
+
+ The sampling frequency is the inverse of the sampling interval `T`.
+ A ``ValueError`` is raised if it is set to a non-positive value.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ T: Sampling interval of input signal and of the window (``1/fs``).
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._fs
+
+ @fs.setter
+ def fs(self, v: float):
+ """Sampling frequency of input signal and of the window.
+
+ The sampling frequency is the inverse of the sampling interval `T`.
+ A ``ValueError`` is raised if it is set to a non-positive value.
+ """
+ if not (v > 0):
+ raise ValueError(f"Sampling frequency fs={v} must be positive!")
+ self._fs = v
+
+ @property
+ def fft_mode(self) -> FFT_MODE_TYPE:
+ """Mode of utilized FFT ('twosided', 'centered', 'onesided' or
+ 'onesided2X').
+
+ It can have the following values:
+
+ 'twosided':
+ Two-sided FFT, where values for the negative frequencies are in
+ upper half of the array. Corresponds to :func:`~scipy.fft.fft()`.
+ 'centered':
+ Two-sided FFT with the values being ordered along monotonically
+ increasing frequencies. Corresponds to applying
+ :func:`~scipy.fft.fftshift()` to :func:`~scipy.fft.fft()`.
+ 'onesided':
+ Calculates only values for non-negative frequency values.
+ Corresponds to :func:`~scipy.fft.rfft()`.
+ 'onesided2X':
+ Like `onesided`, but the non-zero frequencies are doubled if
+ `scaling` is set to 'magnitude' or multiplied by ``sqrt(2)`` if
+ set to 'psd'. If `scaling` is ``None``, setting `fft_mode` to
+ `onesided2X` is not allowed.
+ If the FFT length `mfft` is even, the last FFT value is not paired,
+ and thus it is not scaled.
+
+ Note that `onesided` and `onesided2X` do not work for complex-valued signals or
+ complex-valued windows. Furthermore, the frequency values can be obtained by
+ reading the `f` property, and the number of samples by accessing the `f_pts`
+ property.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f: Frequencies values of the STFT.
+ f_pts: Width of the frequency bins of the STFT.
+ onesided_fft: True if a one-sided FFT is used.
+ scaling: Normalization applied to the window function
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._fft_mode
+
+ @fft_mode.setter
+ def fft_mode(self, t: FFT_MODE_TYPE):
+ """Set mode of FFT.
+
+ Allowed values are 'twosided', 'centered', 'onesided', 'onesided2X'.
+ See the property `fft_mode` for more details.
+ """
+ if t not in (fft_mode_types := get_args(FFT_MODE_TYPE)):
+ raise ValueError(f"fft_mode='{t}' not in {fft_mode_types}!")
+
+ if t in {'onesided', 'onesided2X'} and np.iscomplexobj(self.win):
+ raise ValueError(f"One-sided spectra, i.e., fft_mode='{t}', " +
+ "are not allowed for complex-valued windows!")
+
+ if t == 'onesided2X' and self.scaling is None:
+ raise ValueError(f"For scaling is None, fft_mode='{t}' is invalid!"
+ "Do scale_to('psd') or scale_to('magnitude')!")
+ self._fft_mode = t
+
+ @property
+ def mfft(self) -> int:
+ """Length of input for the FFT used - may be larger than window
+ length `m_num`.
+
+ If not set, `mfft` defaults to the window length `m_num`.
+
+ See Also
+ --------
+ f_pts: Number of points along the frequency axis.
+ f: Frequencies values of the STFT.
+ m_num: Number of samples in window `win`.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._mfft
+
+ @mfft.setter
+ def mfft(self, n_: int):
+ """Setter for the length of FFT utilized.
+
+ See the property `mfft` for further details.
+ """
+ if not (n_ >= self.m_num):
+ raise ValueError(f"Attribute mfft={n_} needs to be at least the " +
+ f"window length m_num={self.m_num}!")
+ self._mfft = n_
+
+ @property
+ def scaling(self) -> Literal['magnitude', 'psd', 'unitary'] | None:
+ """Normalization applied to the window function
+ ('magnitude', 'psd', 'unitary', or ``None``).
+
+ If not ``None``, the FFT slices may be either interpreted as a `magnitude` or
+ a power spectral density spectrum (`psd`). If set to `unitary`, the STFT may be
+ interpreted as a unitary mapping, i.e., preserving the value of the scalar
+ product.
+
+ The window function can be scaled by calling the `scale_to` method,
+ or it is set by the initializer parameter ``scale_to``. Note that a
+ window cannot to be scaled to be `unitary`. Use `from_win_equals_dual`
+ to create a unitary `ShortTimeFFT` instance.
+
+ See Also
+ --------
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
+ fac_psd: Scaling factor for to a power spectral density spectrum.
+ fft_mode: Mode of utilized FFT
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
+ from_win_equals_dual: Class-method for creating a unitary instance.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._scaling
+
+ def scale_to(self, scaling: Literal['magnitude', 'psd']):
+ """Scale window to obtain 'magnitude' or 'psd' scaling for the STFT.
+
+ The window of a 'magnitude' spectrum has an integral of one, i.e., unit
+ area for non-negative windows. This ensures that absolute the values of
+ spectrum does not change if the length of the window changes (given
+ the input signal is stationary).
+
+ To represent the power spectral density ('psd') for varying length
+ windows the area of the absolute square of the window needs to be
+ unity.
+
+ The `scaling` property shows the current scaling. The properties
+ `fac_magnitude` and `fac_psd` show the scaling factors required to
+ scale the STFT values to a magnitude or a psd spectrum.
+
+ Note that a window cannot to be scaled to be `unitary`. Use
+ `from_win_equals_dual` to create a unitary `ShortTimeFFT` instance.
+
+ This method is called, if the initializer parameter `scale_to` is set.
+
+ Parameters
+ ----------
+ scaling : {'magnitude', 'psd'}
+ The scaling type to which the window is scaled.
+
+ See Also
+ --------
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
+ fac_psd: Scaling factor for to a power spectral density spectrum.
+ fft_mode: Mode of utilized FFT
+ scaling: Normalization applied to the window function.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ if scaling not in (scaling_values := {'magnitude', 'psd'}):
+ raise ValueError(f"{scaling=} not in {scaling_values}!")
+ if self._scaling == scaling: # do nothing
+ return
+
+ s_fac = self.fac_psd if scaling == 'psd' else self.fac_magnitude
+ self._win = self._win * s_fac
+ self.win.setflags(write=False)
+ if self._dual_win is not None:
+ self._dual_win = self._dual_win / s_fac
+ self.dual_win.setflags(write=False)
+ self._fac_mag, self._fac_psd = None, None # reset scaling factors
+ self._scaling = scaling
+
+ @property
+ def phase_shift(self) -> int | None:
+ """If set, add linear phase `phase_shift` / `mfft` * `f` to each FFT
+ slice of frequency `f`.
+
+ Shifting (more precisely `rolling`) an `mfft`-point FFT input by
+ `phase_shift` samples results in a multiplication of the output by
+ ``np.exp(2j*np.pi*q*phase_shift/mfft)`` at the frequency q * `delta_f`.
+
+ The default value 0 ensures that there is no phase shift on the
+ zeroth slice (in which t=0 is centered).
+ No phase shift (``phase_shift is None``) is equivalent to
+ ``phase_shift = -mfft//2``. In this case slices are not shifted
+ before calculating the FFT.
+
+ The absolute value of `phase_shift` is limited to be less than `mfft`.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f: Frequencies values of the STFT.
+ mfft: Length of input for the FFT used
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._phase_shift
+
+ @phase_shift.setter
+ def phase_shift(self, v: int | None):
+ """The absolute value of the phase shift needs to be less than mfft
+ samples.
+
+ See the `phase_shift` getter method for more details.
+ """
+ if v is None:
+ self._phase_shift = v
+ return
+ if not isinstance(v, int | np.integer):
+ raise ValueError(f"phase_shift={v} has the unit samples. Hence " +
+ "it needs to be an int or it may be None!")
+ if not (-self.mfft < v < self.mfft):
+ raise ValueError("-mfft < phase_shift < mfft does not hold " +
+ f"for mfft={self.mfft}, phase_shift={v}!")
+ self._phase_shift = v
+
+ def _x_slices(self, x: np.ndarray, k_off: int, p0: int, p1: int,
+ padding: PAD_TYPE) -> Generator[np.ndarray, None, None]:
+ """Generate signal slices along last axis of `x`.
+
+ This method is only used by `stft_detrend`. The parameters are
+ described in `~ShortTimeFFT.stft`.
+ """
+ if padding not in (padding_types := get_args(PAD_TYPE)):
+ raise ValueError(f"Parameter {padding=} not in {padding_types}!")
+ pad_kws: dict[str, dict] = { # possible keywords to pass to np.pad:
+ 'zeros': dict(mode='constant', constant_values=(0, 0)),
+ 'edge': dict(mode='edge'),
+ 'even': dict(mode='reflect', reflect_type='even'),
+ 'odd': dict(mode='reflect', reflect_type='odd'),
+ } # typing of pad_kws is needed to make mypy happy
+
+ n, n1 = x.shape[-1], (p1 - p0) * self.hop
+ k0 = p0 * self.hop - self.m_num_mid + k_off # start sample
+ k1 = k0 + n1 + self.m_num # end sample
+
+ i0, i1 = max(k0, 0), min(k1, n) # indexes to shorten x
+ # dimensions for padding x:
+ pad_width = [(0, 0)] * (x.ndim-1) + [(-min(k0, 0), max(k1 - n, 0))]
+
+ x1 = np.pad(x[..., i0:i1], pad_width, **pad_kws[padding])
+ for k_ in range(0, n1, self.hop):
+ yield x1[..., k_:k_ + self.m_num]
+
+ def stft(self, x: np.ndarray, p0: int | None = None,
+ p1: int | None = None, *, k_offset: int = 0,
+ padding: PAD_TYPE = 'zeros', axis: int = -1) \
+ -> np.ndarray:
+ """Perform the short-time Fourier transform.
+
+ A two-dimensional matrix with ``p1-p0`` columns is calculated.
+ The `f_pts` rows represent value at the frequencies `f`. The q-th
+ column of the windowed FFT with the window `win` is centered at t[q].
+ The columns represent the values at the frequencies `f`.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The input signal as real or complex valued array. For complex values, the
+ property `fft_mode` must be set to 'twosided' or 'centered'.
+ p0 : int | None
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1 : int | None
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset : int
+ Index of first sample (t = 0) in `x`.
+ padding : 'zeros' | 'edge' | 'even' | 'odd'
+ Kind of values which are added, when the sliding window sticks out
+ on either the lower or upper end of the input `x`. Zeros are added
+ if the default 'zeros' is set. For 'edge' either the first or the
+ last value of `x` is used. 'even' pads by reflecting the
+ signal on the first or last sample and 'odd' additionally
+ multiplies it with -1.
+ axis : int
+ The axis of `x` over which to compute the STFT.
+ If not given, the last axis is used.
+
+ Returns
+ -------
+ S : np.ndarray
+ A complex array is returned with the dimension always being larger
+ by one than of `x`. The last axis always represents the time slices
+ of the STFT. `axis` defines the frequency axis (default second to
+ last). E.g., for a one-dimensional `x`, a complex 2d array is
+ returned, with axis 0 representing frequency and axis 1 the time
+ slices.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ delta_t: Time increment of STFT
+ f: Frequencies values of the STFT.
+ invertible: Check if STFT is invertible.
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
+ p_range: Determine and validate slice index range.
+ stft_detrend: STFT with detrended segments.
+ t: Times of STFT for an input signal with `n` samples.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+ """
+ return self.stft_detrend(x, None, p0, p1, k_offset=k_offset,
+ padding=padding, axis=axis)
+
+ def stft_detrend(self, x: np.ndarray,
+ detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None, # noqa: E501
+ p0: int | None = None, p1: int | None = None, *,
+ k_offset: int = 0, padding: PAD_TYPE = 'zeros',
+ axis: int = -1) \
+ -> np.ndarray:
+ """Calculate short-time Fourier transform with a trend being subtracted from
+ each segment beforehand.
+
+ When the parameter `detr` is ``None``, this method's behavior is identical to
+ the `~ShortTimeFFT.stft` method. Note that due to the detrending, the original
+ signal cannot be reconstructed by the `~ShortTimeFFT.istft`.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The input signal as real or complex valued array. For complex values, the
+ property `fft_mode` must be set to 'twosided' or 'centered'.
+ detr : 'linear' | 'constant' | Callable[[np.ndarray], np.ndarray] | None
+ If 'constant', the mean is subtracted, if set to "linear", the linear
+ trend is removed from each segment. This is achieved by calling
+ `~scipy.signal.detrend`. If `detr` is a function with one parameter, `detr`
+ is applied to each segment.
+ p0 : int | None
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1 : int | None
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset : int
+ Index of first sample (t = 0) in `x`.
+ padding : 'zeros' | 'edge' | 'even' | 'odd'
+ Kind of values which are added, when the sliding window sticks out
+ on either the lower or upper end of the input `x`. Zeros are added
+ if the default 'zeros' is set. For 'edge' either the first or the
+ last value of `x` is used. 'even' pads by reflecting the
+ signal on the first or last sample and 'odd' additionally
+ multiplies it with -1.
+ axis : int
+ The axis of `x` over which to compute the STFT.
+ If not given, the last axis is used.
+
+ Returns
+ -------
+ S : np.ndarray
+ A complex array is returned with the dimension always being larger
+ by one than of `x`. The last axis always represents the time slices
+ of the STFT. `axis` defines the frequency axis (default second to
+ last). E.g., for a one-dimensional `x`, a complex 2d array is
+ returned, with axis 0 representing frequency and axis 1 the time
+ slices.
+
+ See Also
+ --------
+ invertible: Check if STFT is invertible.
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
+ :meth:`~ShortTimeFFT.stft`: Short-time Fourier transform
+ (without detrending).
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+ """
+ if self.onesided_fft and np.iscomplexobj(x):
+ raise ValueError(f"Complex-valued `x` not allowed for {self.fft_mode=}'! "
+ "Set property `fft_mode` to 'twosided' or 'centered'.")
+ if isinstance(detr, str):
+ detr = partial(detrend, type=detr)
+ elif not (detr is None or callable(detr)):
+ raise ValueError(f"Parameter {detr=} is not a str, function or " +
+ "None!")
+ n = x.shape[axis]
+ if not (n >= (m2p := self.m_num-self.m_num_mid)):
+ e_str = f'{len(x)=}' if x.ndim == 1 else f'of {axis=} of {x.shape}'
+ raise ValueError(f"{e_str} must be >= ceil(m_num/2) = {m2p}!")
+
+ if x.ndim > 1: # motivated by the NumPy broadcasting mechanisms:
+ x = np.moveaxis(x, axis, -1)
+ # determine slice index range:
+ p0, p1 = self.p_range(n, p0, p1)
+ S_shape_1d = (self.f_pts, p1 - p0)
+ S_shape = x.shape[:-1] + S_shape_1d if x.ndim > 1 else S_shape_1d
+ S = np.zeros(S_shape, dtype=complex)
+ for p_, x_ in enumerate(self._x_slices(x, k_offset, p0, p1, padding)):
+ if detr is not None:
+ x_ = detr(x_)
+ S[..., :, p_] = self._fft_func(x_ * self.win.conj())
+ if x.ndim > 1:
+ return np.moveaxis(S, -2, axis if axis >= 0 else axis-1)
+ return S
+
+ def spectrogram(self, x: np.ndarray, y: np.ndarray | None = None,
+ detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None = None, # noqa: E501
+ *,
+ p0: int | None = None, p1: int | None = None,
+ k_offset: int = 0, padding: PAD_TYPE = 'zeros',
+ axis: int = -1) \
+ -> np.ndarray:
+ r"""Calculate spectrogram or cross-spectrogram.
+
+ The spectrogram is the absolute square of the STFT, i.e., it is
+ ``abs(S[q,p])**2`` for given ``S[q,p]`` and thus is always
+ non-negative.
+ For two STFTs ``Sx[q,p], Sy[q,p]``, the cross-spectrogram is defined
+ as ``Sx[q,p] * np.conj(Sy[q,p])`` and is complex-valued.
+ This is a convenience function for calling `~ShortTimeFFT.stft` /
+ `stft_detrend`, hence all parameters are discussed there.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The input signal as real or complex valued array. For complex values, the
+ property `fft_mode` must be set to 'twosided' or 'centered'.
+ y : np.ndarray
+ The second input signal of the same shape as `x`. If ``None``, it is
+ assumed to be `x`. For complex values, the property `fft_mode` must be
+ set to 'twosided' or 'centered'.
+ detr : 'linear' | 'constant' | Callable[[np.ndarray], np.ndarray] | None
+ If 'constant', the mean is subtracted, if set to "linear", the linear
+ trend is removed from each segment. This is achieved by calling
+ `~scipy.signal.detrend`. If `detr` is a function with one parameter, `detr`
+ is applied to each segment. For ``None`` (default), no trends are removed.
+ p0 : int | None
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1 : int | None
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset : int
+ Index of first sample (t = 0) in `x`.
+ padding : 'zeros' | 'edge' | 'even' | 'odd'
+ Kind of values which are added, when the sliding window sticks out
+ on either the lower or upper end of the input `x`. Zeros are added
+ if the default 'zeros' is set. For 'edge' either the first or the
+ last value of `x` is used. 'even' pads by reflecting the
+ signal on the first or last sample and 'odd' additionally
+ multiplies it with -1.
+ axis : int
+ The axis of `x` over which to compute the STFT.
+ If not given, the last axis is used.
+
+ Returns
+ -------
+ S_xy : np.ndarray
+ A real-valued array with non-negative values is returned, if ``x is y`` or
+ `y` is ``None``. The dimension is always by one larger than of `x`. The
+ last axis always represents the time slices of the spectrogram. `axis`
+ defines the frequency axis (default second to last). E.g., for a
+ one-dimensional `x`, a complex 2d array is returned, with axis 0
+ representing frequency and axis 1 the time slices.
+
+ See Also
+ --------
+ :meth:`~ShortTimeFFT.stft`: Perform the short-time Fourier transform.
+ stft_detrend: STFT with a trend subtracted from each segment.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+
+ Notes
+ -----
+ The cross-spectrogram may be interpreted as the time-frequency analogon of the
+ cross-spectral density (consult `csd`). The absolute square `|Sxy|²` of a
+ cross-spectrogram `Sxy` divided by the spectrograms `Sxx` and `Syy` can be
+ interpreted as a coherence spectrogram ``Cxy := abs(Sxy)**2 / (Sxx*Syy)``,
+ which is the time-frequency analogon to `~coherence`.
+
+ If the STFT is parametrized to be a unitary transform, i.e., utilitzing
+ `~from_win_equals_dual`, then the value of the scalar product, hence also the
+ energy, is preserved.
+
+ Examples
+ --------
+ The following example shows the spectrogram of a square wave with varying
+ frequency :math:`f_i(t)` (marked by a green dashed line in the plot) sampled
+ with 20 Hz. The utilized Gaussian window is 50 samples or 2.5 s long. For the
+ `ShortTimeFFT`, the parameter ``mfft=800`` (oversampling factor 16) and the
+ `hop` interval of 2 in was chosen to produce a sufficient number of points.
+
+ The plot's colormap is logarithmically scaled as the power spectral
+ density is in dB. The time extent of the signal `x` is marked by
+ vertical dashed lines, and the shaded areas mark the presence of border
+ effects.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import square, ShortTimeFFT
+ >>> from scipy.signal.windows import gaussian
+ ...
+ >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal
+ >>> t_x = np.arange(N) * T_x # time indexes for signal
+ >>> f_i = 5e-3*(t_x - t_x[N // 3])**2 + 1 # varying frequency
+ >>> x = square(2*np.pi*np.cumsum(f_i)*T_x) # the signal
+ ...
+ >>> g_std = 12 # standard deviation for Gaussian window in samples
+ >>> win = gaussian(50, std=g_std, sym=True) # symmetric Gaussian wind.
+ >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T_x, mfft=800, scale_to='psd')
+ >>> Sx2 = SFT.spectrogram(x) # calculate absolute square of STFT
+ ...
+ >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit
+ >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot
+ >>> ax1.set_title(rf"Spectrogram ({SFT.m_num*SFT.T:g}$\,s$ Gaussian " +
+ ... rf"window, $\sigma_t={g_std*SFT.T:g}\,$s)")
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " +
+ ... rf"$\Delta t = {SFT.delta_t:g}\,$s)",
+ ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " +
+ ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)",
+ ... xlim=(t_lo, t_hi))
+ >>> Sx_dB = 10 * np.log10(np.fmax(Sx2, 1e-4)) # limit range to -40 dB
+ >>> im1 = ax1.imshow(Sx_dB, origin='lower', aspect='auto',
+ ... extent=SFT.extent(N), cmap='magma')
+ >>> ax1.plot(t_x, f_i, 'g--', alpha=.5, label='$f_i(t)$')
+ >>> fig1.colorbar(im1, label='Power Spectral Density ' +
+ ... r"$20\,\log_{10}|S_x(t, f)|$ in dB")
+ ...
+ >>> # Shade areas where window slices stick out to the side:
+ >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T),
+ ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]:
+ ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.3)
+ >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line
+ ... ax1.axvline(t_, color='c', linestyle='--', alpha=0.5)
+ >>> ax1.legend()
+ >>> fig1.tight_layout()
+ >>> plt.show()
+
+ The logarithmic scaling reveals the odd harmonics of the square wave,
+ which are reflected at the Nyquist frequency of 10 Hz. This aliasing
+ is also the main source of the noise artifacts in the plot.
+ """
+ Sx = self.stft_detrend(x, detr, p0, p1, k_offset=k_offset,
+ padding=padding, axis=axis)
+ if y is None or y is x: # do spectrogram:
+ return Sx.real**2 + Sx.imag**2
+ # Cross-spectrogram:
+ Sy = self.stft_detrend(y, detr, p0, p1, k_offset=k_offset,
+ padding=padding, axis=axis)
+ return Sx * Sy.conj()
+
+ @property
+ def dual_win(self) -> np.ndarray:
+ """Dual window (canonical dual window by default).
+
+ A STFT can be interpreted as the input signal being expressed as a
+ weighted sum of modulated and time-shifted dual windows. If no dual window is
+ given on instantiation, the canonical dual window, i.e., the window with the
+ minimal energy (i.e., minimal L²-norm) is calculated. Alternative means for
+ determining dual windows are provided by `closest_STFT_dual_window` and the
+ `from_win_equals_dual` class-method. Note that `win` is also always a
+ dual window of `dual_win`.
+
+ `dual_win` has same length as `win`, namely `m_num` samples.
+
+ If the dual window cannot be calculated a ``ValueError`` is raised.
+ This attribute is read only and calculated lazily.
+ To make this array immutable, its WRITEABLE flag is set to ``FALSE``.
+
+ See Also
+ --------
+ m_num: Number of samples in window `win` and `dual_win`.
+ win: Window function as real- or complex-valued 1d array.
+ from_win_equals_dual: Create instance where `win` and `dual_win` are equal.
+ closest_STFT_dual_window: Calculate dual window closest to a desired window.
+ numpy.ndarray.setflags: Modify array flags.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self._dual_win is None:
+ self._dual_win = _calc_dual_canonical_window(self.win, self.hop)
+ self.dual_win.setflags(write=False)
+ return self._dual_win
+
+ @property
+ def invertible(self) -> bool:
+ """Check if STFT is invertible.
+
+ This is achieved by trying to calculate the canonical dual window.
+
+ See Also
+ --------
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
+ m_num: Number of samples in window `win` and `dual_win`.
+ dual_win: Dual window.
+ win: Window for STFT.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ try:
+ return len(self.dual_win) > 0 # call self.dual_win()
+ except ValueError:
+ return False
+
+ def istft(self, S: np.ndarray, k0: int = 0, k1: int | None = None, *,
+ f_axis: int = -2, t_axis: int = -1) \
+ -> np.ndarray:
+ """Inverse short-time Fourier transform.
+
+ Parameters
+ ----------
+ S : ndarray
+ A complex valued array where `f_axis` denotes the frequency
+ values and the `t_axis` dimension the temporal values of the
+ STFT values.
+ k0, k1 : int, optional
+ The start and the end index of the reconstructed signal. The
+ default (``k0 = 0``, ``k1 = None``) assumes that the maximum length
+ signal should be reconstructed.
+ f_axis, t_axis : int, optional
+ The axes in `S` denoting the frequency and the time dimension.
+
+ Returns
+ -------
+ ndarray
+ Array of dimension ``S.ndim - 1`` which is real if `onesided_fft` is set,
+ else complex.
+
+ Raises
+ ------
+ ValueError
+ If the STFT is not invertible, or the parameters are out of bounds.
+
+ See Also
+ --------
+ invertible: Check if STFT is invertible.
+ :meth:`~ShortTimeFFT.stft`: Perform Short-time Fourier transform.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+
+ Notes
+ -----
+ It is required that `S` has `f_pts` entries along the `f_axis`. For
+ the `t_axis` it is assumed that the first entry corresponds to
+ `p_min` * `delta_t` (being <= 0). The length of `t_axis` needs to be
+ compatible with `k1`. I.e., ``S.shape[t_axis] >= self.p_max(k1)`` must
+ hold, if `k1` is not ``None``. Else `k1` is set to `k_max` with::
+
+ q_max = S.shape[t_range] + self.p_min
+ k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid
+
+ The :ref:`tutorial_stft` section of the :ref:`user_guide` discussed the
+ slicing behavior by means of an example.
+ """
+ if f_axis == t_axis:
+ raise ValueError(f"{f_axis=} may not be equal to {t_axis=}!")
+ if S.shape[f_axis] != self.f_pts:
+ raise ValueError(f"{S.shape[f_axis]=} must be equal to " +
+ f"{self.f_pts=} ({S.shape=})!")
+ n_min = self.m_num-self.m_num_mid # minimum signal length
+ if not (S.shape[t_axis] >= (q_num := self.p_num(n_min))):
+ raise ValueError(f"{S.shape[t_axis]=} needs to have at least " +
+ f"{q_num} slices ({S.shape=})!")
+ if t_axis != S.ndim - 1 or f_axis != S.ndim - 2:
+ t_axis = S.ndim + t_axis if t_axis < 0 else t_axis
+ f_axis = S.ndim + f_axis if f_axis < 0 else f_axis
+ S = np.moveaxis(S, (f_axis, t_axis), (-2, -1))
+
+ q_max = S.shape[-1] + self.p_min
+ k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid
+
+ k1 = k_max if k1 is None else k1
+ if not (self.k_min <= k0 < k1 <= k_max):
+ raise ValueError(f"({self.k_min=}) <= ({k0=}) < ({k1=}) <= " +
+ f"({k_max=}) is false!")
+ if not (num_pts := k1 - k0) >= n_min:
+ raise ValueError(f"({k1=}) - ({k0=}) = {num_pts} has to be at " +
+ f"least the half the window length {n_min}!")
+
+ q0 = (k0 // self.hop + self.p_min if k0 >= 0 else # p_min always <= 0
+ k0 // self.hop)
+ q1 = min(self.p_max(k1), q_max)
+ k_q0, k_q1 = self.nearest_k_p(k0), self.nearest_k_p(k1, left=False)
+ n_pts = k_q1 - k_q0 + self.m_num - self.m_num_mid
+ x = np.zeros(S.shape[:-2] + (n_pts,),
+ dtype=float if self.onesided_fft else complex)
+ for q_ in range(q0, q1):
+ xs = self._ifft_func(S[..., :, q_ - self.p_min]) * self.dual_win
+ i0 = q_ * self.hop - self.m_num_mid
+ i1 = min(i0 + self.m_num, n_pts+k0)
+ j0, j1 = 0, i1 - i0
+ if i0 < k0: # xs sticks out to the left on x:
+ j0 += k0 - i0
+ i0 = k0
+ x[..., i0-k0:i1-k0] += xs[..., j0:j1]
+ x = x[..., :k1-k0]
+ if x.ndim > 1:
+ x = np.moveaxis(x, -1, f_axis if f_axis < x.ndim else t_axis)
+ return x
+
+ @property
+ def fac_magnitude(self) -> float:
+ """Factor to multiply the STFT values by to scale each frequency slice
+ to a magnitude spectrum.
+
+ It is 1 if attribute ``scaling == 'magnitude'``.
+ The window can be scaled to a magnitude spectrum by using the method
+ `scale_to`.
+
+ See Also
+ --------
+ fac_psd: Scaling factor for to a power spectral density spectrum.
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
+ scaling: Normalization applied to the window function.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self.scaling == 'magnitude':
+ return 1
+ if self._fac_mag is None:
+ self._fac_mag = 1 / abs(sum(self.win))
+ return self._fac_mag
+
+ @property
+ def fac_psd(self) -> float:
+ """Factor to multiply the STFT values by to scale each frequency slice
+ to a power spectral density (PSD).
+
+ It is 1 if attribute ``scaling == 'psd'``.
+ The window can be scaled to a psd spectrum by using the method
+ `scale_to`.
+
+ See Also
+ --------
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
+ scaling: Normalization applied to the window function.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self.scaling == 'psd':
+ return 1
+ if self._fac_psd is None:
+ self._fac_psd = 1 / np.sqrt(
+ sum(self.win.real**2+self.win.imag**2) / self.T)
+ return self._fac_psd
+
+ @property
+ def m_num(self) -> int:
+ """Number of samples in window `win`.
+
+ Note that the FFT can be oversampled by zero-padding. This is achieved
+ by setting the `mfft` property.
+
+ See Also
+ --------
+ m_num_mid: Center index of window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ hop: Time increment in signal samples for sliding window.
+ win: Window function as real- or complex-valued 1d array.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return len(self.win)
+
+ @property
+ def m_num_mid(self) -> int:
+ """Center index of window `win`.
+
+ For odd `m_num`, ``(m_num - 1) / 2`` is returned and
+ for even `m_num` (per definition) ``m_num / 2`` is returned.
+
+ See Also
+ --------
+ m_num: Number of samples in window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ hop: ime increment in signal samples for sliding window.
+ win: Window function as real- or complex-valued 1d array.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self.m_num // 2
+
+ @cached_property
+ def _pre_padding(self) -> tuple[int, int]:
+ """Smallest signal index and slice index due to padding.
+
+ Since, per convention, for time t=0, n,q is zero, the returned values
+ are negative or zero.
+ """
+ w2 = self.win.real**2 + self.win.imag**2
+ # move window to the left until the overlap with t >= 0 vanishes:
+ n0 = -self.m_num_mid
+ for p_, n_ in enumerate(range(n0, n0-self.m_num-1, -self.hop)):
+ n_next = n_ - self.hop
+ if n_next + self.m_num <= 0 or all(w2[n_next:] == 0):
+ return n_, -p_
+ # Make the linter happy:
+ raise RuntimeError("This code line should never run! Please file a bug.")
+
+ @property
+ def k_min(self) -> int:
+ """The smallest possible signal index of the STFT.
+
+ `k_min` is the index of the left-most non-zero value of the lowest
+ slice `p_min`. Since the zeroth slice is centered over the zeroth
+ sample of the input signal, `k_min` is never positive.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._pre_padding[0]
+
+ @property
+ def p_min(self) -> int:
+ """The smallest possible slice index.
+
+ `p_min` is the index of the left-most slice, where the window still
+ sticks into the signal, i.e., has non-zero part for t >= 0.
+ `k_min` is the smallest index where the window function of the slice
+ `p_min` is non-zero.
+
+ Since, per convention the zeroth slice is centered at t=0,
+ `p_min` <= 0 always holds.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._pre_padding[1]
+
+ def _post_padding(self, n: int) -> tuple[int, int]:
+ """Largest signal index and slice index due to padding.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal (must be ≥ half of the window length).
+
+ Notes
+ -----
+ Note that the return values are cached together with the parameter `n` to avoid
+ unnecessary recalculations.
+ """
+ if not (n >= (m2p := self.m_num - self.m_num_mid)):
+ raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!")
+ last_arg, last_return_value = self._cache_post_padding
+ if n == last_arg: # use cached value:
+ return last_return_value
+ w2 = self.win.real**2 + self.win.imag**2
+ # move window to the right until the overlap for t < t[n] vanishes:
+ q1 = n // self.hop # last slice index with t[p1] <= t[n]
+ k1 = q1 * self.hop - self.m_num_mid
+ for q_, k_ in enumerate(range(k1, n+self.m_num, self.hop), start=q1):
+ n_next = k_ + self.hop
+ if n_next >= n or all(w2[:n-n_next] == 0):
+ return_value = k_ + self.m_num, q_ + 1
+ self._cache_post_padding = n, return_value
+ return return_value
+ raise RuntimeError("This code line should never run! Please file a bug.")
+ # If this case is reached, it probably means the last slice should be
+ # returned, i.e.: return k1 + self.m_num - self.m_num_mid, q1 + 1
+
+ def k_max(self, n: int) -> int:
+ """First sample index after signal end not touched by a time slice.
+
+ `k_max` - 1 is the largest sample index of the slice `p_max` - 1 for a
+ given input signal of `n` samples.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal (must be ≥ half of the window length).
+
+ Returns
+ -------
+ int
+ First sample index after signal end not touched by a time slice.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ return self._post_padding(n)[0]
+
+ def p_max(self, n: int) -> int:
+ """Index of first non-overlapping upper time slice for `n` sample
+ input.
+
+ Note that center point t[p_max] = (p_max(n)-1) * `delta_t` is typically
+ larger than last time index t[n-1] == (`n`-1) * `T`. The upper border
+ of samples indexes covered by the window slices is given by `k_max`.
+ Furthermore, `p_max` does not denote the number of slices `p_num` since
+ `p_min` is typically less than zero.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input.
+
+ Returns
+ -------
+ int
+ Index of first non-overlapping upper time slice for `n` sample input.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ p_min: The smallest possible slice index.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ return self._post_padding(n)[1]
+
+ def p_num(self, n: int) -> int:
+ """Number of time slices for an input signal with `n` samples.
+
+ It is given by `p_num` = `p_max` - `p_min` with `p_min` typically
+ being negative.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal
+
+ Returns
+ -------
+ p_num : int
+ Number of time slices for input signal with `n` samples.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_range: Determine and validate slice index range.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ return self.p_max(n) - self.p_min
+
+ @property
+ def lower_border_end(self) -> tuple[int, int]:
+ """First signal index and first slice index unaffected by pre-padding.
+
+ Describes the point where the window does not stick out to the left
+ of the signal domain.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self._lower_border_end is not None:
+ return self._lower_border_end
+
+ # first non-zero element in self.win:
+ m0 = np.flatnonzero(self.win.real**2 + self.win.imag**2)[0]
+
+ # move window to the right until does not stick out to the left:
+ k0 = -self.m_num_mid + m0
+ for q_, k_ in enumerate(range(k0, self.hop + 1, self.hop)):
+ if k_ + self.hop >= 0: # next entry does not stick out anymore
+ self._lower_border_end = (k_ + self.m_num, q_ + 1)
+ return self._lower_border_end
+ self._lower_border_end = (0, max(self.p_min, 0)) # ends at first slice
+ return self._lower_border_end
+
+ def upper_border_begin(self, n: int) -> tuple[int, int]:
+ """First signal index and first slice index affected by post-padding.
+
+ Describes the point where the window does begin stick out to the right
+ of the signal domain.
+ A detailed example is given :ref:`tutorial_stft_sliding_win` section
+ of the :ref:`user_guide`.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal (must be ≥ half of the window length).
+
+ Returns
+ -------
+ k_ub : int
+ Lowest signal index, where a touching time slice sticks out past the
+ signal end.
+ p_ub : int
+ Lowest index of time slice of which the end sticks out past the signal end.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this method belongs to.
+
+ Notes
+ -----
+ Note that the return values are cached together with the parameter `n` to avoid
+ unnecessary recalculations.
+ """
+ if not (n >= (m2p := self.m_num - self.m_num_mid)):
+ raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!")
+ last_arg, last_return_value = self._cache_upper_border_begin
+ if n == last_arg: # use cached value:
+ return last_return_value
+ w2 = self.win.real**2 + self.win.imag**2
+ q2 = n // self.hop + 1 # first t[q] >= t[n]
+ q1 = max((n-self.m_num) // self.hop - 1, -1)
+ # move window left until does not stick out to the right:
+ for q_ in range(q2, q1, -1):
+ k_ = q_ * self.hop + (self.m_num - self.m_num_mid)
+ if k_ <= n or all(w2[n-k_:] == 0):
+ return_value = (q_ + 1) * self.hop - self.m_num_mid, q_ + 1
+ self. _cache_upper_border_begin = n, return_value
+ return return_value
+ # make linter happy:
+ raise RuntimeError("This code line should never run! Please file a bug.")
+
+ @property
+ def delta_t(self) -> float:
+ """Time increment of STFT.
+
+ The time increment `delta_t` = `T` * `hop` represents the sample
+ increment `hop` converted to time based on the sampling interval `T`.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ hop: Hop size in signal samples for sliding window.
+ t: Times of STFT for an input signal with `n` samples.
+ T: Sampling interval of input signal and window `win`.
+ ShortTimeFFT: Class this property belongs to
+ """
+ return self.T * self.hop
+
+ def p_range(self, n: int, p0: int | None = None,
+ p1: int | None = None) -> tuple[int, int]:
+ """Determine and validate slice index range.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal, assuming t[0] = 0.
+ p0 : int | None
+ First slice index. If 0 then the first slice is centered at t = 0.
+ If ``None`` then `p_min` is used. Note that p0 may be < 0 if
+ slices are left of t = 0.
+ p1 : int | None
+ End of interval (last value is p1-1).
+ If ``None`` then `p_max(n)` is used.
+
+
+ Returns
+ -------
+ p0_ : int
+ The fist slice index
+ p1_ : int
+ End of interval (last value is p1-1).
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this property belongs to.
+
+ Notes
+ -----
+ A ``ValueError`` is raised if ``p_min <= p0 < p1 <= p_max(n)`` does not
+ hold.
+ """
+ p_max = self.p_max(n) # shorthand
+ p0_ = self.p_min if p0 is None else p0
+ p1_ = p_max if p1 is None else p1
+ if not (self.p_min <= p0_ < p1_ <= p_max):
+ raise ValueError(f"Invalid Parameter {p0=}, {p1=}, i.e., " +
+ f"{self.p_min=} <= p0 < p1 <= {p_max=} " +
+ f"does not hold for signal length {n=}!")
+ return p0_, p1_
+
+ def t(self, n: int, p0: int | None = None, p1: int | None = None,
+ k_offset: int = 0) -> np.ndarray:
+ """Times of STFT for an input signal with `n` samples.
+
+ Returns a 1d array with times of the `~ShortTimeFFT.stft` values with
+ the same parametrization. Note that the slices are
+ ``delta_t = hop * T`` time units apart.
+
+ Parameters
+ ----------
+ n : int
+ Number of sample of the input signal.
+ p0 : int, optional
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1 : int, optional
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset : int
+ Index of first sample (t = 0) in `x`.
+
+ Returns
+ -------
+ t : ndarray
+ 1D array of times of the STFT slices from `p0` to `p1` - 1.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ nearest_k_p: Nearest sample index k_p for which t[k_p] == t[p] holds.
+ T: Sampling interval of input signal and of the window (``1/fs``).
+ fs: Sampling frequency (being ``1/T``)
+ ShortTimeFFT: Class this method belongs to.
+
+ Notes
+ -----
+ Note that the returned array is cached together with the method's call
+ parameters to avoid unnecessary recalculations.
+ """
+ if not (n > 0 and isinstance(n, int | np.integer)):
+ raise ValueError(f"Parameter {n=} is not a positive integer!")
+ args = n, p0, p1, k_offset, self.T # since `self.T` is mutable, it's needed too
+ last_args, last_return_value = self._cache_t
+ if args == last_args: # use cached value:
+ return last_return_value
+
+ p0, p1 = self.p_range(n, p0, p1)
+ return_value = np.arange(p0, p1) * self.delta_t + k_offset * self.T
+
+ self._cache_t = args, return_value
+ return return_value
+
+ def nearest_k_p(self, k: int, left: bool = True) -> int:
+ """Return nearest sample index k_p for which ``t[k_p] == t[p]`` holds.
+
+ The nearest next smaller time sample p (where ``t[p]`` is the center
+ position of the window of the p-th slice) is ``p_k = k // hop``.
+ If `hop` is a divisor of `k` then `k` is returned.
+ If `left` is set then ``p_k * hop`` is returned else ``(p_k+1) * hop``.
+
+ This method can be used to slice an input signal into chunks for
+ calculating the STFT and iSTFT incrementally.
+
+ Parameters
+ ----------
+ k : int
+ Sample index for which the nearest slice center index is sought.
+ left : bool, optional
+ If ``True`` then the nearest smaller index is returned, else the
+ nearest larger index is returned. Defaults to ``True``.
+
+ Returns
+ -------
+ int
+ Nearest sample index k_p for which ``t[k_p] == t[p]`` holds.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ T: Sampling interval of input signal and of the window (``1/fs``).
+ fs: Sampling frequency (being ``1/T``)
+ t: Times of STFT for an input signal with `n` samples.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ p_q, remainder = divmod(k, self.hop)
+ if remainder == 0:
+ return k
+ return p_q * self.hop if left else (p_q + 1) * self.hop
+
+ @property
+ def delta_f(self) -> float:
+ """Width of the frequency bins of the STFT.
+
+ Return the frequency interval `delta_f` = 1 / (`mfft` * `T`).
+
+ See Also
+ --------
+ delta_t: Time increment of STFT.
+ f_pts: Number of points along the frequency axis.
+ f: Frequencies values of the STFT.
+ mfft: Length of the input for FFT used.
+ T: Sampling interval.
+ t: Times of STFT for an input signal with `n` samples.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return 1 / (self.mfft * self.T)
+
+ @property
+ def f_pts(self) -> int:
+ """Number of points along the frequency axis.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f: Frequencies values of the STFT.
+ mfft: Length of the input for FFT used.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self.mfft // 2 + 1 if self.onesided_fft else self.mfft
+
+ @property
+ def onesided_fft(self) -> bool:
+ """Return True if a one-sided FFT is used.
+
+ Returns ``True`` if `fft_mode` is either 'onesided' or 'onesided2X'.
+
+ See Also
+ --------
+ fft_mode: Utilized FFT ('twosided', 'centered', 'onesided' or
+ 'onesided2X')
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self.fft_mode in {'onesided', 'onesided2X'}
+
+ @property
+ def f(self) -> np.ndarray:
+ """Frequencies values of the STFT.
+
+ A 1d array of length `f_pts` with `delta_f` spaced entries is returned.
+ This array is calculated lazily.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f_pts: Number of points along the frequency axis.
+ mfft: Length of the input for FFT used.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ last_state, last_return_value = self._cache_f
+ current_state = self.fft_mode, self.mfft, self.T
+ if current_state == last_state: # use cached value:
+ return last_return_value
+
+ if self.fft_mode in {'onesided', 'onesided2X'}:
+ return_value = fft_lib.rfftfreq(self.mfft, self.T)
+ elif self.fft_mode == 'twosided':
+ return_value = fft_lib.fftfreq(self.mfft, self.T)
+ elif self.fft_mode == 'centered':
+ return_value = fft_lib.fftshift(fft_lib.fftfreq(self.mfft, self.T))
+ else: # This should never happen but makes the Linters happy:
+ fft_modes = get_args(FFT_MODE_TYPE)
+ raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!")
+ self._cache_f = current_state, return_value
+ return return_value
+
+ def _fft_func(self, x: np.ndarray) -> np.ndarray:
+ """FFT based on the `fft_mode`, `mfft`, `scaling` and `phase_shift`
+ attributes.
+
+ For multidimensional arrays the transformation is carried out on the
+ last axis.
+ """
+ if self.phase_shift is not None:
+ if x.shape[-1] < self.mfft: # zero pad if needed
+ z_shape = list(x.shape)
+ z_shape[-1] = self.mfft - x.shape[-1]
+ x = np.hstack((x, np.zeros(z_shape, dtype=x.dtype)))
+ p_s = (self.phase_shift + self.m_num_mid) % self.m_num
+ x = np.roll(x, -p_s, axis=-1)
+
+ if self.fft_mode == 'twosided':
+ return fft_lib.fft(x, n=self.mfft, axis=-1)
+ if self.fft_mode == 'centered':
+ return fft_lib.fftshift(fft_lib.fft(x, self.mfft, axis=-1), axes=-1)
+ if self.fft_mode == 'onesided':
+ return fft_lib.rfft(x, n=self.mfft, axis=-1)
+ if self.fft_mode == 'onesided2X':
+ X = fft_lib.rfft(x, n=self.mfft, axis=-1)
+ # Either squared magnitude (psd) or magnitude is doubled:
+ fac = np.sqrt(2) if self.scaling == 'psd' else 2
+ # For even input length, the last entry is unpaired:
+ X[..., 1: -1 if self.mfft % 2 == 0 else None] *= fac
+ return X
+ # This should never happen but makes the Linter happy:
+ fft_modes = get_args(FFT_MODE_TYPE)
+ raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!")
+
+ def _ifft_func(self, X: np.ndarray) -> np.ndarray:
+ """Inverse to `_fft_func`.
+
+ Returned is an array of length `m_num`. If the FFT is `onesided`
+ then a float array is returned else a complex array is returned.
+ For multidimensional arrays the transformation is carried out on the
+ last axis.
+ """
+ if self.fft_mode == 'twosided':
+ x = fft_lib.ifft(X, n=self.mfft, axis=-1)
+ elif self.fft_mode == 'centered':
+ x = fft_lib.ifft(fft_lib.ifftshift(X, axes=-1), n=self.mfft, axis=-1)
+ elif self.fft_mode == 'onesided':
+ x = fft_lib.irfft(X, n=self.mfft, axis=-1)
+ elif self.fft_mode == 'onesided2X':
+ Xc = X.copy() # we do not want to modify function parameters
+ fac = np.sqrt(2) if self.scaling == 'psd' else 2
+ # For even length X the last value is not paired with a negative
+ # value on the two-sided FFT:
+ q1 = -1 if self.mfft % 2 == 0 else None
+ Xc[..., 1:q1] /= fac
+ x = fft_lib.irfft(Xc, n=self.mfft, axis=-1)
+ else: # This should never happen but makes the Linter happy:
+ raise RuntimeError(f"{self.fft_mode=} not in {get_args(FFT_MODE_TYPE)}!")
+
+ if self.phase_shift is None:
+ return x[..., :self.m_num]
+ p_s = (self.phase_shift + self.m_num_mid) % self.m_num
+ return np.roll(x, p_s, axis=-1)[..., :self.m_num]
+
+ def extent(self, n: int, axes_seq: Literal['tf', 'ft'] = 'tf',
+ center_bins: bool = False) -> tuple[float, float, float, float]:
+ """Return minimum and maximum values time-frequency values.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples in input signal.
+ axes_seq : {'tf', 'ft'}
+ Return time extent first and then frequency extent or vice versa.
+ center_bins : bool
+ If set (default ``False``), the values of the time slots and
+ frequency bins are moved from the side the middle. This is useful,
+ when plotting the `~ShortTimeFFT.stft` values as step functions,
+ i.e., with no interpolation.
+
+ Returns
+ -------
+ tuple
+ A tuple with four floats ``(t0, t1, f0, f1)`` for 'tf' and
+ ``(f0, f1, t0, t1)`` for 'ft' is returned describing the corners
+ of the time-frequency domain of the `~ShortTimeFFT.stft`.
+ That tuple can be passed to `matplotlib.pyplot.imshow` as a parameter
+ with the same name.
+
+ See Also
+ --------
+ :func:`matplotlib.pyplot.imshow`: Display data as an image.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+
+ Examples
+ --------
+ The following two plots illustrate the effect of the parameter `center_bins`:
+ The grid lines represent the three time and the four frequency values of the
+ STFT.
+ The left plot, where ``(t0, t1, f0, f1) = (0, 3, 0, 4)`` is passed as parameter
+ ``extent`` to `~matplotlib.pyplot.imshow`, shows the standard behavior of the
+ time and frequency values being at the lower edge of the corrsponding bin.
+ The right plot, with ``(t0, t1, f0, f1) = (-0.5, 2.5, -0.5, 3.5)``, shows that
+ the bins are centered over the respective values when passing
+ ``center_bins=True``.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import ShortTimeFFT
+ ...
+ >>> n, m = 12, 6
+ >>> SFT = ShortTimeFFT.from_window('hann', fs=m, nperseg=m, noverlap=0)
+ >>> Sxx = SFT.stft(np.cos(np.arange(n))) # produces a colorful plot
+ ...
+ >>> fig, axx = plt.subplots(1, 2, tight_layout=True, figsize=(6., 4.))
+ >>> for ax_, center_bins in zip(axx, (False, True)):
+ ... ax_.imshow(abs(Sxx), origin='lower', interpolation=None, aspect='equal',
+ ... cmap='viridis', extent=SFT.extent(n, 'tf', center_bins))
+ ... ax_.set_title(f"{center_bins=}")
+ ... ax_.set_xlabel(f"Time ({SFT.p_num(n)} points, Δt={SFT.delta_t})")
+ ... ax_.set_ylabel(f"Frequency ({SFT.f_pts} points, Δf={SFT.delta_f})")
+ ... ax_.set_xticks(SFT.t(n)) # vertical grid line are timestamps
+ ... ax_.set_yticks(SFT.f) # horizontal grid line are frequency values
+ ... ax_.grid(True)
+ >>> plt.show()
+
+ Note that the step-like behavior with the constant colors is caused by passing
+ ``interpolation=None`` to `~matplotlib.pyplot.imshow`.
+ """
+ if axes_seq not in ('tf', 'ft'):
+ raise ValueError(f"Parameter {axes_seq=} not in ['tf', 'ft']!")
+
+ if self.onesided_fft:
+ q0, q1 = 0, self.f_pts
+ elif self.fft_mode == 'centered':
+ q0 = -(self.mfft // 2)
+ q1 = self.mfft // 2 if self.mfft % 2 == 0 else self.mfft // 2 + 1
+ else:
+ raise ValueError(f"Attribute fft_mode={self.fft_mode} must be " +
+ "in ['centered', 'onesided', 'onesided2X']")
+
+ p0, p1 = self.p_min, self.p_max(n) # shorthand
+ if center_bins:
+ t0, t1 = self.delta_t * (p0 - 0.5), self.delta_t * (p1 - 0.5)
+ f0, f1 = self.delta_f * (q0 - 0.5), self.delta_f * (q1 - 0.5)
+ else:
+ t0, t1 = self.delta_t * p0, self.delta_t * p1
+ f0, f1 = self.delta_f * q0, self.delta_f * q1
+ return (t0, t1, f0, f1) if axes_seq == 'tf' else (f0, f1, t0, t1)
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_signal_api.py b/.venv/lib/python3.12/site-packages/scipy/signal/_signal_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..68d19aaf9be016666f20b78e97bebe8e7fd14d85
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_signal_api.py
@@ -0,0 +1,31 @@
+"""This is the 'bare' scipy.signal API.
+
+This --- private! --- module only collects implementations of public API
+for _support_alternative_backends.
+The latter --- also private! --- module adds delegation to CuPy etc and
+re-exports decorated names to __init__.py
+"""
+
+from . import _sigtools, windows # noqa: F401
+from ._waveforms import * # noqa: F403
+from ._max_len_seq import max_len_seq # noqa: F401
+from ._upfirdn import upfirdn # noqa: F401
+
+from ._spline import sepfir2d # noqa: F401
+
+from ._spline_filters import * # noqa: F403
+from ._filter_design import * # noqa: F403
+from ._fir_filter_design import * # noqa: F403
+from ._ltisys import * # noqa: F403
+from ._lti_conversion import * # noqa: F403
+from ._signaltools import * # noqa: F403
+from ._savitzky_golay import savgol_coeffs, savgol_filter # noqa: F401
+from ._spectral_py import * # noqa: F403
+from ._short_time_fft import * # noqa: F403
+from ._peak_finding import * # noqa: F403
+from ._czt import * # noqa: F403
+from ._whittaker import whittaker_henderson # noqa: F401
+from .windows import get_window # keep this one in signal namespace # noqa: F401
+
+
+__all__ = [s for s in dir() if not s.startswith('_')]
diff --git a/.venv/lib/python3.12/site-packages/scipy/signal/_signaltools.py b/.venv/lib/python3.12/site-packages/scipy/signal/_signaltools.py
new file mode 100644
index 0000000000000000000000000000000000000000..a230802509a329f5e431d63c8f3766557ab311e9
--- /dev/null
+++ b/.venv/lib/python3.12/site-packages/scipy/signal/_signaltools.py
@@ -0,0 +1,5369 @@
+# Author: Travis Oliphant
+# 1999 -- 2002
+
+import operator
+import math
+from math import prod as _prod
+import timeit
+import warnings
+from typing import Literal
+
+from numpy._typing import ArrayLike
+
+from scipy.spatial import cKDTree
+from . import _sigtools
+from ._ltisys import dlti
+from ._upfirdn import upfirdn, _output_len, _upfirdn_modes
+from scipy import linalg, fft as sp_fft
+from scipy import ndimage
+from scipy.fft._helper import _init_nd_shape_and_axes
+import numpy as np
+from scipy.special import lambertw
+from .windows import get_window
+from ._arraytools import axis_slice, axis_reverse, odd_ext, even_ext, const_ext
+from ._filter_design import cheby1, _validate_sos, zpk2sos
+from ._fir_filter_design import firwin
+from ._sosfilt import _sosfilt
+
+from scipy._lib._array_api import (
+ array_namespace, is_torch, is_numpy, xp_copy, xp_size, xp_default_dtype,
+ xp_promote, xp_swapaxes,)
+from scipy._external.array_api_compat import is_array_api_obj
+import scipy._external.array_api_extra as xpx
+
+
+__all__ = ['correlate', 'correlation_lags', 'correlate2d',
+ 'convolve', 'convolve2d', 'fftconvolve', 'oaconvolve',
+ 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter',
+ 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2', 'envelope',
+ 'unique_roots', 'invres', 'invresz', 'residue',
+ 'residuez', 'resample', 'resample_poly', 'detrend',
+ 'lfilter_zi', 'sosfilt_zi', 'sosfiltfilt', 'choose_conv_method',
+ 'filtfilt', 'decimate', 'vectorstrength']
+
+
+_modedict = {'valid': 0, 'same': 1, 'full': 2}
+
+_boundarydict = {'fill': 0, 'pad': 0, 'wrap': 2, 'circular': 2, 'symm': 1,
+ 'symmetric': 1, 'reflect': 4}
+
+
+def _valfrommode(mode):
+ try:
+ return _modedict[mode]
+ except KeyError as e:
+ raise ValueError("Acceptable mode flags are 'valid',"
+ " 'same', or 'full'.") from e
+
+
+def _bvalfromboundary(boundary):
+ try:
+ return _boundarydict[boundary] << 2
+ except KeyError as e:
+ raise ValueError("Acceptable boundary flags are 'fill', 'circular' "
+ "(or 'wrap'), and 'symmetric' (or 'symm').") from e
+
+
+def _inputs_swap_needed(mode, shape1, shape2, axes=None):
+ """Determine if inputs arrays need to be swapped in `"valid"` mode.
+
+ If in `"valid"` mode, returns whether or not the input arrays need to be
+ swapped depending on whether `shape1` is at least as large as `shape2` in
+ every calculated dimension.
+
+ This is important for some of the correlation and convolution
+ implementations in this module, where the larger array input needs to come
+ before the smaller array input when operating in this mode.
+
+ Note that if the mode provided is not 'valid', False is immediately
+ returned.
+
+ """
+ if mode != 'valid':
+ return False
+
+ if not shape1:
+ return False
+
+ if axes is None:
+ axes = range(len(shape1))
+
+ ok1 = all(shape1[i] >= shape2[i] for i in axes)
+ ok2 = all(shape2[i] >= shape1[i] for i in axes)
+
+ if not (ok1 or ok2):
+ raise ValueError("For 'valid' mode, one must be at least "
+ "as large as the other in every dimension")
+
+ return not ok1
+
+
+def correlate(in1, in2, mode='full', method='auto'):
+ r"""
+ Cross-correlate two N-dimensional arrays.
+
+ Cross-correlate `in1` and `in2`, with the output size determined by the
+ `mode` argument.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear cross-correlation
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ Output size will be ``N``, the same size as `in1`, centered
+ with respect to the 'full' output.
+ Boundary effects may be visible.
+ method : str {'auto', 'direct', 'fft'}, optional
+ A string indicating which method to use to calculate the correlation.
+
+ ``direct``
+ The correlation is determined directly from sums, the definition of
+ correlation.
+ ``fft``
+ The Fast Fourier Transform is used to perform the correlation more
+ quickly (only available for numerical arrays.)
+ ``auto``
+ Automatically chooses direct or Fourier method based on an estimate
+ of which is faster (default). See `convolve` Notes for more detail.
+
+ .. versionadded:: 0.19.0
+
+ Returns
+ -------
+ correlate : array
+ An N-dimensional array containing a subset of the discrete linear
+ cross-correlation of `in1` with `in2`.
+
+ See Also
+ --------
+ choose_conv_method : contains more documentation on `method`.
+ correlation_lags : calculates the lag / displacement indices array for 1D
+ cross-correlation.
+
+ Notes
+ -----
+ The correlation z of two d-dimensional arrays x and y is defined as::
+
+ z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...])
+
+ This way, if ``x`` and ``y`` are 1-D arrays and ``z = correlate(x, y, 'full')``
+ then
+
+ .. math::
+
+ z[k] = \sum_{l=0}^{N-1} x_l \, y_{l-k}^{*}
+
+ for :math:`k = -(M-1), \dots, (N-1)`, where :math:`N` is the length of ``x``,
+ :math:`M` is the length of ``y``, and :math:`y_m = 0` when :math:`m` is outside the
+ valid range :math:`[0, M-1]`. The size of :math:`z` is :math:`N + M - 1` and
+ :math:`y^*` denotes the complex conjugate of :math:`y`.
+
+ ``method='fft'`` only works for numerical arrays as it relies on
+ `fftconvolve`. In certain cases (i.e., arrays of objects or when
+ rounding integers can lose precision), ``method='direct'`` is always used.
+
+ When using ``mode='same'`` with even-length inputs, the outputs of `correlate`
+ and `correlate2d` differ: There is a 1-index offset between them.
+
+ Examples
+ --------
+ Implement a matched filter using cross-correlation, to recover a signal
+ that has passed through a noisy channel.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128)
+ >>> sig_noise = sig + rng.standard_normal(len(sig))
+ >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128
+
+ >>> clock = np.arange(64, len(sig), 128)
+ >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.plot(clock, sig[clock], 'ro')
+ >>> ax_orig.set_title('Original signal')
+ >>> ax_noise.plot(sig_noise)
+ >>> ax_noise.set_title('Signal with noise')
+ >>> ax_corr.plot(corr)
+ >>> ax_corr.plot(clock, corr[clock], 'ro')
+ >>> ax_corr.axhline(0.5, ls=':')
+ >>> ax_corr.set_title('Cross-correlated with rectangular pulse')
+ >>> ax_orig.margins(0, 0.1)
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ Compute the cross-correlation of a noisy signal with the original signal.
+
+ >>> x = np.arange(128) / 128
+ >>> sig = np.sin(2 * np.pi * x)
+ >>> sig_noise = sig + rng.standard_normal(len(sig))
+ >>> corr = signal.correlate(sig_noise, sig)
+ >>> lags = signal.correlation_lags(len(sig), len(sig_noise))
+ >>> corr /= np.max(corr)
+
+ >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, figsize=(4.8, 4.8))
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('Original signal')
+ >>> ax_orig.set_xlabel('Sample Number')
+ >>> ax_noise.plot(sig_noise)
+ >>> ax_noise.set_title('Signal with noise')
+ >>> ax_noise.set_xlabel('Sample Number')
+ >>> ax_corr.plot(lags, corr)
+ >>> ax_corr.set_title('Cross-correlated signal')
+ >>> ax_corr.set_xlabel('Lag')
+ >>> ax_orig.margins(0, 0.1)
+ >>> ax_noise.margins(0, 0.1)
+ >>> ax_corr.margins(0, 0.1)
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ in1 = xp.asarray(in1)
+ in2 = xp.asarray(in2)
+
+ if in1.ndim == in2.ndim == 0:
+ in2_conj = (xp.conj(in2)
+ if xp.isdtype(in2.dtype, 'complex floating')
+ else in2)
+ return in1 * in2_conj
+ elif in1.ndim != in2.ndim:
+ raise ValueError("in1 and in2 should have the same dimensionality")
+
+ # Don't use _valfrommode, since correlate should not accept numeric modes
+ try:
+ val = _modedict[mode]
+ except KeyError as e:
+ raise ValueError("Acceptable mode flags are 'valid',"
+ " 'same', or 'full'.") from e
+
+ # this either calls fftconvolve or this function with method=='direct'
+ if method in ('fft', 'auto'):
+ return convolve(in1, _reverse_and_conj(in2, xp), mode, method)
+
+ elif method == 'direct':
+ # fastpath to faster numpy.correlate for 1d inputs when possible
+ if _np_conv_ok(in1, in2, mode, xp):
+ a_in1 = np.asarray(in1)
+ a_in2 = np.asarray(in2)
+ out = np.correlate(a_in1, a_in2, mode)
+ return xp.asarray(out)
+
+ # _correlateND is far slower when in2.size > in1.size, so swap them
+ # and then undo the effect afterward if mode == 'full'. Also, it fails
+ # with 'valid' mode if in2 is larger than in1, so swap those, too.
+ # Don't swap inputs for 'same' mode, since shape of in1 matters.
+ swapped_inputs = ((mode == 'full') and (xp_size(in2) > xp_size(in1)) or
+ _inputs_swap_needed(mode, in1.shape, in2.shape))
+
+ if swapped_inputs:
+ in1, in2 = in2, in1
+
+ # convert to numpy & back for _sigtools._correlateND
+ a_in1 = np.asarray(in1)
+ a_in2 = np.asarray(in2)
+
+ if mode == 'valid':
+ ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)]
+ out = np.empty(ps, a_in1.dtype)
+
+ z = _sigtools._correlateND(a_in1, a_in2, out, val)
+
+ else:
+ ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)]
+
+ # zero pad input
+ in1zpadded = np.zeros(ps, a_in1.dtype)
+ sc = tuple(slice(0, i) for i in in1.shape)
+ in1zpadded[sc] = a_in1.copy()
+
+ if mode == 'full':
+ out = np.empty(ps, a_in1.dtype)
+ elif mode == 'same':
+ out = np.empty(in1.shape, a_in1.dtype)
+
+ z = _sigtools._correlateND(in1zpadded, a_in2, out, val)
+
+ z = xp.asarray(z)
+
+ if swapped_inputs:
+ # Reverse and conjugate to undo the effect of swapping inputs
+ z = _reverse_and_conj(z, xp)
+
+ return z
+
+ else:
+ raise ValueError("Acceptable method flags are 'auto',"
+ " 'direct', or 'fft'.")
+
+
+def correlation_lags(in1_len, in2_len, mode='full'):
+ r"""
+ Calculates the lag / displacement indices array for 1D cross-correlation.
+
+ Parameters
+ ----------
+ in1_len : int
+ First input size.
+ in2_len : int
+ Second input size.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output.
+ See the documentation `correlate` for more information.
+
+ Returns
+ -------
+ lags : array
+ Returns an array containing cross-correlation lag/displacement indices.
+ Indices can be indexed with the np.argmax of the correlation to return
+ the lag/displacement.
+
+ See Also
+ --------
+ correlate : Compute the N-dimensional cross-correlation.
+
+ Notes
+ -----
+ Cross-correlation for continuous functions :math:`f` and :math:`g` is
+ defined as:
+
+ .. math::
+
+ \left ( f\star g \right )\left ( \tau \right )
+ \triangleq \int_{t_0}^{t_0 +T}
+ \overline{f\left ( t \right )}g\left ( t+\tau \right )dt
+
+ Where :math:`\tau` is defined as the displacement, also known as the lag.
+
+ Cross correlation for discrete functions :math:`f` and :math:`g` is
+ defined as:
+
+ .. math::
+ \left ( f\star g \right )\left [ n \right ]
+ \triangleq \sum_{-\infty}^{\infty}
+ \overline{f\left [ m \right ]}g\left [ m+n \right ]
+
+ Where :math:`n` is the lag.
+
+ Examples
+ --------
+ Cross-correlation of a signal with its time-delayed self.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> x = rng.standard_normal(1000)
+ >>> y = np.concatenate([rng.standard_normal(100), x])
+ >>> correlation = signal.correlate(x, y, mode="full")
+ >>> lags = signal.correlation_lags(x.size, y.size, mode="full")
+ >>> lag = lags[np.argmax(correlation)]
+ """
+
+ # calculate lag ranges in different modes of operation
+ if mode == "full":
+ # the output is the full discrete linear convolution
+ # of the inputs. (Default)
+ lags = np.arange(-in2_len + 1, in1_len)
+ elif mode == "same":
+ # the output is the same size as `in1`, centered
+ # with respect to the 'full' output.
+ # calculate the full output
+ lags = np.arange(-in2_len + 1, in1_len)
+ # determine the midpoint in the full output
+ mid = lags.size // 2
+ # determine lag_bound to be used with respect
+ # to the midpoint
+ lag_bound = in1_len // 2
+ # calculate lag ranges for even and odd scenarios
+ if in1_len % 2 == 0:
+ lags = lags[(mid-lag_bound):(mid+lag_bound)]
+ else:
+ lags = lags[(mid-lag_bound):(mid+lag_bound)+1]
+ elif mode == "valid":
+ # the output consists only of those elements that do not
+ # rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ # must be at least as large as the other in every dimension.
+
+ # the lag_bound will be either negative or positive
+ # this let's us infer how to present the lag range
+ lag_bound = in1_len - in2_len
+ if lag_bound >= 0:
+ lags = np.arange(lag_bound + 1)
+ else:
+ lags = np.arange(lag_bound, 1)
+ else:
+ raise ValueError(f"Mode {mode} is invalid")
+ return lags
+
+
+def _centered(arr, newshape):
+ # Return the center newshape portion of the array.
+ newshape = np.asarray(newshape)
+ currshape = np.array(arr.shape)
+ startind = (currshape - newshape) // 2
+ endind = startind + newshape
+ myslice = [slice(startind[k], endind[k]) for k in range(len(endind))]
+ return arr[tuple(myslice)]
+
+
+def _init_freq_conv_axes(in1, in2, mode, axes, sorted_axes=False):
+ """Handle the axes argument for frequency-domain convolution.
+
+ Returns the inputs and axes in a standard form, eliminating redundant axes,
+ swapping the inputs if necessary, and checking for various potential
+ errors.
+
+ Parameters
+ ----------
+ in1 : array
+ First input.
+ in2 : array
+ Second input.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output.
+ See the documentation `fftconvolve` for more information.
+ axes : list of ints
+ Axes over which to compute the FFTs.
+ sorted_axes : bool, optional
+ If `True`, sort the axes.
+ Default is `False`, do not sort.
+
+ Returns
+ -------
+ in1 : array
+ The first input, possible swapped with the second input.
+ in2 : array
+ The second input, possible swapped with the first input.
+ axes : list of ints
+ Axes over which to compute the FFTs.
+
+ """
+ s1 = in1.shape
+ s2 = in2.shape
+ noaxes = axes is None
+
+ _, axes = _init_nd_shape_and_axes(in1, shape=None, axes=axes)
+
+ if not noaxes and not len(axes):
+ raise ValueError("when provided, axes cannot be empty")
+
+ # Axes of length 1 can rely on broadcasting rules for multiply,
+ # no fft needed.
+ axes = [a for a in axes if s1[a] != 1 and s2[a] != 1]
+
+ if sorted_axes:
+ axes.sort()
+
+ if not all(s1[a] == s2[a] or s1[a] == 1 or s2[a] == 1
+ for a in range(in1.ndim) if a not in axes):
+ raise ValueError("incompatible shapes for in1 and in2:"
+ f" {s1} and {s2}")
+
+ # Check that input sizes are compatible with 'valid' mode.
+ if _inputs_swap_needed(mode, s1, s2, axes=axes):
+ # Convolution is commutative; order doesn't have any effect on output.
+ in1, in2 = in2, in1
+
+ return in1, in2, axes
+
+
+def _freq_domain_conv(xp, in1, in2, axes, shape, calc_fast_len=False):
+ """Convolve two arrays in the frequency domain.
+
+ This function implements only base the FFT-related operations.
+ Specifically, it converts the signals to the frequency domain, multiplies
+ them, then converts them back to the time domain. Calculations of axes,
+ shapes, convolution mode, etc. are implemented in higher level-functions,
+ such as `fftconvolve` and `oaconvolve`. Those functions should be used
+ instead of this one.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ axes : array_like of ints
+ Axes over which to compute the FFTs.
+ shape : array_like of ints
+ The sizes of the FFTs.
+ calc_fast_len : bool, optional
+ If `True`, set each value of `shape` to the next fast FFT length.
+ Default is `False`, use `axes` as-is.
+
+ Returns
+ -------
+ out : array
+ An N-dimensional array containing the discrete linear convolution of
+ `in1` with `in2`.
+
+ """
+ if not len(axes):
+ return in1 * in2
+
+ complex_result = (xp.isdtype(in1.dtype, 'complex floating') or
+ xp.isdtype(in2.dtype, 'complex floating'))
+
+ if calc_fast_len:
+ # Speed up FFT by padding to optimal size.
+ fshape = [
+ sp_fft.next_fast_len(shape[a], not complex_result) for a in axes]
+ else:
+ fshape = shape
+
+ if not complex_result:
+ fft, ifft = sp_fft.rfftn, sp_fft.irfftn
+ else:
+ fft, ifft = sp_fft.fftn, sp_fft.ifftn
+
+ if xp.isdtype(in1.dtype, 'integral'):
+ in1 = xp.astype(in1, xp_default_dtype(xp))
+ if xp.isdtype(in2.dtype, 'integral'):
+ in2 = xp.astype(in2, xp_default_dtype(xp))
+
+ sp1 = fft(in1, fshape, axes=axes)
+ sp2 = fft(in2, fshape, axes=axes)
+
+ ret = ifft(sp1 * sp2, fshape, axes=axes)
+
+ if calc_fast_len:
+ fslice = tuple([slice(sz) for sz in shape])
+ ret = ret[fslice]
+
+ return ret
+
+
+def _apply_conv_mode(ret, s1, s2, mode, axes, xp):
+ """Calculate the convolution result shape based on the `mode` argument.
+
+ Returns the result sliced to the correct size for the given mode.
+
+ Parameters
+ ----------
+ ret : array
+ The result array, with the appropriate shape for the 'full' mode.
+ s1 : list of int
+ The shape of the first input.
+ s2 : list of int
+ The shape of the second input.
+ mode : str {'full', 'valid', 'same'}
+ A string indicating the size of the output.
+ See the documentation `fftconvolve` for more information.
+ axes : list of ints
+ Axes over which to compute the convolution.
+
+ Returns
+ -------
+ ret : array
+ A copy of `res`, sliced to the correct size for the given `mode`.
+
+ """
+ if mode == "full":
+ return xp_copy(ret, xp=xp)
+ elif mode == "same":
+ return xp_copy(_centered(ret, s1), xp=xp)
+ elif mode == "valid":
+ shape_valid = [ret.shape[a] if a not in axes else s1[a] - s2[a] + 1
+ for a in range(ret.ndim)]
+ return xp_copy(_centered(ret, shape_valid), xp=xp)
+ else:
+ raise ValueError("acceptable mode flags are 'valid',"
+ " 'same', or 'full'")
+
+
+def fftconvolve(in1, in2, mode="full", axes=None):
+ """Convolve two N-dimensional arrays using FFT.
+
+ Convolve `in1` and `in2` using the fast Fourier transform method, with
+ the output size determined by the `mode` argument.
+
+ This is generally much faster than `convolve` for large arrays (n > ~500),
+ but can be slower when only a few output values are needed, and can only
+ output float arrays (int or object array inputs will be cast to float).
+
+ As of v0.19, `convolve` automatically chooses this method or the direct
+ method based on an estimation of which is faster.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ Output size will be ``N``, the same size as `in1`, centered
+ with respect to the 'full' output.
+ Boundary effects may be visible.
+ axes : int or array_like of ints or None, optional
+ Axes over which to compute the convolution.
+ The default is over all axes.
+
+ Returns
+ -------
+ out : array
+ An N-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ The output size along each axis depends on ``mode``. For input
+ sizes ``N`` and ``M`` along a given axis:
+
+ - ``full`` : ``N + M - 1``
+ - ``same`` : ``N`` (same as the size of `in1`)
+ - ``valid`` : ``max(N, M) - min(N, M) + 1``
+
+ See Also
+ --------
+ convolve : Uses the direct convolution or FFT convolution algorithm
+ depending on which is faster.
+ oaconvolve : Uses the overlap-add method to do convolution, which is
+ generally faster when the input arrays are large and
+ significantly different in size.
+
+ Examples
+ --------
+ Autocorrelation of white noise is an impulse.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> sig = rng.standard_normal(1000)
+ >>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full')
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('White noise')
+ >>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr)
+ >>> ax_mag.set_title('Autocorrelation')
+ >>> fig.tight_layout()
+ >>> fig.show()
+
+ Gaussian blur implemented using FFT convolution. Notice the dark borders
+ around the image, due to the zero-padding beyond its boundaries.
+ The `convolve2d` function allows for other types of image boundaries,
+ but is far slower.
+
+ >>> from scipy import datasets
+ >>> face = datasets.face(gray=True)
+ >>> kernel = np.outer(signal.windows.gaussian(70, 8),
+ ... signal.windows.gaussian(70, 8))
+ >>> blurred = signal.fftconvolve(face, kernel, mode='same')
+
+ >>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(3, 1,
+ ... figsize=(6, 15))
+ >>> ax_orig.imshow(face, cmap='gray')
+ >>> ax_orig.set_title('Original')
+ >>> ax_orig.set_axis_off()
+ >>> ax_kernel.imshow(kernel, cmap='gray')
+ >>> ax_kernel.set_title('Gaussian kernel')
+ >>> ax_kernel.set_axis_off()
+ >>> ax_blurred.imshow(blurred, cmap='gray')
+ >>> ax_blurred.set_title('Blurred')
+ >>> ax_blurred.set_axis_off()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ in1 = xp.asarray(in1)
+ in2 = xp.asarray(in2)
+
+ if in1.ndim == in2.ndim == 0: # scalar inputs
+ return in1 * in2
+ elif in1.ndim != in2.ndim:
+ raise ValueError("in1 and in2 should have the same dimensionality")
+ elif xp_size(in1) == 0 or xp_size(in2) == 0: # empty arrays
+ return xp.asarray([])
+
+ in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes,
+ sorted_axes=False)
+
+ s1 = in1.shape
+ s2 = in2.shape
+
+ shape = [max((s1[i], s2[i])) if i not in axes else s1[i] + s2[i] - 1
+ for i in range(in1.ndim)]
+
+ ret = _freq_domain_conv(xp, in1, in2, axes, shape, calc_fast_len=True)
+
+ return _apply_conv_mode(ret, s1, s2, mode, axes, xp=xp)
+
+
+def _calc_oa_lens(s1, s2):
+ """Calculate the optimal FFT lengths for overlap-add convolution.
+
+ The calculation is done for a single dimension.
+
+ Parameters
+ ----------
+ s1 : int
+ Size of the dimension for the first array.
+ s2 : int
+ Size of the dimension for the second array.
+
+ Returns
+ -------
+ block_size : int
+ The size of the FFT blocks.
+ overlap : int
+ The amount of overlap between two blocks.
+ in1_step : int
+ The size of each step for the first array.
+ in2_step : int
+ The size of each step for the second array.
+
+ """
+ # Set up the arguments for the conventional FFT approach.
+ fallback = (s1+s2-1, None, s1, s2)
+
+ # Use conventional FFT convolve if sizes are same.
+ if s1 == s2 or s1 == 1 or s2 == 1:
+ return fallback
+
+ if s2 > s1:
+ s1, s2 = s2, s1
+ swapped = True
+ else:
+ swapped = False
+
+ # There cannot be a useful block size if s2 is more than half of s1.
+ if s2 >= s1/2:
+ return fallback
+
+ # Derivation of optimal block length
+ # For original formula see:
+ # https://en.wikipedia.org/wiki/Overlap-add_method
+ #
+ # Formula:
+ # K = overlap = s2-1
+ # N = block_size
+ # C = complexity
+ # e = exponential, exp(1)
+ #
+ # C = (N*(log2(N)+1))/(N-K)
+ # C = (N*log2(2N))/(N-K)
+ # C = N/(N-K) * log2(2N)
+ # C1 = N/(N-K)
+ # C2 = log2(2N) = ln(2N)/ln(2)
+ #
+ # dC1/dN = (1*(N-K)-N)/(N-K)^2 = -K/(N-K)^2
+ # dC2/dN = 2/(2*N*ln(2)) = 1/(N*ln(2))
+ #
+ # dC/dN = dC1/dN*C2 + dC2/dN*C1
+ # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + N/(N*ln(2)*(N-K))
+ # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + 1/(ln(2)*(N-K))
+ # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + (N-K)/(ln(2)*(N-K)^2)
+ # dC/dN = (-K*ln(2N) + (N-K)/(ln(2)*(N-K)^2)
+ # dC/dN = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2)
+ #
+ # Solve for minimum, where dC/dN = 0
+ # 0 = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2)
+ # 0 * ln(2)*(N-K)^2 = N - K*ln(2N) - K
+ # 0 = N - K*ln(2N) - K
+ # 0 = N - K*(ln(2N) + 1)
+ # 0 = N - K*ln(2Ne)
+ # N = K*ln(2Ne)
+ # N/K = ln(2Ne)
+ #
+ # e^(N/K) = e^ln(2Ne)
+ # e^(N/K) = 2Ne
+ # 1/e^(N/K) = 1/(2*N*e)
+ # e^(N/-K) = 1/(2*N*e)
+ # e^(N/-K) = K/N*1/(2*K*e)
+ # N/K*e^(N/-K) = 1/(2*e*K)
+ # N/-K*e^(N/-K) = -1/(2*e*K)
+ #
+ # Using Lambert W function
+ # https://en.wikipedia.org/wiki/Lambert_W_function
+ # x = W(y) It is the solution to y = x*e^x
+ # x = N/-K
+ # y = -1/(2*e*K)
+ #
+ # N/-K = W(-1/(2*e*K))
+ #
+ # N = -K*W(-1/(2*e*K))
+ overlap = s2-1
+ opt_size = -overlap*lambertw(-1/(2*math.e*overlap), k=-1).real
+ block_size = sp_fft.next_fast_len(math.ceil(opt_size))
+
+ # Use conventional FFT convolve if there is only going to be one block.
+ if block_size >= s1:
+ return fallback
+
+ if not swapped:
+ in1_step = block_size-s2+1
+ in2_step = s2
+ else:
+ in1_step = s2
+ in2_step = block_size-s2+1
+
+ return block_size, overlap, in1_step, in2_step
+
+
+# may want to look at moving xp_swapaxes and this to array-api-extra,
+# cross-ref https://github.com/data-apis/array-api-extra/issues/97
+def _split(x, indices_or_sections, axis, xp):
+ """A simplified version of np.split, with `indices` being a list.
+ """
+ # https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_shape_base_impl.py#L743
+ Ntotal = x.shape[axis]
+
+ # handle array case.
+ Nsections = len(indices_or_sections) + 1
+ div_points = [0] + list(indices_or_sections) + [Ntotal]
+
+ sub_arys = []
+ sary = xp_swapaxes(x, axis, 0, xp=xp)
+ for i in range(Nsections):
+ st = div_points[i]
+ end = div_points[i + 1]
+ sub_arys.append(xp_swapaxes(sary[st:end, ...], axis, 0, xp=xp))
+
+ return sub_arys
+
+
+def oaconvolve(in1, in2, mode="full", axes=None):
+ """Convolve two N-dimensional arrays using the overlap-add method.
+
+ Convolve `in1` and `in2` using the overlap-add method, with
+ the output size determined by the `mode` argument.
+
+ This is generally much faster than `convolve` for large arrays (n > ~500),
+ and generally much faster than `fftconvolve` when one array is much
+ larger than the other, but can be slower when only a few output values are
+ needed or when the arrays are very similar in shape, and can only
+ output float arrays (int or object array inputs will be cast to float).
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ Output size will be ``N``, the same size as `in1`, centered
+ with respect to the 'full' output.
+ Boundary effects may be visible.
+ axes : int or array_like of ints or None, optional
+ Axes over which to compute the convolution.
+ The default is over all axes.
+
+ Returns
+ -------
+ out : array
+ An N-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ The output size along each axis depends on ``mode``. For input
+ sizes ``N`` and ``M`` along a given axis:
+
+ - ``full`` : ``N + M - 1``
+ - ``same`` : ``N`` (same as the size of `in1`)
+ - ``valid`` : ``max(N, M) - min(N, M) + 1``
+
+ See Also
+ --------
+ convolve : Uses the direct convolution or FFT convolution algorithm
+ depending on which is faster.
+ fftconvolve : An implementation of convolution using FFT.
+
+ Notes
+ -----
+ .. versionadded:: 1.4.0
+
+ References
+ ----------
+ .. [1] Wikipedia, "Overlap-add_method".
+ https://en.wikipedia.org/wiki/Overlap-add_method
+ .. [2] Richard G. Lyons. Understanding Digital Signal Processing,
+ Third Edition, 2011. Chapter 13.10.
+ ISBN 13: 978-0137-02741-5
+
+ Examples
+ --------
+ Convolve a 100,000 sample signal with a 512-sample filter.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> sig = rng.standard_normal(100000)
+ >>> filt = signal.firwin(512, 0.01)
+ >>> fsig = signal.oaconvolve(sig, filt)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('White noise')
+ >>> ax_mag.plot(fsig)
+ >>> ax_mag.set_title('Filtered noise')
+ >>> fig.tight_layout()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ in1 = xp.asarray(in1)
+ in2 = xp.asarray(in2)
+
+ if in1.ndim == in2.ndim == 0: # scalar inputs
+ return in1 * in2
+ elif in1.ndim != in2.ndim:
+ raise ValueError("in1 and in2 should have the same dimensionality")
+ elif in1.size == 0 or in2.size == 0: # empty arrays
+ return xp.asarray([])
+ elif in1.shape == in2.shape: # Equivalent to fftconvolve
+ return fftconvolve(in1, in2, mode=mode, axes=axes)
+
+ in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes,
+ sorted_axes=True)
+
+ s1 = in1.shape
+ s2 = in2.shape
+
+ if not axes:
+ ret = in1 * in2
+ return _apply_conv_mode(ret, s1, s2, mode, axes, xp)
+
+ # Calculate this now since in1 is changed later
+ shape_final = [None if i not in axes else
+ s1[i] + s2[i] - 1 for i in range(in1.ndim)]
+
+ # Calculate the block sizes for the output, steps, first and second inputs.
+ # It is simpler to calculate them all together than doing them in separate
+ # loops due to all the special cases that need to be handled.
+ optimal_sizes = ((-1, -1, s1[i], s2[i]) if i not in axes else
+ _calc_oa_lens(s1[i], s2[i]) for i in range(in1.ndim))
+ block_size, overlaps, \
+ in1_step, in2_step = zip(*optimal_sizes)
+
+ # Fall back to fftconvolve if there is only one block in every dimension.
+ if in1_step == s1 and in2_step == s2:
+ return fftconvolve(in1, in2, mode=mode, axes=axes)
+
+ # Figure out the number of steps and padding.
+ # This would get too complicated in a list comprehension.
+ nsteps1 = []
+ nsteps2 = []
+ pad_size1 = []
+ pad_size2 = []
+ for i in range(in1.ndim):
+ if i not in axes:
+ pad_size1 += [(0, 0)]
+ pad_size2 += [(0, 0)]
+ continue
+
+ if s1[i] > in1_step[i]:
+ curnstep1 = math.ceil((s1[i]+1)/in1_step[i])
+ if (block_size[i] - overlaps[i])*curnstep1 < shape_final[i]:
+ curnstep1 += 1
+
+ curpad1 = curnstep1*in1_step[i] - s1[i]
+ else:
+ curnstep1 = 1
+ curpad1 = 0
+
+ if s2[i] > in2_step[i]:
+ curnstep2 = math.ceil((s2[i]+1)/in2_step[i])
+ if (block_size[i] - overlaps[i])*curnstep2 < shape_final[i]:
+ curnstep2 += 1
+
+ curpad2 = curnstep2*in2_step[i] - s2[i]
+ else:
+ curnstep2 = 1
+ curpad2 = 0
+
+ nsteps1 += [curnstep1]
+ nsteps2 += [curnstep2]
+ pad_size1 += [(0, curpad1)]
+ pad_size2 += [(0, curpad2)]
+
+ # Pad the array to a size that can be reshaped to the desired shape
+ # if necessary.
+ if not all(curpad == (0, 0) for curpad in pad_size1):
+ in1 = xpx.pad(in1, pad_size1, mode='constant', constant_values=0, xp=xp)
+
+ if not all(curpad == (0, 0) for curpad in pad_size2):
+ in2 = xpx.pad(in2, pad_size2, mode='constant', constant_values=0, xp=xp)
+
+ # Reshape the overlap-add parts to input block sizes.
+ split_axes = [iax+i for i, iax in enumerate(axes)]
+ fft_axes = [iax+1 for iax in split_axes]
+
+ # We need to put each new dimension before the corresponding dimension
+ # being reshaped in order to get the data in the right layout at the end.
+ reshape_size1 = list(in1_step)
+ reshape_size2 = list(in2_step)
+ for i, iax in enumerate(split_axes):
+ reshape_size1.insert(iax, nsteps1[i])
+ reshape_size2.insert(iax, nsteps2[i])
+
+ in1 = xp.reshape(in1, tuple(reshape_size1))
+ in2 = xp.reshape(in2, tuple(reshape_size2))
+
+ # Do the convolution.
+ fft_shape = [block_size[i] for i in axes]
+ ret = _freq_domain_conv(xp, in1, in2, fft_axes, fft_shape, calc_fast_len=False)
+
+ # Do the overlap-add.
+ for ax, ax_fft, ax_split in zip(axes, fft_axes, split_axes):
+ overlap = overlaps[ax]
+ if overlap is None:
+ continue
+
+ ret, overpart = _split(ret, [-overlap], ax_fft, xp=xp)
+ overpart = _split(overpart, [-1], ax_split, xp=xp)[0]
+
+ overlap_slice = [slice(None)] * ret.ndim
+ overlap_slice[ax_fft] = slice(0, overlap)
+ overlap_slice[ax_split] = slice(1, None)
+ ret = xpx.at(ret)[tuple(overlap_slice)].add(overpart)
+
+ # Reshape back to the correct dimensionality.
+ shape_ret = [ret.shape[i] if i not in fft_axes else
+ ret.shape[i]*ret.shape[i-1]
+ for i in range(ret.ndim) if i not in split_axes]
+ ret = xp.reshape(ret, tuple(shape_ret))
+
+ # Slice to the correct size.
+ slice_final = tuple([slice(islice) for islice in shape_final])
+ ret = ret[slice_final]
+
+ return _apply_conv_mode(ret, s1, s2, mode, axes, xp)
+
+
+def _numeric_arrays(arrays, kinds='buifc', xp=None):
+ """
+ See if a list of arrays are all numeric.
+
+ Parameters
+ ----------
+ arrays : array or list of arrays
+ arrays to check if numeric.
+ kinds : string-like
+ The dtypes of the arrays to be checked. If the dtype.kind of
+ the ndarrays are not in this string the function returns False and
+ otherwise returns True.
+ """
+ if xp is None:
+ xp = array_namespace(*arrays)
+ if not is_numpy(xp):
+ return True
+
+ if type(arrays) is np.ndarray:
+ return arrays.dtype.kind in kinds
+ for array_ in arrays:
+ if array_.dtype.kind not in kinds:
+ return False
+ return True
+
+
+def _conv_ops(x_shape, h_shape, mode):
+ """
+ Find the number of operations required for direct/fft methods of
+ convolution. The direct operations were recorded by making a dummy class to
+ record the number of operations by overriding ``__mul__`` and ``__add__``.
+ The FFT operations rely on the (well-known) computational complexity of the
+ FFT (and the implementation of ``_freq_domain_conv``).
+
+ """
+ if mode == "full":
+ out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)]
+ elif mode == "valid":
+ out_shape = [abs(n - k) + 1 for n, k in zip(x_shape, h_shape)]
+ elif mode == "same":
+ out_shape = x_shape
+ else:
+ raise ValueError("Acceptable mode flags are 'valid',"
+ f" 'same', or 'full', not mode={mode}")
+
+ s1, s2 = x_shape, h_shape
+ if len(x_shape) == 1:
+ s1, s2 = s1[0], s2[0]
+ if mode == "full":
+ direct_ops = s1 * s2
+ elif mode == "valid":
+ direct_ops = (s2 - s1 + 1) * s1 if s2 >= s1 else (s1 - s2 + 1) * s2
+ elif mode == "same":
+ direct_ops = (s1 * s2 if s1 < s2 else
+ s1 * s2 - (s2 // 2) * ((s2 + 1) // 2))
+ else:
+ if mode == "full":
+ direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape)
+ elif mode == "valid":
+ direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape)
+ elif mode == "same":
+ direct_ops = _prod(s1) * _prod(s2)
+
+ full_out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)]
+ N = _prod(full_out_shape)
+ fft_ops = 3 * N * np.log(N) # 3 separate FFTs of size full_out_shape
+ return fft_ops, direct_ops
+
+
+def _fftconv_faster(x, h, mode):
+ """
+ See if using fftconvolve or convolve is faster.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ Signal
+ h : np.ndarray
+ Kernel
+ mode : str
+ Mode passed to convolve
+
+ Returns
+ -------
+ fft_faster : bool
+
+ Notes
+ -----
+ See docstring of `choose_conv_method` for details on tuning hardware.
+
+ See pull request 11031 for more detail:
+ https://github.com/scipy/scipy/pull/11031.
+
+ """
+ fft_ops, direct_ops = _conv_ops(x.shape, h.shape, mode)
+ offset = -1e-3 if x.ndim == 1 else -1e-4
+ constants = {
+ "valid": (1.89095737e-9, 2.1364985e-10, offset),
+ "full": (1.7649070e-9, 2.1414831e-10, offset),
+ "same": (3.2646654e-9, 2.8478277e-10, offset)
+ if h.size <= x.size
+ else (3.21635404e-9, 1.1773253e-8, -1e-5),
+ } if x.ndim == 1 else {
+ "valid": (1.85927e-9, 2.11242e-8, offset),
+ "full": (1.99817e-9, 1.66174e-8, offset),
+ "same": (2.04735e-9, 1.55367e-8, offset),
+ }
+ O_fft, O_direct, O_offset = constants[mode]
+ return O_fft * fft_ops < O_direct * direct_ops + O_offset
+
+
+def _reverse_and_conj(x, xp):
+ """
+ Reverse array `x` in all dimensions and perform the complex conjugate
+ """
+ if not is_torch(xp):
+ reverse = (slice(None, None, -1),) * x.ndim
+ x_rev = x[reverse]
+ else:
+ # NB: is a copy, not a view as torch does not allow negative indices
+ # in slices, x-ref https://github.com/pytorch/pytorch/issues/59786
+ x_rev = xp.flip(x)
+
+ # cf https://github.com/data-apis/array-api/issues/824
+ if xp.isdtype(x.dtype, 'complex floating'):
+ return xp.conj(x_rev)
+ else:
+ return x_rev
+
+
+def _np_conv_ok(volume, kernel, mode, xp):
+ """
+ See if numpy supports convolution of `volume` and `kernel` (i.e. both are
+ 1D ndarrays and of the appropriate shape). NumPy's 'same' mode uses the
+ size of the larger input, while SciPy's uses the size of the first input.
+
+ Invalid mode strings will return False and be caught by the calling func.
+ """
+ if volume.ndim == kernel.ndim == 1:
+ if mode in ('full', 'valid'):
+ return True
+ elif mode == 'same':
+ return xp_size(volume) >= xp_size(kernel)
+ else:
+ return False
+
+
+def _timeit_fast(stmt="pass", setup="pass", repeat=3):
+ """
+ Returns the time the statement/function took, in seconds.
+
+ Faster, less precise version of IPython's timeit. `stmt` can be a statement
+ written as a string or a callable.
+
+ Will do only 1 loop (like IPython's timeit) with no repetitions
+ (unlike IPython) for very slow functions. For fast functions, only does
+ enough loops to take 5 ms, which seems to produce similar results (on
+ Windows at least), and avoids doing an extraneous cycle that isn't
+ measured.
+
+ """
+ timer = timeit.Timer(stmt, setup)
+
+ # determine number of calls per rep so total time for 1 rep >= 5 ms
+ x = 0
+ for p in range(0, 10):
+ number = 10**p
+ x = timer.timeit(number) # seconds
+ if x >= 5e-3 / 10: # 5 ms for final test, 1/10th that for this one
+ break
+ if x > 1: # second
+ # If it's macroscopic, don't bother with repetitions
+ best = x
+ else:
+ number *= 10
+ r = timer.repeat(repeat, number)
+ best = min(r)
+
+ sec = best / number
+ return sec
+
+
+def choose_conv_method(in1, in2, mode='full', measure=False):
+ """
+ Find the fastest convolution/correlation method.
+
+ This primarily exists to be called during the ``method='auto'`` option in
+ `convolve` and `correlate`. It can also be used to determine the value of
+ ``method`` for many different convolutions of the same dtype/shape.
+ In addition, it supports timing the convolution to adapt the value of
+ ``method`` to a particular set of inputs and/or hardware.
+
+ Parameters
+ ----------
+ in1 : array_like
+ The first argument passed into the convolution function.
+ in2 : array_like
+ The second argument passed into the convolution function.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding.
+ ``same``
+ Output size will be ``N``, the same size as `in1`, centered
+ with respect to the 'full' output.
+ Boundary effects may be visible.
+ measure : bool, optional
+ If True, run and time the convolution of `in1` and `in2` with both
+ methods and return the fastest. If False (default), predict the fastest
+ method using precomputed values.
+
+ Returns
+ -------
+ method : str
+ A string indicating which convolution method is fastest, either
+ 'direct' or 'fft'
+ times : dict, optional
+ A dictionary containing the times (in seconds) needed for each method.
+ This value is only returned if ``measure=True``.
+
+ See Also
+ --------
+ convolve
+ correlate
+
+ Notes
+ -----
+ Generally, this method is 99% accurate for 2D signals and 85% accurate
+ for 1D signals for randomly chosen input sizes. For precision, use
+ ``measure=True`` to find the fastest method by timing the convolution.
+ This can be used to avoid the minimal overhead of finding the fastest
+ ``method`` later, or to adapt the value of ``method`` to a particular set
+ of inputs.
+
+ Experiments were run on an Amazon EC2 r5a.2xlarge machine to test this
+ function. These experiments measured the ratio between the time required
+ when using ``method='auto'`` and the time required for the fastest method
+ (i.e., ``ratio = time_auto / min(time_fft, time_direct)``). In these
+ experiments, we found:
+
+ * There is a 95% chance of this ratio being less than 1.5 for 1D signals
+ and a 99% chance of being less than 2.5 for 2D signals.
+ * The ratio was always less than 2.5/5 for 1D/2D signals respectively.
+ * This function is most inaccurate for 1D convolutions that take between 1
+ and 10 milliseconds with ``method='direct'``. A good proxy for this
+ (at least in our experiments) is ``1e6 <= in1.size * in2.size <= 1e7``.
+
+ The 2D results almost certainly generalize to 3D/4D/etc because the
+ implementation is the same (the 1D implementation is different).
+
+ All the numbers above are specific to the EC2 machine. However, we did find
+ that this function generalizes fairly decently across hardware. The speed
+ tests were of similar quality (and even slightly better) than the same
+ tests performed on the machine to tune this function's numbers (a mid-2014
+ 15-inch MacBook Pro with 16GB RAM and a 2.5GHz Intel i7 processor).
+
+ There are cases when `fftconvolve` supports the inputs but this function
+ returns `direct` (e.g., to protect against floating point integer
+ precision).
+
+ .. versionadded:: 0.19
+
+ Examples
+ --------
+ Estimate the fastest method for a given input:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> img = rng.random((32, 32))
+ >>> filter = rng.random((8, 8))
+ >>> method = signal.choose_conv_method(img, filter, mode='same')
+ >>> method
+ 'fft'
+
+ This can then be applied to other arrays of the same dtype and shape:
+
+ >>> img2 = rng.random((32, 32))
+ >>> filter2 = rng.random((8, 8))
+ >>> corr2 = signal.correlate(img2, filter2, mode='same', method=method)
+ >>> conv2 = signal.convolve(img2, filter2, mode='same', method=method)
+
+ The output of this function (``method``) works with `correlate` and
+ `convolve`.
+
+ """
+ xp = array_namespace(in1, in2)
+
+ volume = xp.asarray(in1)
+ kernel = xp.asarray(in2)
+
+ if measure:
+ times = {}
+ for method in ['fft', 'direct']:
+ times[method] = _timeit_fast(lambda: convolve(volume, kernel,
+ mode=mode, method=method))
+
+ chosen_method = 'fft' if times['fft'] < times['direct'] else 'direct'
+ return chosen_method, times
+
+ # for integer input,
+ # catch when more precision required than float provides (representing an
+ # integer as float can lose precision in fftconvolve if larger than 2**52)
+ if any([_numeric_arrays([x], kinds='ui', xp=xp) for x in [volume, kernel]]):
+ max_value = int(xp.max(xp.abs(volume))) * int(xp.max(xp.abs(kernel)))
+ max_value *= int(min(xp_size(volume), xp_size(kernel)))
+ if max_value > 2**np.finfo('float').nmant - 1:
+ return 'direct'
+
+ if _numeric_arrays([volume, kernel], kinds='b', xp=xp):
+ return 'direct'
+
+ if _numeric_arrays([volume, kernel], xp=xp):
+ if _fftconv_faster(volume, kernel, mode):
+ return 'fft'
+
+ return 'direct'
+
+
+def convolve(in1, in2, mode='full', method='auto'):
+ """
+ Convolve two N-dimensional arrays.
+
+ Convolve `in1` and `in2`, with the output size determined by the
+ `mode` argument.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ Output size will be ``N``, the same size as `in1`, centered
+ with respect to the 'full' output.
+ Boundary effects may be visible.
+ method : str {'auto', 'direct', 'fft'}, optional
+ A string indicating which method to use to calculate the convolution.
+
+ ``direct``
+ The convolution is determined directly from sums, the definition of
+ convolution.
+ ``fft``
+ The Fourier Transform is used to perform the convolution by calling
+ `fftconvolve`.
+ ``auto``
+ Automatically chooses direct or Fourier method based on an estimate
+ of which is faster (default). See Notes for more detail.
+
+ .. versionadded:: 0.19.0
+
+ Returns
+ -------
+ convolve : array
+ An N-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ The output size along each axis depends on ``mode``. For input
+ sizes ``N`` and ``M`` along a given axis:
+
+ - ``full`` : ``N + M - 1``
+ - ``same`` : ``N`` (same as the size of `in1`)
+ - ``valid`` : ``max(N, M) - min(N, M) + 1``
+
+ Warns
+ -----
+ RuntimeWarning
+ Use of the FFT convolution on input containing NAN or INF will lead
+ to the entire output being NAN or INF. Use method='direct' when your
+ input contains NAN or INF values.
+
+ See Also
+ --------
+ numpy.polymul : performs polynomial multiplication (same operation, but
+ also accepts poly1d objects)
+ choose_conv_method : chooses the fastest appropriate convolution method
+ fftconvolve : Always uses the FFT method.
+ oaconvolve : Uses the overlap-add method to do convolution, which is
+ generally faster when the input arrays are large and
+ significantly different in size.
+
+ Notes
+ -----
+ By default, `convolve` and `correlate` use ``method='auto'``, which calls
+ `choose_conv_method` to choose the fastest method using pre-computed
+ values (`choose_conv_method` can also measure real-world timing with a
+ keyword argument). Because `fftconvolve` relies on floating point numbers,
+ there are certain constraints that may force ``method='direct'`` (more detail
+ in `choose_conv_method` docstring).
+
+ Examples
+ --------
+ Smooth a square pulse using a Hann window:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> sig = np.repeat([0., 1., 0.], 100)
+ >>> win = signal.windows.hann(50)
+ >>> filtered = signal.convolve(sig, win, mode='same') / sum(win)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_win, ax_filt) = plt.subplots(3, 1, sharex=True)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('Original pulse')
+ >>> ax_orig.margins(0, 0.1)
+ >>> ax_win.plot(win)
+ >>> ax_win.set_title('Filter impulse response')
+ >>> ax_win.margins(0, 0.1)
+ >>> ax_filt.plot(filtered)
+ >>> ax_filt.set_title('Filtered signal')
+ >>> ax_filt.margins(0, 0.1)
+ >>> fig.tight_layout()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ volume = xp.asarray(in1)
+ kernel = xp.asarray(in2)
+
+ if volume.ndim == kernel.ndim == 0:
+ return volume * kernel
+ elif volume.ndim != kernel.ndim:
+ raise ValueError("volume and kernel should have the same "
+ "dimensionality")
+
+ if _inputs_swap_needed(mode, volume.shape, kernel.shape):
+ # Convolution is commutative; order doesn't have any effect on output
+ volume, kernel = kernel, volume
+
+ if method == 'auto':
+ method = choose_conv_method(volume, kernel, mode=mode)
+
+ if method == 'fft':
+ out = fftconvolve(volume, kernel, mode=mode)
+ result_type = xp.result_type(volume, kernel)
+ if xp.isdtype(result_type, 'integral'):
+ out = xp.round(out)
+
+ if xp.isnan(xp.reshape(out, (-1,))[0]) or xp.isinf(xp.reshape(out, (-1,))[0]):
+ warnings.warn("Use of fft convolution on input with NAN or inf"
+ " results in NAN or inf output. Consider using"
+ " method='direct' instead.",
+ category=RuntimeWarning, stacklevel=2)
+
+ return xp.astype(out, result_type)
+ elif method == 'direct':
+ # fastpath to faster numpy.convolve for 1d inputs when possible
+ if _np_conv_ok(volume, kernel, mode, xp):
+ # convert to numpy and back
+ a_volume = np.asarray(volume)
+ a_kernel = np.asarray(kernel)
+ out = np.convolve(a_volume, a_kernel, mode)
+ return xp.asarray(out)
+
+ return correlate(volume, _reverse_and_conj(kernel, xp), mode, 'direct')
+ else:
+ raise ValueError("Acceptable method flags are 'auto',"
+ " 'direct', or 'fft'.")
+
+
+def order_filter(a, domain, rank):
+ """
+ Perform an order filter on an N-D array.
+
+ Perform an order filter on the array in. The domain argument acts as a
+ mask centered over each pixel. The non-zero elements of domain are
+ used to select elements surrounding each input pixel which are placed
+ in a list. The list is sorted, and the output for that pixel is the
+ element corresponding to rank in the sorted list.
+
+ Parameters
+ ----------
+ a : ndarray
+ The N-dimensional input array.
+ domain : array_like
+ A mask array with the same number of dimensions as `a`.
+ Each dimension should have an odd number of elements.
+ rank : int
+ A non-negative integer which selects the element from the
+ sorted list (0 corresponds to the smallest element, 1 is the
+ next smallest element, etc.).
+
+ Returns
+ -------
+ out : ndarray
+ The results of the order filter in an array with the same
+ shape as `a`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> x = np.arange(25).reshape(5, 5)
+ >>> domain = np.identity(3)
+ >>> x
+ array([[ 0, 1, 2, 3, 4],
+ [ 5, 6, 7, 8, 9],
+ [10, 11, 12, 13, 14],
+ [15, 16, 17, 18, 19],
+ [20, 21, 22, 23, 24]])
+ >>> signal.order_filter(x, domain, 0)
+ array([[ 0, 0, 0, 0, 0],
+ [ 0, 0, 1, 2, 0],
+ [ 0, 5, 6, 7, 0],
+ [ 0, 10, 11, 12, 0],
+ [ 0, 0, 0, 0, 0]])
+ >>> signal.order_filter(x, domain, 2)
+ array([[ 6, 7, 8, 9, 4],
+ [ 11, 12, 13, 14, 9],
+ [ 16, 17, 18, 19, 14],
+ [ 21, 22, 23, 24, 19],
+ [ 20, 21, 22, 23, 24]])
+
+ """
+ xp = array_namespace(a, domain)
+
+ domain = xp.asarray(domain)
+ for dimsize in domain.shape:
+ if (dimsize % 2) != 1:
+ raise ValueError("Each dimension of domain argument "
+ "should have an odd number of elements.")
+
+ a = xp.asarray(a)
+ if not (
+ xp.isdtype(a.dtype, "integral") or a.dtype in (xp.float32, xp.float64)
+ ):
+ raise ValueError(f"dtype={a.dtype} is not supported by order_filter")
+ result = ndimage.rank_filter(a, rank, footprint=domain, mode='constant')
+ return result
+
+
+def medfilt(volume, kernel_size=None):
+ """
+ Perform a median filter on an N-dimensional array.
+
+ Apply a median filter to the input array using a local window-size
+ given by `kernel_size`. The array will automatically be zero-padded.
+
+ Parameters
+ ----------
+ volume : array_like
+ An N-dimensional input array.
+ kernel_size : array_like, optional
+ A scalar or an N-length list giving the size of the median filter
+ window in each dimension. Elements of `kernel_size` should be odd.
+ If `kernel_size` is a scalar, then this scalar is used as the size in
+ each dimension. Default size is 3 for each dimension.
+
+ Returns
+ -------
+ out : ndarray
+ An array the same size as input containing the median filtered
+ result.
+
+ Warns
+ -----
+ UserWarning
+ If array size is smaller than kernel size along any dimension
+
+ See Also
+ --------
+ scipy.ndimage.median_filter
+ scipy.signal.medfilt2d
+
+ """
+ xp = array_namespace(volume)
+ volume = xp.asarray(volume)
+ if volume.ndim == 0:
+ volume = xpx.atleast_nd(volume, ndim=1, xp=xp)
+
+ if not (xp.isdtype(volume.dtype, "integral") or
+ volume.dtype in [xp.float32, xp.float64]):
+ raise ValueError(f"dtype={volume.dtype} is not supported by medfilt")
+
+ if kernel_size is None:
+ kernel_size = [3] * volume.ndim
+ kernel_size = xp.asarray(kernel_size)
+ if kernel_size.shape == ():
+ kernel_size = xp.repeat(kernel_size, volume.ndim)
+
+ for k in range(volume.ndim):
+ if (kernel_size[k] % 2) != 1:
+ raise ValueError("Each element of kernel_size should be odd.")
+ if any(k > s for k, s in zip(kernel_size, volume.shape)):
+ warnings.warn('kernel_size exceeds volume extent: the volume will be '
+ 'zero-padded.',
+ stacklevel=2)
+
+ size = math.prod(kernel_size)
+ result = ndimage.rank_filter(volume, size // 2, size=kernel_size,
+ mode='constant')
+
+ return result
+
+
+def wiener(im, mysize=None, noise=None):
+ """
+ Perform a Wiener filter on an N-dimensional array.
+
+ Apply a Wiener filter to the N-dimensional array `im`.
+
+ Parameters
+ ----------
+ im : ndarray
+ An N-dimensional array.
+ mysize : int or array_like, optional
+ A scalar or an N-length list giving the size of the Wiener filter
+ window in each dimension. Elements of mysize should be odd.
+ If mysize is a scalar, then this scalar is used as the size
+ in each dimension.
+ noise : float, optional
+ The noise-power to use. If None, then noise is estimated as the
+ average of the local variance of the input.
+
+ Returns
+ -------
+ out : ndarray
+ Wiener filtered result with the same shape as `im`.
+
+ Notes
+ -----
+ This implementation is similar to wiener2 in Matlab/Octave.
+ For more details see [1]_
+
+ References
+ ----------
+ .. [1] Lim, Jae S., Two-Dimensional Signal and Image Processing,
+ Englewood Cliffs, NJ, Prentice Hall, 1990, p. 548.
+
+ Examples
+ --------
+ >>> from scipy.datasets import face
+ >>> from scipy.signal import wiener
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+ >>> img = rng.random((40, 40)) #Create a random image
+ >>> filtered_img = wiener(img, (5, 5)) #Filter the image
+ >>> f, (plot1, plot2) = plt.subplots(1, 2)
+ >>> plot1.imshow(img)
+ >>> plot2.imshow(filtered_img)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(im)
+
+ im = xp.asarray(im)
+ if mysize is None:
+ mysize = [3] * im.ndim
+ mysize_arr = xp.asarray(mysize)
+ if mysize_arr.shape == ():
+ mysize = [mysize] * im.ndim
+
+ # Estimate the local mean
+ size = math.prod(mysize)
+ lMean = correlate(im, xp.ones(mysize), 'same')
+ lsize = float(size)
+ lMean = lMean / lsize
+
+ # Estimate the local variance
+ lVar = (correlate(im ** 2, xp.ones(mysize), 'same') / lsize - lMean ** 2)
+
+ # Estimate the noise power if needed.
+ if noise is None:
+ noise = xp.mean(xp.reshape(lVar, (-1,)), axis=0)
+
+ res = (im - lMean)
+ res *= (1 - noise / lVar)
+ res += lMean
+ out = xp.where(lVar < noise, lMean, res)
+
+ return out
+
+
+def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
+ """
+ Convolve two 2-dimensional arrays.
+
+ Convolve `in1` and `in2` with output size determined by `mode`, and
+ boundary conditions determined by `boundary` and `fillvalue`.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ boundary : str {'fill', 'wrap', 'symm'}, optional
+ A flag indicating how to handle boundaries:
+
+ ``fill``
+ pad input arrays with fillvalue. (default)
+ ``wrap``
+ circular boundary conditions.
+ ``symm``
+ symmetrical boundary conditions.
+
+ fillvalue : scalar, optional
+ Value to fill pad input arrays with. Default is 0.
+
+ Returns
+ -------
+ out : ndarray
+ A 2-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ Examples
+ --------
+ Compute the gradient of an image by 2D convolution with a complex Scharr
+ operator. (Horizontal operator is real, vertical is imaginary.) Use
+ symmetric boundary condition to avoid creating edges at the image
+ boundaries.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy import datasets
+ >>> ascent = datasets.ascent()
+ >>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j],
+ ... [-10+0j, 0+ 0j, +10 +0j],
+ ... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy
+ >>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same')
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15))
+ >>> ax_orig.imshow(ascent, cmap='gray')
+ >>> ax_orig.set_title('Original')
+ >>> ax_orig.set_axis_off()
+ >>> ax_mag.imshow(np.absolute(grad), cmap='gray')
+ >>> ax_mag.set_title('Gradient magnitude')
+ >>> ax_mag.set_axis_off()
+ >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles
+ >>> ax_ang.set_title('Gradient orientation')
+ >>> ax_ang.set_axis_off()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ # NB: do work in NumPy, only convert the output
+
+ in1 = np.asarray(in1)
+ in2 = np.asarray(in2)
+
+ if not in1.ndim == in2.ndim == 2:
+ raise ValueError('convolve2d inputs must both be 2-D arrays')
+
+ if _inputs_swap_needed(mode, in1.shape, in2.shape):
+ in1, in2 = in2, in1
+
+ val = _valfrommode(mode)
+ bval = _bvalfromboundary(boundary)
+ out = _sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue)
+ return xp.asarray(out)
+
+
+def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
+ """
+ Cross-correlate two 2-dimensional arrays.
+
+ Cross correlate `in1` and `in2` with output size determined by `mode`, and
+ boundary conditions determined by `boundary` and `fillvalue`.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear cross-correlation
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ boundary : str {'fill', 'wrap', 'symm'}, optional
+ A flag indicating how to handle boundaries:
+
+ ``fill``
+ pad input arrays with fillvalue. (default)
+ ``wrap``
+ circular boundary conditions.
+ ``symm``
+ symmetrical boundary conditions.
+
+ fillvalue : scalar, optional
+ Value to fill pad input arrays with. Default is 0.
+
+ Returns
+ -------
+ correlate2d : ndarray
+ A 2-dimensional array containing a subset of the discrete linear
+ cross-correlation of `in1` with `in2`.
+
+ Notes
+ -----
+ When using "same" mode with even-length inputs, the outputs of `correlate`
+ and `correlate2d` differ: There is a 1-index offset between them.
+
+ Examples
+ --------
+ Use 2D cross-correlation to find the location of a template in a noisy
+ image:
+
+ >>> import numpy as np
+ >>> from scipy import signal, datasets, ndimage
+ >>> rng = np.random.default_rng()
+ >>> face = datasets.face(gray=True) - datasets.face(gray=True).mean()
+ >>> face = ndimage.zoom(face[30:500, 400:950], 0.5) # extract the face
+ >>> template = np.copy(face[135:165, 140:175]) # right eye
+ >>> template -= template.mean()
+ >>> face = face + rng.standard_normal(face.shape) * 50 # add noise
+ >>> corr = signal.correlate2d(face, template, boundary='symm', mode='same')
+ >>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1,
+ ... figsize=(6, 15))
+ >>> ax_orig.imshow(face, cmap='gray')
+ >>> ax_orig.set_title('Original')
+ >>> ax_orig.set_axis_off()
+ >>> ax_template.imshow(template, cmap='gray')
+ >>> ax_template.set_title('Template')
+ >>> ax_template.set_axis_off()
+ >>> ax_corr.imshow(corr, cmap='gray')
+ >>> ax_corr.set_title('Cross-correlation')
+ >>> ax_corr.set_axis_off()
+ >>> ax_orig.plot(x, y, 'ro')
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+ in1 = np.asarray(in1)
+ in2 = np.asarray(in2)
+
+ if not in1.ndim == in2.ndim == 2:
+ raise ValueError('correlate2d inputs must both be 2-D arrays')
+
+ swapped_inputs = _inputs_swap_needed(mode, in1.shape, in2.shape)
+ if swapped_inputs:
+ in1, in2 = in2, in1
+
+ val = _valfrommode(mode)
+ bval = _bvalfromboundary(boundary)
+ out = _sigtools._convolve2d(in1, in2.conj(), 0, val, bval, fillvalue)
+
+ if swapped_inputs:
+ out = out[::-1, ::-1]
+
+ return xp.asarray(out)
+
+
+def medfilt2d(input, kernel_size=3):
+ """
+ Median filter a 2-dimensional array.
+
+ Apply a median filter to the `input` array using a local window-size
+ given by `kernel_size` (must be odd). The array is zero-padded
+ automatically.
+
+ Parameters
+ ----------
+ input : array_like
+ A 2-dimensional input array.
+ kernel_size : array_like, optional
+ A scalar or a list of length 2, giving the size of the
+ median filter window in each dimension. Elements of
+ `kernel_size` should be odd. If `kernel_size` is a scalar,
+ then this scalar is used as the size in each dimension.
+ Default is a kernel of size (3, 3).
+
+ Returns
+ -------
+ out : ndarray
+ An array the same size as input containing the median filtered
+ result.
+
+ See Also
+ --------
+ scipy.ndimage.median_filter
+
+ Notes
+ -----
+ This is faster than `medfilt` when the input dtype is ``uint8``,
+ ``float32``, or ``float64``; for other types, this falls back to
+ `medfilt`. In some situations, `scipy.ndimage.median_filter` may be
+ faster than this function.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> x = np.arange(25).reshape(5, 5)
+ >>> x
+ array([[ 0, 1, 2, 3, 4],
+ [ 5, 6, 7, 8, 9],
+ [10, 11, 12, 13, 14],
+ [15, 16, 17, 18, 19],
+ [20, 21, 22, 23, 24]])
+
+ # Replaces i,j with the median out of 5*5 window
+
+ >>> signal.medfilt2d(x, kernel_size=5)
+ array([[ 0, 0, 2, 0, 0],
+ [ 0, 3, 7, 4, 0],
+ [ 2, 8, 12, 9, 4],
+ [ 0, 8, 12, 9, 0],
+ [ 0, 0, 12, 0, 0]])
+
+ # Replaces i,j with the median out of default 3*3 window
+
+ >>> signal.medfilt2d(x)
+ array([[ 0, 1, 2, 3, 0],
+ [ 1, 6, 7, 8, 4],
+ [ 6, 11, 12, 13, 9],
+ [11, 16, 17, 18, 14],
+ [ 0, 16, 17, 18, 0]])
+
+ # Replaces i,j with the median out of default 5*3 window
+
+ >>> signal.medfilt2d(x, kernel_size=[5,3])
+ array([[ 0, 1, 2, 3, 0],
+ [ 0, 6, 7, 8, 3],
+ [ 5, 11, 12, 13, 8],
+ [ 5, 11, 12, 13, 8],
+ [ 0, 11, 12, 13, 0]])
+
+ # Replaces i,j with the median out of default 3*5 window
+
+ >>> signal.medfilt2d(x, kernel_size=[3,5])
+ array([[ 0, 0, 2, 1, 0],
+ [ 1, 5, 7, 6, 3],
+ [ 6, 10, 12, 11, 8],
+ [11, 15, 17, 16, 13],
+ [ 0, 15, 17, 16, 0]])
+
+ # As seen in the examples,
+ # kernel numbers must be odd and not exceed original array dim
+
+ """
+ xp = array_namespace(input)
+
+ image = np.asarray(input)
+
+ # checking dtype.type, rather than just dtype, is necessary for
+ # excluding np.longdouble with MS Visual C.
+ if image.dtype.type not in (np.ubyte, np.float32, np.float64):
+ return xp.asarray(medfilt(image, kernel_size))
+
+ if kernel_size is None:
+ kernel_size = [3] * 2
+ kernel_size = np.asarray(kernel_size)
+ if kernel_size.shape == ():
+ kernel_size = np.repeat(kernel_size.item(), 2)
+
+ for size in kernel_size:
+ if (size % 2) != 1:
+ raise ValueError("Each element of kernel_size should be odd.")
+
+ result_np = _sigtools._medfilt2d(image, kernel_size)
+ return xp.asarray(result_np)
+
+
+def lfilter(b, a, x, axis=-1, zi=None):
+ """
+ Filter data along one-dimension with an IIR or FIR filter.
+
+ Filter a data sequence, `x`, using a digital filter. This works for many
+ fundamental data types (including Object type). The filter is a direct
+ form II transposed implementation of the standard difference equation
+ (see Notes).
+
+ The function `sosfilt` (and filter design using ``output='sos'``) should be
+ preferred over `lfilter` for most filtering tasks, as second-order sections
+ have fewer numerical problems.
+
+ Parameters
+ ----------
+ b : array_like
+ The numerator coefficient vector in a 1-D sequence.
+ a : array_like
+ The denominator coefficient vector in a 1-D sequence. If ``a[0]``
+ is not 1, then both `a` and `b` are normalized by ``a[0]``.
+ x : array_like
+ An N-dimensional input array.
+ axis : int, optional
+ The axis of the input data array along which to apply the
+ linear filter. The filter is applied to each subarray along
+ this axis. Default is -1.
+ zi : array_like, optional
+ Initial conditions for the filter delays. It is a vector
+ (or array of vectors for an N-dimensional input) of length
+ ``max(len(a), len(b)) - 1``. If `zi` is None or is not given then
+ initial rest is assumed. See `lfiltic` for more information.
+
+ Returns
+ -------
+ y : array
+ The output of the digital filter.
+ zf : array, optional
+ If `zi` is None, this is not returned, otherwise, `zf` holds the
+ final filter delay values.
+
+ See Also
+ --------
+ lfiltic : Construct initial conditions for `lfilter`.
+ lfilter_zi : Compute initial state (steady state of step response) for
+ `lfilter`.
+ filtfilt : A forward-backward filter, to obtain a filter with zero phase.
+ savgol_filter : A Savitzky-Golay filter.
+ sosfilt: Filter data using cascaded second-order sections.
+ sosfiltfilt: A forward-backward filter using second-order sections.
+
+ Notes
+ -----
+ The filter function is implemented as a direct II transposed structure.
+ This means that the filter implements::
+
+ a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M]
+ - a[1]*y[n-1] - ... - a[N]*y[n-N]
+
+ where `M` is the degree of the numerator, `N` is the degree of the
+ denominator, and `n` is the sample number. It is implemented using
+ the following difference equations (assuming M = N)::
+
+ a[0]*y[n] = b[0] * x[n] + d[0][n-1]
+ d[0][n] = b[1] * x[n] - a[1] * y[n] + d[1][n-1]
+ d[1][n] = b[2] * x[n] - a[2] * y[n] + d[2][n-1]
+ ...
+ d[N-2][n] = b[N-1]*x[n] - a[N-1]*y[n] + d[N-1][n-1]
+ d[N-1][n] = b[N] * x[n] - a[N] * y[n]
+
+ where `d` are the state variables.
+
+ The rational transfer function describing this filter in the
+ z-transform domain is::
+
+ -1 -M
+ b[0] + b[1]z + ... + b[M] z
+ Y(z) = -------------------------------- X(z)
+ -1 -N
+ a[0] + a[1]z + ... + a[N] z
+
+ Examples
+ --------
+ Generate a noisy signal to be filtered:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+ >>> t = np.linspace(-1, 1, 201)
+ >>> x = (np.sin(2*np.pi*0.75*t*(1-t) + 2.1) +
+ ... 0.1*np.sin(2*np.pi*1.25*t + 1) +
+ ... 0.18*np.cos(2*np.pi*3.85*t))
+ >>> xn = x + rng.standard_normal(len(t)) * 0.08
+
+ Create an order 3 lowpass butterworth filter:
+
+ >>> b, a = signal.butter(3, 0.05)
+
+ Apply the filter to xn. Use lfilter_zi to choose the initial condition of
+ the filter:
+
+ >>> zi = signal.lfilter_zi(b, a)
+ >>> z, _ = signal.lfilter(b, a, xn, zi=zi*xn[0])
+
+ Apply the filter again, to have a result filtered at an order the same as
+ filtfilt:
+
+ >>> z2, _ = signal.lfilter(b, a, z, zi=zi*z[0])
+
+ Use filtfilt to apply the filter:
+
+ >>> y = signal.filtfilt(b, a, xn)
+
+ Plot the original signal and the various filtered versions:
+
+ >>> plt.figure
+ >>> plt.plot(t, xn, 'b', alpha=0.75)
+ >>> plt.plot(t, z, 'r--', t, z2, 'r', t, y, 'k')
+ >>> plt.legend(('noisy signal', 'lfilter, once', 'lfilter, twice',
+ ... 'filtfilt'), loc='best')
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(b, a, x, zi)
+
+ b = np.atleast_1d(b)
+ a = np.atleast_1d(a)
+ x = np.asarray(x)
+ if zi is not None:
+ zi = np.asarray(zi)
+
+ if not (b.ndim == 1 and xp_size(b) > 0):
+ raise ValueError(f"Parameter b is not a non-empty 1d array, since {b.shape=}!")
+ if not (a.ndim == 1 and xp_size(a) > 0):
+ raise ValueError(f"Parameter a is not a non-empty 1d array, since {a.shape=}!")
+
+ if len(a) == 1:
+ # This path only supports types fdgFDGO to mirror _linear_filter below.
+ # Any of b, a, x, or zi can set the dtype, but there is no default
+ # casting of other types; instead a NotImplementedError is raised.
+ b = np.asarray(b)
+ a = np.asarray(a)
+ x = _validate_x(x)
+ inputs = [b, a, x]
+ if zi is not None:
+ # _linear_filter does not broadcast zi, but does do expansion of
+ # singleton dims.
+ zi = np.asarray(zi)
+ if zi.ndim != x.ndim:
+ raise ValueError("Dimensions of parameters x and zi must match, but " +
+ f"{x.ndim=}, {zi.ndim=}!")
+ expected_shape = list(x.shape)
+ expected_shape[axis] = b.shape[0] - 1
+ expected_shape = tuple(expected_shape)
+ # check the trivial case where zi is the right shape first
+ if zi.shape != expected_shape:
+ strides = zi.ndim * [None]
+ if axis < 0:
+ axis += zi.ndim
+ for k in range(zi.ndim):
+ if k == axis and zi.shape[k] == expected_shape[k]:
+ strides[k] = zi.strides[k]
+ elif k != axis and zi.shape[k] == expected_shape[k]:
+ strides[k] = zi.strides[k]
+ elif k != axis and zi.shape[k] == 1:
+ strides[k] = 0
+ else:
+ raise ValueError('Unexpected shape for parameter zi: expected '
+ f'{expected_shape}, found {zi.shape}.')
+ zi = np.lib.stride_tricks.as_strided(zi, expected_shape,
+ strides)
+ inputs.append(zi)
+ dtype = np.result_type(*inputs)
+
+ if dtype.char not in 'fdgFDGO':
+ raise NotImplementedError("Parameter's dtypes produced result type " +
+ f"'{dtype}', which is not supported!")
+
+ b = np.array(b, dtype=dtype)
+ a = np.asarray(a, dtype=dtype)
+ b /= a[0]
+ x = np.asarray(x, dtype=dtype)
+
+ out_full = np.apply_along_axis(lambda y: np.convolve(b, y), axis, x)
+ ind = out_full.ndim * [slice(None)]
+ if zi is not None:
+ ind[axis] = slice(zi.shape[axis])
+ out_full[tuple(ind)] += zi
+
+ ind[axis] = slice(out_full.shape[axis] - len(b) + 1)
+ out = out_full[tuple(ind)]
+
+ if zi is None:
+ return xp.asarray(out)
+ else:
+ ind[axis] = slice(out_full.shape[axis] - len(b) + 1, None)
+ zf = out_full[tuple(ind)]
+ return xp.asarray(out), xp.asarray(zf)
+ else:
+ if zi is None:
+ result =_sigtools._linear_filter(b, a, x, axis)
+ return xp.asarray(result)
+ else:
+ out, zf = _sigtools._linear_filter(b, a, x, axis, zi)
+ return xp.asarray(out), xp.asarray(zf)
+
+
+def lfiltic(b, a, y, x=None):
+ """
+ Construct initial conditions for lfilter given input and output vectors.
+
+ Given a linear filter (b, a) and initial conditions on the output `y`
+ and the input `x`, return the initial conditions on the state vector zi
+ which is used by `lfilter` to generate the output given the input.
+
+ Parameters
+ ----------
+ b : array_like
+ Linear filter term.
+ a : array_like
+ Linear filter term.
+ y : array_like
+ Initial conditions.
+
+ If ``N = len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``.
+
+ If `y` is too short, it is padded with zeros.
+ x : array_like, optional
+ Initial conditions.
+
+ If ``M = len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``.
+
+ If `x` is not given, its initial conditions are assumed zero.
+
+ If `x` is too short, it is padded with zeros.
+
+ Returns
+ -------
+ zi : ndarray
+ The state vector ``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``,
+ where ``K = max(M, N)``.
+
+ See Also
+ --------
+ lfilter, lfilter_zi
+
+ """
+ xp = array_namespace(a, b, y, x)
+
+ a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
+ b = xpx.atleast_nd(xp.asarray(b), ndim=1, xp=xp)
+ if a.ndim > 1:
+ raise ValueError('Filter coefficients `a` must be 1-D.')
+ if b.ndim > 1:
+ raise ValueError('Filter coefficients `b` must be 1-D.')
+ N = a.shape[0] - 1
+ M = b.shape[0] - 1
+ K = max(M, N)
+ y = xp.asarray(y)
+
+ if N < 0:
+ raise ValueError("There must be at least one `a` coefficient.")
+
+ if x is None:
+ result_type = xp.result_type(b, a, y)
+ if xp.isdtype(result_type, ('bool', 'integral')): #'bui':
+ result_type = xp.float64
+ x = xp.zeros(M, dtype=result_type)
+ else:
+ x = xp.asarray(x)
+
+ result_type = xp.result_type(b, a, y, x)
+ if xp.isdtype(result_type, ('bool', 'integral')): #'bui':
+ result_type = xp.float64
+ x = xp.astype(x, result_type)
+
+ L = xp_size(x)
+ if L < M:
+ x = xp.concat((x, xp.zeros(M - L)))
+
+ y = xp.astype(y, result_type)
+ zi = xp.zeros(K, dtype=result_type)
+
+ L = xp_size(y)
+ if L < N:
+ y = xp.concat((y, xp.zeros(N - L)))
+
+ for m in range(M):
+ zi[m] = xp.sum(b[m + 1:] * x[:M - m], axis=0)
+
+ for m in range(N):
+ zi[m] -= xp.sum(a[m + 1:] * y[:N - m], axis=0)
+
+ if a[0] != 1.:
+ if a[0] == 0.:
+ raise ValueError("First `a` filter coefficient must be non-zero.")
+ zi /= a[0]
+
+ return zi
+
+
+def deconvolve(signal, divisor):
+ """Deconvolves ``divisor`` out of ``signal`` using inverse filtering.
+
+ Returns the quotient and remainder such that
+ ``signal = convolve(divisor, quotient) + remainder``
+
+ Parameters
+ ----------
+ signal : (N,) array_like
+ Signal data, typically a recorded signal
+ divisor : (N,) array_like
+ Divisor data, typically an impulse response or filter that was
+ applied to the original signal
+
+ Returns
+ -------
+ quotient : ndarray
+ Quotient, typically the recovered original signal
+ remainder : ndarray
+ Remainder
+
+ See Also
+ --------
+ numpy.polydiv : performs polynomial division (same operation, but
+ also accepts poly1d objects)
+
+ Examples
+ --------
+ Deconvolve a signal that's been filtered:
+
+ >>> from scipy import signal
+ >>> original = [0, 1, 0, 0, 1, 1, 0, 0]
+ >>> impulse_response = [2, 1]
+ >>> recorded = signal.convolve(impulse_response, original)
+ >>> recorded
+ array([0, 2, 1, 0, 2, 3, 1, 0, 0])
+ >>> recovered, remainder = signal.deconvolve(recorded, impulse_response)
+ >>> recovered
+ array([ 0., 1., 0., 0., 1., 1., 0., 0.])
+ >>> remainder
+ array([0., 0., 0., 0., 0., 0., 0., 0., 0.])
+ """
+ xp = array_namespace(signal, divisor)
+
+ num = xpx.atleast_nd(xp.asarray(signal), ndim=1, xp=xp)
+ den = xpx.atleast_nd(xp.asarray(divisor), ndim=1, xp=xp)
+ if not (num.ndim == 1 and xp_size(num) > 0):
+ raise ValueError("Parameter signal must be non-empty 1d array, " +
+ f"but its shape is {num.shape}!")
+ if not (den.ndim == 1 and xp_size(den) > 0):
+ raise ValueError("Parameter divisor must be non-empty 1d array, " +
+ f"but its shape is {den.shape}!")
+ N = num.shape[0]
+ D = den.shape[0]
+ if D > N:
+ quot = []
+ rem = num
+ else:
+ input = xp.zeros(N - D + 1, dtype=xp.float64)
+ input = xpx.at(input)[0].set(1)
+ quot = lfilter(num, den, input)
+ rem = num - convolve(den, quot, mode='full')
+ return quot, rem
+
+
+def hilbert(x, N=None, axis=-1):
+ r"""FFT-based computation of the analytic signal.
+
+ The analytic signal is calculated by zeroing out the negative frequencies and
+ doubling the amplitudes of the positive frequencies in the FFT domain.
+ The imaginary part of the result is the hilbert transform of the real-valued input
+ signal.
+
+ The transformation is done along the last axis by default.
+
+ For numpy arrays, `scipy.fft.set_workers` can be used to change the number of
+ workers used for the FFTs.
+
+ Parameters
+ ----------
+ x : array_like
+ Signal data. Must be real.
+ N : int, optional
+ Number of output samples. `x` is initially cropped or zero-padded to length
+ `N` along `axis`. Default: ``x.shape[axis]``
+ axis : int, optional
+ Axis along which to do the transformation. Default: -1.
+
+ Returns
+ -------
+ xa : ndarray
+ Analytic signal of `x`, of each 1-D array along `axis`
+
+ Notes
+ -----
+ The analytic signal ``x_a(t)`` of a real-valued signal ``x(t)``
+ can be expressed as [1]_
+
+ .. math:: x_a = F^{-1}(F(x) 2U) = x + i y\ ,
+
+ where `F` is the Fourier transform, `U` the unit step function,
+ and `y` the Hilbert transform of `x`. [2]_
+
+ In other words, the negative half of the frequency spectrum is zeroed
+ out, turning the real-valued signal into a complex-valued signal. The Hilbert
+ transformed signal can be obtained from ``np.imag(hilbert(x))``, and the
+ original signal from ``np.real(hilbert(x))``.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Analytic signal".
+ https://en.wikipedia.org/wiki/Analytic_signal
+ .. [2] Wikipedia, "Hilbert Transform".
+ https://en.wikipedia.org/wiki/Hilbert_transform
+ .. [3] Leon Cohen, "Time-Frequency Analysis", 1995. Chapter 2.
+ .. [4] Alan V. Oppenheim, Ronald W. Schafer. Discrete-Time Signal
+ Processing, Third Edition, 2009. Chapter 12.
+ ISBN 13: 978-1292-02572-8
+
+ See Also
+ --------
+ envelope: Compute envelope of a real- or complex-valued signal.
+
+ Examples
+ --------
+ In this example we use the Hilbert transform to determine the amplitude
+ envelope and instantaneous frequency of an amplitude-modulated signal.
+
+ Let's create a chirp of which the frequency increases from 20 Hz to 100 Hz and
+ apply an amplitude modulation:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import hilbert, chirp
+ ...
+ >>> duration, fs = 1, 400 # 1 s signal with sampling frequency of 400 Hz
+ >>> t = np.arange(int(fs*duration)) / fs # timestamps of samples
+ >>> signal = chirp(t, 20.0, t[-1], 100.0)
+ >>> signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) )
+
+ The amplitude envelope is given by the magnitude of the analytic signal. The
+ instantaneous frequency can be obtained by differentiating the
+ instantaneous phase in respect to time. The instantaneous phase corresponds
+ to the phase angle of the analytic signal.
+
+ >>> analytic_signal = hilbert(signal)
+ >>> amplitude_envelope = np.abs(analytic_signal)
+ >>> instantaneous_phase = np.unwrap(np.angle(analytic_signal))
+ >>> instantaneous_frequency = np.diff(instantaneous_phase) / (2.0*np.pi) * fs
+ ...
+ >>> fig, (ax0, ax1) = plt.subplots(nrows=2, sharex='all', tight_layout=True)
+ >>> ax0.set_title("Amplitude-modulated Chirp Signal")
+ >>> ax0.set_ylabel("Amplitude")
+ >>> ax0.plot(t, signal, label='Signal')
+ >>> ax0.plot(t, amplitude_envelope, label='Envelope')
+ >>> ax0.legend()
+ >>> ax1.set(xlabel="Time in seconds", ylabel="Frequency in Hz", ylim=(0, 120))
+ >>> ax1.plot(t[1:], instantaneous_frequency, 'C2-',
+ ... label='Instantaneous Frequency')
+ >>> ax1.legend()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(x)
+
+ x = xp.asarray(x)
+ if xp.isdtype(x.dtype, 'complex floating'):
+ raise ValueError("x must be real.")
+
+ if N is None:
+ N = x.shape[axis]
+ if N <= 0:
+ raise ValueError("N must be positive.")
+
+ Xf = sp_fft.fft(x, N, axis=axis)
+ Xf = xp.moveaxis(Xf, axis, -1)
+ if N % 2 == 0:
+ Xf = xpx.at(Xf)[..., 1: N // 2].multiply(2.0)
+ Xf = xpx.at(Xf)[..., N // 2 + 1:N].set(0.0)
+ else:
+ Xf = xpx.at(Xf)[..., 1: (N + 1) // 2].multiply(2.0)
+ Xf = xpx.at(Xf)[..., (N + 1) // 2:N].set(0.0)
+
+ Xf = xp.moveaxis(Xf, -1, axis)
+ x = sp_fft.ifft(Xf, axis=axis)
+ return x
+
+
+def hilbert2(x, N=None, axes=(-2, -1)):
+ r"""Compute the '2-D' analytic signal of `x`.
+
+ The 2-D analytic signal is calculated as a so-called "single-orthant" transform.
+ This is achieved by applying one-dimensional Hilbert functions (as in
+ `~scipy.signal.hilbert`) to the first and to the second array axis in Fourier space.
+
+ For NumPy arrays, `scipy.fft.set_workers` can be used to change the number of
+ workers used for the FFTs.
+
+ Parameters
+ ----------
+ x : array_like
+ Input signal. Must be at least two-dimensional.
+ N : int or tuple of two ints, optional
+ Number of output samples. `x` is initially cropped or zero-padded to length
+ `N` along `axes`. Default: ``x.shape[i] for i in axes``
+ axes : tuple of two ints, optional
+ Axes along which to do the transformation. Default: (-2, -1).
+
+ .. versionchanged:: 1.17
+
+ Added `axes` parameter
+
+ Returns
+ -------
+ xa : ndarray
+ Analytic signal of `x` taken along given axes.
+
+ Notes
+ -----
+ The "single-orthant" transform, as defined in [2]_, is calculated by performing the
+ following steps:
+
+ 1. Calculate the two-dimensional FFT of the input, i.e.,
+
+ .. math::
+
+ X[p,q] = \sum_{k,l=0}^{N_0,N_1} x[k,l]\,
+ e^{-2j\pi k p/N_0}\, e^{-2j\pi l q/N_1}
+
+ 2. Zero negative frequency bins and double their positive counterparts, i.e.,
+
+ .. math::
+
+ X_a[p,q] = \big(1 + s_{N_0}(p)\big) \big(1 + s_{N_1}(q)\big) X[p,q]
+
+ with :math:`s_N(.)` being a modified sign function defined as
+
+ .. math::
+
+ s_N(p) := \begin{cases}
+ -1 & \text{ for } p < 0\ ,\\
+ \phantom{-}0 & \text{ for } p = 0\ ,\\
+ +1 & \text{ for } 1 \leq p < (N+1) // 2\ ,\\
+ \phantom{-}0 & \text{ elsewhere.}
+ \end{cases}
+
+ The limitation of the ":math:`+1`" case to the range of ``[1:(N+1)//2]``
+ accounts for the unpaired Nyquist frequency bin at :math:`N/2` for even
+ :math:`N`. Note that :math:`X_a[p] = \big(1 + s_N(p)\big) X[p]` is the
+ one-dimensional Hilbert function (as in `~scipy.signal.hilbert`) in Fourier
+ space.
+
+ 3. Produce the analytic signal by performing the inverse FFT, i.e.,
+
+ .. math::
+
+ x_a[k, l] = \frac{1}{N_0 N_1}
+ \sum_{p,q=0}^{N_0,N_1} X_a[p,q]\, e^{2j\pi k p/N_0}\, e^{2j\pi l q/N_1}
+
+ The "single-orthant" transform is not the only possible definition of an analytic
+ signal in multiple dimensions (as noted in [1]_). Consult [3]_ for a description of
+ properties that this 2-D transform does and does not share with the 1-D transform.
+ The second example below shows one of the downsides of this approach.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Analytic signal",
+ https://en.wikipedia.org/wiki/Analytic_signal
+ .. [2] Hahn, Stefan L. "Multidimensional complex signals with
+ single-orthant spectra." Proceedings of the IEEE 80.8
+ (1992): 1287-1300.
+ `PDF `__
+ .. [3] Bülow, Thomas, and Gerald Sommer. "A novel approach to the 2D analytic
+ signal." In International Conference on Computer Analysis of Images and
+ Patterns, pp. 25-32. Berlin, Heidelberg: Springer Berlin Heidelberg, 1999.
+ `PDF `__
+
+ Examples
+ --------
+ The following example calculates the two-dimensional analytic signal from a single
+ impulse with an added constant offset. The impulse produces an FFT where each bin
+ has a value of one and the constant offset component produces only a non-zero
+ component at the ``(0,0)`` bin.
+
+ >>> import numpy as np
+ >>> from scipy.fft import fft2, fftshift, ifftshift
+ >>> from scipy.signal import hilbert2
+ ...
+ >>> # Input signal is unit impulse with a constant offset:
+ >>> x = np.ones((5, 5)) / 5
+ >>> x[0, 0] += 1
+ ...
+ >>> X = fftshift(fft2(x)) # Zero frequency bin is at center
+ >>> print(X)
+ [[1.-0.j 1.-0.j 1.-0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 1.-0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 6.-0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 1.+0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 1.+0.j 1.+0.j 1.+0.j]]
+ >>> x_a = hilbert2(x)
+ >>> X_a = fftshift(fft2(x_a))
+ >>> print(np.round(X_a, 3))
+ [[ 0.+0.j 0.+0.j -0.+0.j 0.+0.j 0.+0.j]
+ [ 0.+0.j 0.+0.j -0.+0.j 0.+0.j 0.+0.j]
+ [ 0.+0.j 0.+0.j 6.+0.j 2.+0.j 2.+0.j]
+ [ 0.+0.j 0.+0.j 2.+0.j 4.+0.j 4.+0.j]
+ [ 0.+0.j 0.+0.j 2.+0.j 4.+0.j 4.+0.j]]
+
+ The FFT of the result illustrates that the values of the lower right quadrant (or
+ orthant) with purely positive frequency bins have been quadrupled. The values at its
+ borders, where only one frequency component is zero, are doubled. The zero frequency
+ bin ``(0, 0)`` has not been altered. All other quadrants have been set to zero.
+
+ This second example illustrates a problem with the "single-orthant" convention. A
+ purely real signal can produce an analytic signal which is completely zero:
+
+ >>> from scipy.fft import fft2, fftshift, ifft2, ifftshift
+ >>> from scipy.signal import hilbert2
+ ...
+ >>> # Create a real signal by ensuring `Z[-p,-q] == np.conj(Z[p,q])` holds:
+ >>> Z = np.array([[0, 0, 0, 0, 0],
+ ... [0, 0, 0, 1, 0],
+ ... [0, 0, 0, 0, 0],
+ ... [0, 1, 0, 0, 0],
+ ... [0, 0, 0, 0, 0]]) * 25
+ >>> z = ifft2(ifftshift(Z))
+ >>> np.allclose(z.imag, 0) # z is a real signal
+ True
+ >>> np.sum(z.real**2) # z.real is non-zero
+ np.float64(50.0)
+ >>> z_a = hilbert2(z.real)
+ >>> np.allclose(z_a, 0) # analytic signal is zero
+ True
+
+ """
+ xp = array_namespace(x)
+ x = xpx.atleast_nd(xp.asarray(x), ndim=2, xp=xp)
+ if xp.isdtype(x.dtype, 'complex floating'):
+ raise ValueError("x must be real.")
+ if len(axes) != 2:
+ raise ValueError("axes must be a tuple of length 2")
+ if axes[0] == axes[1]:
+ raise ValueError("axes must contain 2 distinct axes")
+
+ if N is None:
+ N = (x.shape[axes[0]], x.shape[axes[1]])
+ elif isinstance(N, int):
+ if N <= 0:
+ raise ValueError("N must be positive.")
+ N = (N, N)
+ elif len(N) != 2 or np.any(np.asarray(N) <= 0):
+ raise ValueError("When given as a tuple, N must hold exactly "
+ "two positive integers")
+
+ Xf = sp_fft.fft2(x, N, axes=axes)
+ Xf = xp.moveaxis(Xf, axes, (-2, -1))
+ k0, k1 = (N[0] + 1) // 2, (N[1] + 1) // 2
+
+ if k0 > 1: # condition k0 > 1 needed for Dask backend
+ Xf = xpx.at(Xf)[..., 1:k0, :].multiply(2.0)
+ if k1 > 1: # condition k1 > 1 needed for Dask backend
+ Xf = xpx.at(Xf)[..., :, 1:k1].multiply(2.0)
+ Xf = xpx.at(Xf)[..., k0:, :].set(0.0)
+ Xf = xpx.at(Xf)[..., :, k1:].set(0.0)
+
+ Xf = xp.moveaxis(Xf, (-2, -1), axes)
+ x = sp_fft.ifft2(Xf, axes=axes)
+ return x
+
+
+def envelope(z, bp_in: tuple[int | None, int | None] = (1, None), *,
+ n_out: int | None = None, squared: bool = False,
+ residual: Literal['lowpass', 'all', None] = 'lowpass',
+ axis: int = -1):
+ r"""Compute the envelope of a real- or complex-valued signal.
+
+ Parameters
+ ----------
+ z : ndarray
+ Real- or complex-valued input signal, which is assumed to be made up of ``n``
+ samples and having sampling interval ``T``. `z` may also be a multidimensional
+ array with the time axis being defined by `axis`.
+ bp_in : tuple[int | None, int | None], optional
+ 2-tuple defining the frequency band ``bp_in[0]:bp_in[1]`` of the input filter.
+ The corner frequencies are specified as integer multiples of ``1/(n*T)`` with
+ ``-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2`` being the allowed frequency range.
+ ``None`` entries are replaced with ``-n//2`` or ``(n+1)//2`` respectively. The
+ default of ``(1, None)`` removes the mean value as well as the negative
+ frequency components.
+ n_out : int | None, optional
+ If not ``None`` the output will be resampled to `n_out` samples. The default
+ of ``None`` sets the output to the same length as the input `z`.
+ squared : bool, optional
+ If set, the square of the envelope is returned. The bandwidth of the squared
+ envelope is often smaller than the non-squared envelope bandwidth due to the
+ nonlinear nature of the utilized absolute value function. I.e., the embedded
+ square root function typically produces addiational harmonics.
+ The default is ``False``.
+ residual : Literal['lowpass', 'all', None], optional
+ This option determines what kind of residual, i.e., the signal part which the
+ input bandpass filter removes, is returned. ``'all'`` returns everything except
+ the contents of the frequency band ``bp_in[0]:bp_in[1]``, ``'lowpass'``
+ returns the contents of the frequency band ``< bp_in[0]``. If ``None`` then
+ only the envelope is returned. Default: ``'lowpass'``.
+ axis : int, optional
+ Axis of `z` over which to compute the envelope. Default is last the axis.
+
+ Returns
+ -------
+ ndarray
+ If parameter `residual` is ``None`` then an array ``z_env`` with the same shape
+ as the input `z` is returned, containing its envelope. Otherwise, an array with
+ shape ``(2, *z.shape)``, containing the arrays ``z_env`` and ``z_res``, stacked
+ along the first axis, is returned.
+ It allows unpacking, i.e., ``z_env, z_res = envelope(z, residual='all')``.
+ The residual ``z_res`` contains the signal part which the input bandpass filter
+ removed, depending on the parameter `residual`. Note that for real-valued
+ signals, a real-valued residual is returned. Hence, the negative frequency
+ components of `bp_in` are ignored.
+
+ Notes
+ -----
+ Any complex-valued signal :math:`z(t)` can be described by a real-valued
+ instantaneous amplitude :math:`a(t)` and a real-valued instantaneous phase
+ :math:`\phi(t)`, i.e., :math:`z(t) = a(t) \exp\!\big(j \phi(t)\big)`. The
+ envelope is defined as the absolute value of the amplitude :math:`|a(t)| = |z(t)|`,
+ which is at the same time the absolute value of the signal. Hence, :math:`|a(t)|`
+ "envelopes" the class of all signals with amplitude :math:`a(t)` and arbitrary
+ phase :math:`\phi(t)`.
+ For real-valued signals, :math:`x(t) = a(t) \cos\!\big(\phi(t)\big)` is the
+ analogous formulation. Hence, :math:`|a(t)|` can be determined by converting
+ :math:`x(t)` into an analytic signal :math:`z_a(t)` by means of a Hilbert
+ transform, i.e.,
+ :math:`z_a(t) = a(t) \cos\!\big(\phi(t)\big) + j a(t) \sin\!\big(\phi(t) \big)`,
+ which produces a complex-valued signal with the same envelope :math:`|a(t)|`.
+
+ The implementation is based on computing the FFT of the input signal and then
+ performing the necessary operations in Fourier space. Hence, the typical :ref:`FFT
+ caveats ` need to be taken into account. The frequency
+ spacing ``1 / (n*T)`` for corner frequencies of the bandpass filter corresponds to
+ the frequencies produced by ``scipy.fft.fftfreq(len(z), T)``.
+
+ If the envelope of a complex-valued signal `z` with no bandpass filtering is
+ desired, i.e., ``bp_in=(None, None)``, then the envelope corresponds to the
+ absolute value. Hence, it is more efficient to use ``np.abs(z)`` instead of this
+ function.
+
+ Although computing the envelope based on the analytic signal [1]_ is the natural
+ method for real-valued signals, other methods are also frequently used. The most
+ popular alternative is probably the so-called "square-law" envelope detector and
+ its relatives [2]_. They do not always compute the correct result for all kinds of
+ signals, but are usually correct and typically computationally more efficient for
+ most kinds of narrowband signals. The definition for an envelope presented here is
+ common where instantaneous amplitude and phase are of interest (e.g., as described
+ in [3]_). There exist also other concepts, which rely on the general mathematical
+ idea of an envelope [4]_: A pragmatic approach is to determine all upper and lower
+ signal peaks and use a spline interpolation to determine the curves [5]_.
+
+
+ References
+ ----------
+ .. [1] "Analytic Signal", Wikipedia,
+ https://en.wikipedia.org/wiki/Analytic_signal
+ .. [2] Lyons, Richard, "Digital envelope detection: The good, the bad, and the
+ ugly", IEEE Signal Processing Magazine 34.4 (2017): 183-187.
+ `PDF `__
+ .. [3] T.G. Kincaid, "The complex representation of signals.",
+ TIS R67# MH5, General Electric Co. (1966).
+ `PDF `__
+ .. [4] "Envelope (mathematics)", Wikipedia,
+ https://en.wikipedia.org/wiki/Envelope_(mathematics)
+ .. [5] Yang, Yanli. "A signal theoretic approach for envelope analysis of
+ real-valued signals." IEEE Access 5 (2017): 5623-5630.
+ `PDF